@kortix/sdk 0.14.2 → 0.14.4

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 (351) hide show
  1. package/README.md +42 -12
  2. package/dist/browser/session-sync/server-transcript-mirror.d.ts.map +1 -1
  3. package/dist/browser/session-sync/server-transcript-mirror.js +8 -1
  4. package/dist/browser/session-sync/server-transcript-mirror.js.map +1 -1
  5. package/dist/browser/session-sync/session-sync-registry.d.ts +6 -5
  6. package/dist/browser/session-sync/session-sync-registry.d.ts.map +1 -1
  7. package/dist/browser/session-sync/session-sync-registry.js +37 -5
  8. package/dist/browser/session-sync/session-sync-registry.js.map +1 -1
  9. package/dist/browser/stores/sync-store.d.ts +2 -2
  10. package/dist/browser/stores/sync-store.d.ts.map +1 -1
  11. package/dist/browser/stores/sync-store.js +22 -9
  12. package/dist/browser/stores/sync-store.js.map +1 -1
  13. package/dist/core/agents/composer-agents.js +1 -1
  14. package/dist/core/agents/composer-agents.js.map +1 -1
  15. package/dist/core/capture/rules.d.ts +6 -4
  16. package/dist/core/capture/rules.d.ts.map +1 -1
  17. package/dist/core/capture/rules.js +7 -5
  18. package/dist/core/capture/rules.js.map +1 -1
  19. package/dist/core/client/capture.d.ts +2 -0
  20. package/dist/core/client/capture.d.ts.map +1 -1
  21. package/dist/core/client/capture.js.map +1 -1
  22. package/dist/core/client/facade-catalog.d.ts +3 -0
  23. package/dist/core/client/facade-catalog.d.ts.map +1 -1
  24. package/dist/core/client/facade-catalog.js +3 -0
  25. package/dist/core/client/facade-catalog.js.map +1 -1
  26. package/dist/core/client/kortix.d.ts +67 -1
  27. package/dist/core/client/kortix.d.ts.map +1 -1
  28. package/dist/core/client/kortix.js +2 -0
  29. package/dist/core/client/kortix.js.map +1 -1
  30. package/dist/core/client/project-core.d.ts +14 -0
  31. package/dist/core/client/project-core.d.ts.map +1 -1
  32. package/dist/core/client/project-core.js +6 -0
  33. package/dist/core/client/project-core.js.map +1 -1
  34. package/dist/core/client/project-operations-admin.d.ts +45 -0
  35. package/dist/core/client/project-operations-admin.d.ts.map +1 -1
  36. package/dist/core/client/project-operations-admin.js +15 -0
  37. package/dist/core/client/project-operations-admin.js.map +1 -1
  38. package/dist/core/client/project-operations-review.d.ts +5 -0
  39. package/dist/core/client/project-operations-review.d.ts.map +1 -1
  40. package/dist/core/client/project-operations-workspace.d.ts +5 -0
  41. package/dist/core/client/project-operations-workspace.d.ts.map +1 -1
  42. package/dist/core/client/project-operations.d.ts +50 -0
  43. package/dist/core/client/project-operations.d.ts.map +1 -1
  44. package/dist/core/client/project-operations.js +4 -0
  45. package/dist/core/client/project-operations.js.map +1 -1
  46. package/dist/core/client/project-platform-security.d.ts +1 -1
  47. package/dist/core/client/project-platform-settings.d.ts +1 -1
  48. package/dist/core/files/client.d.ts +1 -1
  49. package/dist/core/files/client.js +1 -1
  50. package/dist/core/http/api/errors.d.ts +26 -0
  51. package/dist/core/http/api/errors.d.ts.map +1 -1
  52. package/dist/core/http/api/errors.js +36 -0
  53. package/dist/core/http/api/errors.js.map +1 -1
  54. package/dist/core/http/response-error.d.ts.map +1 -1
  55. package/dist/core/http/response-error.js +6 -2
  56. package/dist/core/http/response-error.js.map +1 -1
  57. package/dist/core/http/session-stopped.d.ts +8 -0
  58. package/dist/core/http/session-stopped.d.ts.map +1 -1
  59. package/dist/core/http/session-stopped.js +23 -0
  60. package/dist/core/http/session-stopped.js.map +1 -1
  61. package/dist/core/models/composer-model.d.ts +36 -6
  62. package/dist/core/models/composer-model.d.ts.map +1 -1
  63. package/dist/core/models/composer-model.js +43 -15
  64. package/dist/core/models/composer-model.js.map +1 -1
  65. package/dist/core/models/model-flatten.d.ts +6 -11
  66. package/dist/core/models/model-flatten.d.ts.map +1 -1
  67. package/dist/core/models/model-flatten.js +2 -3
  68. package/dist/core/models/model-flatten.js.map +1 -1
  69. package/dist/core/models/model-key.d.ts +6 -7
  70. package/dist/core/models/model-key.d.ts.map +1 -1
  71. package/dist/core/models/model-key.js +7 -15
  72. package/dist/core/models/model-key.js.map +1 -1
  73. package/dist/core/models/model-visibility.d.ts +2 -2
  74. package/dist/core/models/model-visibility.d.ts.map +1 -1
  75. package/dist/core/models/model-visibility.js +8 -8
  76. package/dist/core/models/model-visibility.js.map +1 -1
  77. package/dist/core/models/provider-selection.d.ts +13 -79
  78. package/dist/core/models/provider-selection.d.ts.map +1 -1
  79. package/dist/core/models/provider-selection.js +13 -240
  80. package/dist/core/models/provider-selection.js.map +1 -1
  81. package/dist/core/rest/platform-client/capture.d.ts +6 -1
  82. package/dist/core/rest/platform-client/capture.d.ts.map +1 -1
  83. package/dist/core/rest/platform-client/capture.js +6 -3
  84. package/dist/core/rest/platform-client/capture.js.map +1 -1
  85. package/dist/core/rest/platform-client/instance-admin.d.ts +1 -1
  86. package/dist/core/rest/platform-client/instance-admin.js +2 -2
  87. package/dist/core/rest/platform-client/instance-admin.js.map +1 -1
  88. package/dist/core/rest/platform-client/shared.js +1 -1
  89. package/dist/core/rest/platform-client/shared.js.map +1 -1
  90. package/dist/core/rest/platform-client/types.d.ts +5 -1
  91. package/dist/core/rest/platform-client/types.d.ts.map +1 -1
  92. package/dist/core/rest/platform-client/urls.d.ts +1 -1
  93. package/dist/core/rest/platform-client/urls.js +1 -1
  94. package/dist/core/rest/projects-client/access.d.ts +2 -0
  95. package/dist/core/rest/projects-client/access.d.ts.map +1 -1
  96. package/dist/core/rest/projects-client/access.js.map +1 -1
  97. package/dist/core/rest/projects-client/apps.d.ts +2 -1
  98. package/dist/core/rest/projects-client/apps.d.ts.map +1 -1
  99. package/dist/core/rest/projects-client/apps.js.map +1 -1
  100. package/dist/core/rest/projects-client/audit.d.ts +2 -2
  101. package/dist/core/rest/projects-client/audit.d.ts.map +1 -1
  102. package/dist/core/rest/projects-client/billing.d.ts +5 -0
  103. package/dist/core/rest/projects-client/billing.d.ts.map +1 -1
  104. package/dist/core/rest/projects-client/billing.js.map +1 -1
  105. package/dist/core/rest/projects-client/channels.d.ts +19 -0
  106. package/dist/core/rest/projects-client/channels.d.ts.map +1 -1
  107. package/dist/core/rest/projects-client/channels.js +22 -0
  108. package/dist/core/rest/projects-client/channels.js.map +1 -1
  109. package/dist/core/rest/projects-client/connectors.d.ts +53 -1
  110. package/dist/core/rest/projects-client/connectors.d.ts.map +1 -1
  111. package/dist/core/rest/projects-client/connectors.js +12 -0
  112. package/dist/core/rest/projects-client/connectors.js.map +1 -1
  113. package/dist/core/rest/projects-client/custom-llm-providers.d.ts +40 -0
  114. package/dist/core/rest/projects-client/custom-llm-providers.d.ts.map +1 -0
  115. package/dist/core/rest/projects-client/custom-llm-providers.js +31 -0
  116. package/dist/core/rest/projects-client/custom-llm-providers.js.map +1 -0
  117. package/dist/core/rest/projects-client/drives.d.ts +23 -7
  118. package/dist/core/rest/projects-client/drives.d.ts.map +1 -1
  119. package/dist/core/rest/projects-client/drives.js +87 -9
  120. package/dist/core/rest/projects-client/drives.js.map +1 -1
  121. package/dist/core/rest/projects-client/github.d.ts +16 -0
  122. package/dist/core/rest/projects-client/github.d.ts.map +1 -1
  123. package/dist/core/rest/projects-client/github.js +4 -0
  124. package/dist/core/rest/projects-client/github.js.map +1 -1
  125. package/dist/core/rest/projects-client/iam-actions.d.ts +4 -0
  126. package/dist/core/rest/projects-client/iam-actions.d.ts.map +1 -1
  127. package/dist/core/rest/projects-client/iam-actions.js +4 -0
  128. package/dist/core/rest/projects-client/iam-actions.js.map +1 -1
  129. package/dist/core/rest/projects-client/iam-audit.d.ts +2 -2
  130. package/dist/core/rest/projects-client/iam-audit.d.ts.map +1 -1
  131. package/dist/core/rest/projects-client/index.d.ts +2 -0
  132. package/dist/core/rest/projects-client/index.d.ts.map +1 -1
  133. package/dist/core/rest/projects-client/index.js +2 -0
  134. package/dist/core/rest/projects-client/index.js.map +1 -1
  135. package/dist/core/rest/projects-client/model-access.d.ts +1 -1
  136. package/dist/core/rest/projects-client/model-access.d.ts.map +1 -1
  137. package/dist/core/rest/projects-client/notifications.d.ts +22 -2
  138. package/dist/core/rest/projects-client/notifications.d.ts.map +1 -1
  139. package/dist/core/rest/projects-client/notifications.js +29 -0
  140. package/dist/core/rest/projects-client/notifications.js.map +1 -1
  141. package/dist/core/rest/projects-client/projects.d.ts +14 -8
  142. package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
  143. package/dist/core/rest/projects-client/projects.js +5 -4
  144. package/dist/core/rest/projects-client/projects.js.map +1 -1
  145. package/dist/core/rest/projects-client/review-items.d.ts +12 -0
  146. package/dist/core/rest/projects-client/review-items.d.ts.map +1 -1
  147. package/dist/core/rest/projects-client/review-items.js +7 -0
  148. package/dist/core/rest/projects-client/review-items.js.map +1 -1
  149. package/dist/core/rest/projects-client/review.d.ts +13 -1
  150. package/dist/core/rest/projects-client/review.d.ts.map +1 -1
  151. package/dist/core/rest/projects-client/review.js.map +1 -1
  152. package/dist/core/rest/projects-client/rooms.d.ts +144 -0
  153. package/dist/core/rest/projects-client/rooms.d.ts.map +1 -0
  154. package/dist/core/rest/projects-client/rooms.js +59 -0
  155. package/dist/core/rest/projects-client/rooms.js.map +1 -0
  156. package/dist/core/rest/projects-client/sandbox.d.ts +8 -8
  157. package/dist/core/rest/projects-client/sandbox.d.ts.map +1 -1
  158. package/dist/core/rest/projects-client/secrets.d.ts +2 -0
  159. package/dist/core/rest/projects-client/secrets.d.ts.map +1 -1
  160. package/dist/core/rest/projects-client/secrets.js.map +1 -1
  161. package/dist/core/rest/projects-client/session-sandbox.d.ts +1 -1
  162. package/dist/core/rest/projects-client/session-sandbox.d.ts.map +1 -1
  163. package/dist/core/rest/projects-client/sessions.d.ts +27 -9
  164. package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
  165. package/dist/core/rest/projects-client/sessions.js +5 -4
  166. package/dist/core/rest/projects-client/sessions.js.map +1 -1
  167. package/dist/core/rest/projects-client/setup-links.d.ts +5 -0
  168. package/dist/core/rest/projects-client/setup-links.d.ts.map +1 -1
  169. package/dist/core/rest/projects-client/setup-links.js.map +1 -1
  170. package/dist/core/rest/projects-client/skills.d.ts +11 -0
  171. package/dist/core/rest/projects-client/skills.d.ts.map +1 -1
  172. package/dist/core/rest/projects-client/skills.js +4 -0
  173. package/dist/core/rest/projects-client/skills.js.map +1 -1
  174. package/dist/core/rest/projects-client/triggers.d.ts +97 -11
  175. package/dist/core/rest/projects-client/triggers.d.ts.map +1 -1
  176. package/dist/core/rest/projects-client/triggers.js +9 -1
  177. package/dist/core/rest/projects-client/triggers.js.map +1 -1
  178. package/dist/core/session/current-runtime.d.ts +1 -1
  179. package/dist/core/session/current-runtime.d.ts.map +1 -1
  180. package/dist/core/session/preview-auth.d.ts +2 -2
  181. package/dist/core/session/preview-auth.d.ts.map +1 -1
  182. package/dist/core/session/preview-auth.js +15 -4
  183. package/dist/core/session/preview-auth.js.map +1 -1
  184. package/dist/core/session/runtime-sessions.js +1 -1
  185. package/dist/core/session/runtime-sessions.js.map +1 -1
  186. package/dist/core/session/runtime-verbs.d.ts.map +1 -1
  187. package/dist/core/session/runtime-verbs.js +8 -0
  188. package/dist/core/session/runtime-verbs.js.map +1 -1
  189. package/dist/core/session/session-runtime-registry.d.ts +1 -1
  190. package/dist/core/session/session-runtime-registry.d.ts.map +1 -1
  191. package/dist/core/session/static-file-preview.d.ts.map +1 -1
  192. package/dist/core/session/static-file-preview.js +2 -1
  193. package/dist/core/session/static-file-preview.js.map +1 -1
  194. package/dist/core/session/status-vocabulary.d.ts +3 -2
  195. package/dist/core/session/status-vocabulary.d.ts.map +1 -1
  196. package/dist/core/session/status-vocabulary.js +3 -2
  197. package/dist/core/session/status-vocabulary.js.map +1 -1
  198. package/dist/core/session/turn-end-watch.d.ts +1 -1
  199. package/dist/core/session/turn-end-watch.js +1 -1
  200. package/dist/core/session/url.d.ts +1 -1
  201. package/dist/core/session/url.d.ts.map +1 -1
  202. package/dist/core/session-log/source.d.ts +4 -1
  203. package/dist/core/session-log/source.d.ts.map +1 -1
  204. package/dist/core/session-log/source.js +15 -10
  205. package/dist/core/session-log/source.js.map +1 -1
  206. package/dist/core/session-log/store.d.ts +12 -2
  207. package/dist/core/session-log/store.d.ts.map +1 -1
  208. package/dist/core/session-log/store.js +43 -10
  209. package/dist/core/session-log/store.js.map +1 -1
  210. package/dist/core/session-log/v1-view.d.ts +12 -0
  211. package/dist/core/session-log/v1-view.d.ts.map +1 -1
  212. package/dist/core/session-log/v1-view.js +64 -5
  213. package/dist/core/session-log/v1-view.js.map +1 -1
  214. package/dist/core/session-sync/saved-transcript.d.ts +16 -0
  215. package/dist/core/session-sync/saved-transcript.d.ts.map +1 -1
  216. package/dist/core/session-sync/saved-transcript.js +29 -13
  217. package/dist/core/session-sync/saved-transcript.js.map +1 -1
  218. package/dist/core/stream/event-attempt.d.ts.map +1 -1
  219. package/dist/core/stream/event-attempt.js +21 -8
  220. package/dist/core/stream/event-attempt.js.map +1 -1
  221. package/dist/core/stream/event-stream.d.ts +2 -1
  222. package/dist/core/stream/event-stream.d.ts.map +1 -1
  223. package/dist/core/stream/event-stream.js.map +1 -1
  224. package/dist/core/turns/segments/narration.js +1 -1
  225. package/dist/index.d.ts +2 -2
  226. package/dist/index.d.ts.map +1 -1
  227. package/dist/index.js +2 -2
  228. package/dist/index.js.map +1 -1
  229. package/dist/kortix.esm.min.js +38 -38
  230. package/dist/kortix.global.js +38 -38
  231. package/dist/react/connector-setup.d.ts.map +1 -1
  232. package/dist/react/connector-setup.js +5 -4
  233. package/dist/react/connector-setup.js.map +1 -1
  234. package/dist/react/index.d.ts +2 -0
  235. package/dist/react/index.d.ts.map +1 -1
  236. package/dist/react/index.js +2 -0
  237. package/dist/react/index.js.map +1 -1
  238. package/dist/react/opencode.d.ts +1 -1
  239. package/dist/react/opencode.d.ts.map +1 -1
  240. package/dist/react/opencode.js +1 -1
  241. package/dist/react/opencode.js.map +1 -1
  242. package/dist/react/prefetch-session-open.d.ts +6 -6
  243. package/dist/react/prefetch-session-open.d.ts.map +1 -1
  244. package/dist/react/prefetch-session-open.js +21 -12
  245. package/dist/react/prefetch-session-open.js.map +1 -1
  246. package/dist/react/query-keys.d.ts +17 -1
  247. package/dist/react/query-keys.d.ts.map +1 -1
  248. package/dist/react/query-keys.js +16 -0
  249. package/dist/react/query-keys.js.map +1 -1
  250. package/dist/react/session-cache-write.d.ts.map +1 -1
  251. package/dist/react/session-cache-write.js +3 -0
  252. package/dist/react/session-cache-write.js.map +1 -1
  253. package/dist/react/sign-in-with-kortix.d.ts +1 -1
  254. package/dist/react/use-accounts.d.ts.map +1 -1
  255. package/dist/react/use-accounts.js +1 -1
  256. package/dist/react/use-authenticated-preview-url.d.ts.map +1 -1
  257. package/dist/react/use-authenticated-preview-url.js +6 -9
  258. package/dist/react/use-authenticated-preview-url.js.map +1 -1
  259. package/dist/react/use-can.d.ts +1 -1
  260. package/dist/react/use-can.js +1 -1
  261. package/dist/react/use-canonical-opencode-session.d.ts +6 -0
  262. package/dist/react/use-canonical-opencode-session.d.ts.map +1 -1
  263. package/dist/react/use-canonical-opencode-session.js +3 -1
  264. package/dist/react/use-canonical-opencode-session.js.map +1 -1
  265. package/dist/react/use-capture.d.ts +1 -0
  266. package/dist/react/use-capture.d.ts.map +1 -1
  267. package/dist/react/use-capture.js +5 -1
  268. package/dist/react/use-capture.js.map +1 -1
  269. package/dist/react/use-custom-llm-providers.d.ts +16 -0
  270. package/dist/react/use-custom-llm-providers.d.ts.map +1 -0
  271. package/dist/react/use-custom-llm-providers.js +49 -0
  272. package/dist/react/use-custom-llm-providers.js.map +1 -0
  273. package/dist/react/use-feature-flag.d.ts +3 -3
  274. package/dist/react/use-feature-flag.d.ts.map +1 -1
  275. package/dist/react/use-feature-flag.js +4 -3
  276. package/dist/react/use-feature-flag.js.map +1 -1
  277. package/dist/react/use-gateway-routing-policy.d.ts +1 -0
  278. package/dist/react/use-gateway-routing-policy.d.ts.map +1 -1
  279. package/dist/react/use-gateway-routing-policy.js +3 -12
  280. package/dist/react/use-gateway-routing-policy.js.map +1 -1
  281. package/dist/react/use-model-defaults.d.ts +2 -4
  282. package/dist/react/use-model-defaults.d.ts.map +1 -1
  283. package/dist/react/use-model-defaults.js +2 -7
  284. package/dist/react/use-model-defaults.js.map +1 -1
  285. package/dist/react/use-model-enablement.d.ts.map +1 -1
  286. package/dist/react/use-model-enablement.js +1 -5
  287. package/dist/react/use-model-enablement.js.map +1 -1
  288. package/dist/react/use-model-store.d.ts +4 -1
  289. package/dist/react/use-model-store.d.ts.map +1 -1
  290. package/dist/react/use-model-store.js +16 -6
  291. package/dist/react/use-model-store.js.map +1 -1
  292. package/dist/react/use-opencode-local.d.ts +13 -1
  293. package/dist/react/use-opencode-local.d.ts.map +1 -1
  294. package/dist/react/use-opencode-local.js +41 -28
  295. package/dist/react/use-opencode-local.js.map +1 -1
  296. package/dist/react/use-opencode-sessions/no-compaction-model-error.d.ts +1 -1
  297. package/dist/react/use-opencode-sessions/no-compaction-model-error.js +1 -1
  298. package/dist/react/use-opencode-sessions/providers.d.ts +6 -0
  299. package/dist/react/use-opencode-sessions/providers.d.ts.map +1 -1
  300. package/dist/react/use-opencode-sessions/providers.js +15 -79
  301. package/dist/react/use-opencode-sessions/providers.js.map +1 -1
  302. package/dist/react/use-opencode-sessions/sessions.d.ts.map +1 -1
  303. package/dist/react/use-opencode-sessions/sessions.js +5 -1
  304. package/dist/react/use-opencode-sessions/sessions.js.map +1 -1
  305. package/dist/react/use-project-models.d.ts.map +1 -1
  306. package/dist/react/use-project-models.js +2 -8
  307. package/dist/react/use-project-models.js.map +1 -1
  308. package/dist/react/use-rooms.d.ts +382 -0
  309. package/dist/react/use-rooms.d.ts.map +1 -0
  310. package/dist/react/use-rooms.js +83 -0
  311. package/dist/react/use-rooms.js.map +1 -0
  312. package/dist/react/use-session-audit.js +1 -1
  313. package/dist/react/use-session-log.d.ts +27 -5
  314. package/dist/react/use-session-log.d.ts.map +1 -1
  315. package/dist/react/use-session-log.js +114 -20
  316. package/dist/react/use-session-log.js.map +1 -1
  317. package/dist/react/use-session-messages.d.ts.map +1 -1
  318. package/dist/react/use-session-messages.js +6 -7
  319. package/dist/react/use-session-messages.js.map +1 -1
  320. package/dist/react/use-session-stream.d.ts +1 -0
  321. package/dist/react/use-session-stream.d.ts.map +1 -1
  322. package/dist/react/use-session-stream.js +8 -0
  323. package/dist/react/use-session-stream.js.map +1 -1
  324. package/dist/react/use-session-sync.d.ts +7 -0
  325. package/dist/react/use-session-sync.d.ts.map +1 -1
  326. package/dist/react/use-session-sync.js +6 -6
  327. package/dist/react/use-session-sync.js.map +1 -1
  328. package/dist/react/use-session.d.ts +3 -0
  329. package/dist/react/use-session.d.ts.map +1 -1
  330. package/dist/react/use-session.js +63 -23
  331. package/dist/react/use-session.js.map +1 -1
  332. package/dist/react/use-tunnel.d.ts +3 -0
  333. package/dist/react/use-tunnel.d.ts.map +1 -1
  334. package/dist/react/use-tunnel.js.map +1 -1
  335. package/package.json +2 -17
  336. package/dist/core/models/bedrock-invokable.d.ts +0 -58
  337. package/dist/core/models/bedrock-invokable.d.ts.map +0 -1
  338. package/dist/core/models/bedrock-invokable.js +0 -83
  339. package/dist/core/models/bedrock-invokable.js.map +0 -1
  340. package/dist/react/bedrock-invokable.d.ts +0 -2
  341. package/dist/react/bedrock-invokable.d.ts.map +0 -1
  342. package/dist/react/bedrock-invokable.js +0 -3
  343. package/dist/react/bedrock-invokable.js.map +0 -1
  344. package/dist/react/use-opencode-sessions/provider-load-plan.d.ts +0 -6
  345. package/dist/react/use-opencode-sessions/provider-load-plan.d.ts.map +0 -1
  346. package/dist/react/use-opencode-sessions/provider-load-plan.js +0 -4
  347. package/dist/react/use-opencode-sessions/provider-load-plan.js.map +0 -1
  348. package/dist/react/use-project-llm-gateway.d.ts +0 -27
  349. package/dist/react/use-project-llm-gateway.d.ts.map +0 -1
  350. package/dist/react/use-project-llm-gateway.js +0 -41
  351. package/dist/react/use-project-llm-gateway.js.map +0 -1
@@ -1,24 +1,24 @@
1
- "use strict";var Kortix=(()=>{var oi=Object.defineProperty;var hk=Object.getOwnPropertyDescriptor;var _k=Object.getOwnPropertyNames;var bk=Object.prototype.hasOwnProperty;var Pk=(e,t)=>{for(var n in t)oi(e,n,{get:t[n],enumerable:!0})},Sk=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _k(t))!bk.call(e,s)&&s!==n&&oi(e,s,{get:()=>t[s],enumerable:!(r=hk(t,s))||r.enumerable});return e};var xk=e=>Sk(oi({},"__esModule",{value:!0}),e);var TN={};Pk(TN,{ABORT_REASONS:()=>HS,ABORT_REASONS_NOT_YET_EMITTED:()=>h$,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>hi,ACTIVE_INSTANCE_COOKIE:()=>Mr,ANALYTICS_UNAVAILABLE_CODE:()=>yi,ATTACHMENT_PART_REF_PREFIX:()=>mx,ApiError:()=>x,AuthError:()=>re,BillingError:()=>Ze,CAPTURE_DEVICE_DEFAULTS:()=>nO,CAPTURE_EXCLUSION_GROUPS:()=>XM,CAPTURE_FRAME_INTERVALS_MS:()=>eO,CAPTURE_LAYERS:()=>QM,CAPTURE_MAX_HEIGHTS:()=>tO,CAPTURE_RETENTION_LIMITS:()=>ZM,CONNECTION_FAULT_GRACE_MS:()=>xx,CONNECTOR_POLL_FIRST_DELAY_MS:()=>lx,CONNECTOR_POLL_INTERVAL_MS:()=>ux,CONNECTOR_POLL_WINDOW_MS:()=>px,CONTEXT_TOOLS:()=>eS,COST_MARKUP:()=>ry,ConnectorApprovalPendingError:()=>ms,ConnectorCallError:()=>In,ConnectorPageLimitError:()=>fs,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>tS,DEFAULT_NOTIFICATION_PREFERENCES:()=>ST,DEFAULT_TRANSCRIPT_OPTIONS:()=>Pf,DESTRUCTIVE_PHASES:()=>rx,FEATURE_DISABLED_CODE:()=>Hr,FEATURE_FLAG_KEYS:()=>tv,FEATURE_NOT_SUPPORTED_CODE:()=>di,FILE_VERBS:()=>dt,FileExistsError:()=>Zt,HeadlessAuthError:()=>Wt,HostBoundaryError:()=>jr,IMPERSONATION_HEADER:()=>Yy,INBOX_NOTIFICATION_KINDS:()=>PT,INBOX_OBSERVATION_MAX_MS:()=>Go,INITIAL_SETTLED_CONNECTION:()=>PU,INSTANCE_SCOPED_ROUTES:()=>zS,KNOWN_TOOL_KINDS:()=>Ph,KORTIX_TRANSCRIPT_SCHEMA:()=>ke,KortixMemberError:()=>mt,MAX_PROMPT_ATTACHMENTS_BYTES:()=>Qv,MAX_PROMPT_ATTACHMENT_BYTES:()=>il,MAX_PROMPT_ATTACHMENT_FILES:()=>mh,MEMORY_VERBS:()=>OL,MODEL_NOT_SERVABLE_CODE:()=>gi,NO_GROUP_ACTIVITY_TOOLS:()=>C_,OPTIMISTIC_ABORT_MAX_MS:()=>Wo,OPTIMISTIC_COMPACTION_MAX_MS:()=>OU,OPTIMISTIC_RECEIPT_MAX_MS:()=>Bo,PERSISTED_QUERY_CACHE_VERSION:()=>Y2,PLUMBING_TOOLS:()=>SS,PREVIEW_PROBE_TIMEOUT_MS:()=>pU,PROJECT_ACTIONS:()=>J,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>OA,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>MA,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>Lh,PROVISION_IN_FLIGHT_CODE:()=>mi,PROVISION_STREAM_UNTERMINATED_CODE:()=>ch,PublicSessionShareError:()=>Ts,REVIEW_CONTROL_ACTIONS:()=>$R,RUNTIME_NOT_READY_MARKERS:()=>T$,RUNTIME_PERMISSION_CAPABILITIES:()=>vT,RUNTIME_PERMISSION_REPLIES:()=>kT,RequestTooLargeError:()=>ht,RuntimeNotReadyError:()=>Qt,SANDBOX_FS_ROOTS:()=>yo,SANDBOX_PORTS:()=>We,SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE:()=>fi,SERVER_COMPACTION_REVALIDATE_MS:()=>Ax,SERVER_OBSERVATION_MAX_MS:()=>qo,SESSION_LIST_STATUS:()=>HU,SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES:()=>Jo,SESSION_LOG_MINOR:()=>_e,SESSION_LOG_SCHEMA:()=>ce,SESSION_NOTICE:()=>JU,STANDALONE_TOOLS:()=>T_,STREAM_OBSERVATION_MAX_MS:()=>yn,SandboxNotReadyError:()=>Or,SessionNotReadyError:()=>Rt,SessionStartError:()=>ws,TRIGGER_CONTROL_ACTIONS:()=>jR,TURN_END_LEDGER_LAG_MS:()=>AU,TURN_ERROR_CODES:()=>l_,WAKE_ESCALATION_COOLDOWN_MS:()=>FU,WAKE_MAX_RESTARTS:()=>UU,WAKE_NO_PROGRESS_MS:()=>$U,WIRE_ID_BACKDATE_MS:()=>co,WIRE_ID_CLOCK_TOLERANCE:()=>it,WIRE_ID_TIME_MASK:()=>Ve,WIRE_ID_TIME_SCALE:()=>zt,WIRE_MESSAGE_ID:()=>X_,__getConfigResolver:()=>vk,__setConfigResolver:()=>kk,abortErrorReason:()=>_$,acceptAccountInvite:()=>ns,acceptAccountInviteAndLand:()=>qi,acceptEnterpriseOffer:()=>Yu,acceptInvite:()=>J$,accountInviteLanding:()=>ih,actReviewItem:()=>hd,activateConnection:()=>fc,addComputerToProject:()=>_c,addGroupMembers:()=>Gp,addMarketplaceSource:()=>Qd,advanceWakeEscalation:()=>BU,allDescendantIds:()=>pS,appendPreviewToken:()=>yy,approveCaptureDeviceGrant:()=>df,approveCaptureEnrollment:()=>Zm,approveProjectAccessRequest:()=>Sa,approveTask:()=>DI,archiveProject:()=>Tn,assignTicket:()=>BI,attachGroupToProject:()=>Ea,authMfa:()=>so,authUser:()=>to,authenticatedFetch:()=>L,authenticatedRequest:()=>Mn,authorizePreviewUrl:()=>uU,backendApi:()=>l,bindSlackIdentity:()=>cR,bindTeamsIdentity:()=>lR,brokerProjectSecretRequest:()=>qa,browserKeyValueStorage:()=>nU,buildInstancePath:()=>JS,buildPresentationTemplateImageUrl:()=>fU,buildPresentationTemplatePdfUrl:()=>mU,buildPreviewAuthEndpoint:()=>fy,buildPublicTemplateUrl:()=>K0,buildRuntimePresentationConversionUrl:()=>Sx,buildSandboxTemplate:()=>Xc,buildScrapeFailureResults:()=>yS,buildStaticFileHealthPreviewUrl:()=>UM,buildStaticFileLocalUrl:()=>$M,buildStaticFilePreviewUrl:()=>LM,buildStaticFileServicePath:()=>Qb,buildTunnelEventStreamUrl:()=>XF,buildWebProxyUrl:()=>qM,bulkActReviewItems:()=>_d,bulkDeletePolicies:()=>HR,bulkImportPolicies:()=>zR,burstSummary:()=>Lo,burstSummaryLabel:()=>xS,burstWorkLabel:()=>Vf,callConnector:()=>xt,canManageBilling:()=>Hh,canOfferTopup:()=>XA,cancelAccountDeletion:()=>OC,cancelAccountInvite:()=>Fi,cancelSandbox:()=>G$,cancelSandboxUpdate:()=>u0,cancelScheduledChange:()=>Bu,cancelSubscription:()=>Fu,captureHealthBucket:()=>iO,changeRequestControlsFrom:()=>t_,checkAccessEmail:()=>w0,checkMcpServerSignIn:()=>Nv,childMapByParent:()=>UD,claimComputer:()=>f0,claimNext:()=>vP,claimPerSeatBilling:()=>rR,claimWarmProjectSession:()=>Nl,classifyPart:()=>Df,classifyPreviewProbeStatus:()=>Px,classifyPtyClose:()=>ab,classifySessionLogMessage:()=>uw,classifyTurn:()=>To,cleanErrorMessage:()=>XD,cleanResultSnippet:()=>nj,cleanWorkerOutput:()=>RL,clearImpersonationSession:()=>Si,clearKortixAppViewerCache:()=>$w,clearModelDefault:()=>ku,clearSessionFresh:()=>pA,closeChangeRequest:()=>Pl,closeMilestone:()=>yE,collectTurnParts:()=>qD,commentTicket:()=>GI,commitSessionChanges:()=>wl,compactionExpiryAtMs:()=>jU,compactionTurnInfo:()=>Fj,compareForDisplayAt:()=>Eo,compareMessagesForDisplay:()=>$D,compareSemver:()=>uO,completeInFlight:()=>AP,completeSlackInstall:()=>sp,completeTeamsInstall:()=>op,composerSelectableAgents:()=>jy,computeStatusFromPart:()=>ey,configureAutoTopup:()=>Vu,configureKortix:()=>qr,confirmCheckoutSession:()=>$u,connectEmail:()=>gp,connectSlack:()=>np,connectionFromHealth:()=>bU,connectionIsFaulted:()=>_U,connectionSharedWithEveryone:()=>Av,connectorConnect:()=>ph,connectorFinalize:()=>dh,connectorHeadline:()=>H0,contactEnterpriseSales:()=>Ju,contextLabelForTool:()=>pj,contextToolSummary:()=>KO,contextToolTrigger:()=>BO,convertPresentationToGoogleSlides:()=>GC,convertRuntimePresentation:()=>yU,copyFile:()=>gr,costExportUrl:()=>Xu,countLiveInboxPrompts:()=>CU,countReviewItemsBySegment:()=>wR,createAccount:()=>Ci,createAccountAuditWebhook:()=>Nd,createAccountSecretResource:()=>Xa,createAccountToken:()=>Cd,createApp:()=>eg,createAppAccessSession:()=>cg,createAppDeployment:()=>ug,createAppToken:()=>rg,createAppVolume:()=>Rg,createAppVolumeSnapshot:()=>Eg,createArtifactKind:()=>Oj,createAssignment:()=>ud,createAuditWebhook:()=>kC,createBackup:()=>Z$,createCaptureEnrollmentToken:()=>Jm,createCheckoutSession:()=>Lu,createConnector:()=>Mc,createConnectorLinkInfoCache:()=>G0,createFile:()=>dr,createGatewayKey:()=>Ep,createGroup:()=>Np,createHttpSessionSyncController:()=>Cw,createInstance:()=>d0,createKortix:()=>SP,createKortixPty:()=>wm,createKortixSession:()=>io,createMarketplaceInstallSession:()=>QC,createMilestone:()=>mE,createModelVisibility:()=>lk,createOAuthClient:()=>od,createPerSeatCheckout:()=>nR,createPersistedQueryCache:()=>tU,createPolicy:()=>GR,createPortalSession:()=>Uu,createProject:()=>Zi,createProjectAgent:()=>eE,createProjectCliToken:()=>Od,createProjectRepo:()=>ea,createProjectResourceGrant:()=>ja,createProjectSession:()=>vt,createProjectSkill:()=>ia,createProjectTrigger:()=>lu,createPromptAttachmentController:()=>Gm,createRole:()=>Qp,createSSEStream:()=>ZF,createSandbox:()=>$$,createSandboxShare:()=>Pd,createSandboxTemplate:()=>Yc,createSavedCopyStore:()=>CA,createScimToken:()=>XR,createServiceAccountApi:()=>PC,createSessionPrompt:()=>Kn,createSessionPublicShare:()=>$l,createSessionQueue:()=>wP,createSessionReminder:()=>wd,createSsoGroupMapping:()=>pC,createTask:()=>EI,createTicket:()=>FI,createTunnelEventStream:()=>eN,createWarmSessionPool:()=>FF,currentSavedCopyStore:()=>Rl,declineAccountInvite:()=>Gi,declineInvite:()=>Q$,deleteAccountImmediately:()=>DC,deleteAccountSecretResource:()=>tc,deleteApp:()=>ng,deleteAppDeployment:()=>yg,deleteAuditWebhook:()=>AC,deleteBackup:()=>t0,deleteConnector:()=>Dc,deleteConnectorCredential:()=>Nc,deleteCredential:()=>wE,deleteDriveFile:()=>fT,deleteEnv:()=>Pm,deleteFile:()=>Et,deleteGatewayBudget:()=>Tp,deleteGitHubInstallation:()=>ha,deleteGroup:()=>Bp,deleteInstance:()=>g0,deleteKortixProject:()=>lE,deleteMilestone:()=>_E,deleteOAuthClient:()=>cd,deletePersonalProjectSecret:()=>Ya,deletePolicy:()=>VR,deleteProjectAgent:()=>nE,deleteProjectProviderOAuth:()=>Wa,deleteProjectResourceGrant:()=>La,deleteProjectSecret:()=>Ha,deleteProjectSession:()=>Ql,deleteProjectTrigger:()=>pu,deletePromptAttachment:()=>Ft,deleteRole:()=>ed,deleteSandboxTemplate:()=>Qc,deleteServiceAccountApi:()=>xC,deleteSessionPrompt:()=>Wl,deleteSessionReminder:()=>Es,deleteSessionReminders:()=>vd,deleteSsoGroupMapping:()=>dC,deleteSsoProvider:()=>lC,deleteTask:()=>jI,deleteTicket:()=>WI,denyCaptureDeviceGrant:()=>gf,denyCaptureEnrollment:()=>ef,describeAccountInvite:()=>Bi,describeConnectorTool:()=>ls,destroyAppMachine:()=>wg,destroyAppVolume:()=>Tg,detachGroupFromProject:()=>Oa,detectLocalhostUrls:()=>Hb,directSubsessions:()=>XU,disableServiceAccountApi:()=>SC,disconnectEmail:()=>mp,disconnectGitHubApp:()=>X0,disconnectSlack:()=>ap,discoverConnectionOAuth2:()=>Iv,discoverConnectionOAuth2Resource:()=>Ev,discoverConnectorAuth:()=>Oc,discoverLocalSandbox:()=>K$,dismissDriveConflict:()=>cT,downloadAccountAudit:()=>F0,downloadDriveFile:()=>uT,dropClientForUrl:()=>OE,dropPublicClientForUrl:()=>LE,editQueued:()=>IP,editSessionPrompt:()=>Vl,enqueue:()=>kP,ensurePmSession:()=>XI,ensurePreviewSessionCookie:()=>bx,ensureProjectConnectorConnection:()=>Rv,ensureSandbox:()=>nx,ensureWarmProjectSession:()=>Fl,env:()=>ob,exchangeCode:()=>Xs,execInApp:()=>vg,exportAccountAudit:()=>Ud,extractGatewayErrorDetails:()=>Pe,extractInstanceRoute:()=>mn,extractSkillBaseDir:()=>KS,extractSkillContent:()=>NL,extractSkillFiles:()=>NS,extractWorkerPreview:()=>TL,failInFlight:()=>RP,fallbackBusyRowAfterTurnId:()=>sL,familyForTool:()=>pn,featureDisabledKey:()=>li,featureFlags:()=>cm,fetchAccountStateWithToken:()=>ZA,fetchAccountsWithToken:()=>ev,fetchAttachmentPart:()=>rU,fetchCostExportCsv:()=>aR,fetchKortixAppViewer:()=>Ey,fetchProjectArchive:()=>sl,fetchProjectFileRaw:()=>Jv,fetchProjectsForAccountWithToken:()=>pv,fetchSessionAttachment:()=>im,fileDownloadRequest:()=>Cb,filePhase:()=>ML,fileVerb:()=>EL,files:()=>$b,finalizeAppArtifact:()=>Ds,finalizeConnectorSetupLink:()=>I0,findActiveTranscriptShare:()=>jA,findFiles:()=>ur,findLastTextPart:()=>GD,findSessionAttachments:()=>aI,findText:()=>pr,fireProjectTrigger:()=>gu,fixSandboxWithAgent:()=>zc,flattenModels:()=>ik,flattenThought:()=>Gj,forkAppVolume:()=>Og,formatBillingErrorForUI:()=>pi,formatCost:()=>bL,formatDuration:()=>ny,formatJsonFailureOutput:()=>ZD,formatMessageDay:()=>Jj,formatMessageExact:()=>Qj,formatOpenCodeRuntimeError:()=>O$,formatRawOutput:()=>tj,formatRuntimeError:()=>tx,formatTokens:()=>PL,formatTranscript:()=>MP,freshSendHint:()=>cL,generateSessionId:()=>xP,getAccount:()=>Ti,getAccountBranding:()=>Ei,getAccountDeletionStatus:()=>EC,getAccountState:()=>Tu,getAccountStateMinimal:()=>Iu,getActiveInstanceIdFromCookie:()=>XS,getAdminProviderAnalytics:()=>FC,getAdminProviderDistribution:()=>LC,getAdminProviderFallback:()=>KC,getAdminRole:()=>jC,getAgentCardLabel:()=>sS,getAgentConfig:()=>HA,getAgentPersona:()=>rE,getAllVersions:()=>a0,getAnsweredQuestionParts:()=>VD,getApp:()=>Ms,getAppAccess:()=>og,getAppAuthEnv:()=>sg,getAppDeployment:()=>dg,getAppDeploymentLogs:()=>gg,getApprovalLink:()=>JC,getAuthToken:()=>$t,getAuthTokenWithRetry:()=>Sv,getAutoTopupSettings:()=>Wu,getAutoTopupSetupStatus:()=>tR,getBillingCreditBreakdown:()=>Ou,getBillingTierConfigurations:()=>ju,getBillingTransactionsSummary:()=>Mu,getBillingUsageHistory:()=>Du,getCaptureAssetUrl:()=>uf,getCaptureChunkMedia:()=>lf,getCaptureDays:()=>of,getCaptureDeviceGrant:()=>pf,getCaptureFrame:()=>cf,getCapturePolicy:()=>tf,getCaptureTimeline:()=>rf,getCaptureTimelineItems:()=>sf,getCaptureWorkspace:()=>mf,getChangeRequest:()=>fl,getChangeRequestDiff:()=>yl,getChangeRequestMergePreview:()=>hl,getChildSessionError:()=>nD,getChildSessionId:()=>wr,getChildSessionToolParts:()=>rD,getClient:()=>ct,getClientForUrl:()=>Me,getConnectStatus:()=>Uc,getConnectionOAuth2Application:()=>Tv,getConnectionOAuth2Status:()=>Lv,getConnectionPolicies:()=>$v,getConnectorCatalog:()=>Ut,getConnectorConfig:()=>Tc,getConnectorPolicies:()=>Rc,getConnectorSetupLink:()=>C0,getCostSummary:()=>iR,getCurrentInstanceIdFromPathname:()=>QS,getCurrentInstanceIdFromWindow:()=>S$,getCurrentProject:()=>Dm,getDefaultAccountState:()=>Cu,getDiagnostics:()=>cD,getDirectory:()=>rS,getDiscoverConnector:()=>gs,getDiscoverIntegration:()=>Gv,getDriveFileUrl:()=>Dg,getEmailInstallation:()=>pp,getEmailMode:()=>dp,getEnterpriseDemo:()=>CC,getFileStatus:()=>lr,getFileWithDir:()=>Rf,getFilename:()=>nS,getFolderAccess:()=>rT,getFullChangelog:()=>sx,getGatewayBreakdown:()=>kp,getGatewayBudgets:()=>Rp,getGatewayErrors:()=>Ap,getGatewayKeys:()=>Ip,getGatewayLog:()=>Sp,getGatewayOverview:()=>xp,getGatewayRoutingPolicy:()=>yp,getGatewaySeries:()=>wp,getGatewaySessions:()=>vp,getGitHubAppStatus:()=>z0,getGitHubInstallation:()=>la,getGoogleAuthUrl:()=>qC,getGroup:()=>Fp,getHiddenToolParts:()=>QO,getImpersonationSession:()=>Xy,getInvite:()=>Y$,getJustavpsServerTypes:()=>p0,getKortixProject:()=>iE,getKortixProjectBySession:()=>aE,getKortixPtyWebSocketUrl:()=>Am,getLatestSandboxVersion:()=>i0,getMaintenanceConfig:()=>j0,getManagedGitBackend:()=>_a,getManagedGitStatus:()=>av,getMarketplaceCatalogItem:()=>zd,getMarketplaceCatalogItemFile:()=>Yd,getMfaRequired:()=>eC,getMilestone:()=>dE,getMobileClientPolicy:()=>bf,getModelDefaults:()=>xu,getMyCaptureFrame:()=>_f,getMyCaptureTimeline:()=>hf,getNotificationPreferences:()=>Fg,getOAuthClient:()=>sd,getOAuthConsentRequest:()=>A0,getOpenCodeConfigInvalidError:()=>A$,getPartText:()=>zO,getPatPolicy:()=>hC,getPermissionForTool:()=>lD,getProject:()=>St,getProjectActivity:()=>sE,getProjectCommit:()=>ul,getProjectCommitDiff:()=>pl,getProjectDetail:()=>vn,getProjectDrive:()=>nT,getProjectFileHistory:()=>dl,getProjectGitToken:()=>Xi,getProjectLlmCatalog:()=>An,getProjectLlmCatalogProviders:()=>rv,getProjectModelAccess:()=>Hn,getProjectModelPicker:()=>Rn,getProjectQuota:()=>iv,getProjectSandboxHealth:()=>En,getProjectSandboxProviderTransition:()=>cv,getProjectSession:()=>Un,getProjectSessionConfigState:()=>eu,getProjectSessionScope:()=>ru,getProrationPreview:()=>qu,getProviders:()=>j$,getProxyBaseUrl:()=>FM,getPublicClientForUrl:()=>jE,getPublicMarketplaceItem:()=>S0,getPublicMarketplaceItemFile:()=>x0,getPublicSessionShare:()=>WC,getPublicSessionShareMessages:()=>VC,getPublicShareByToken:()=>O0,getPublicTemplate:()=>B0,getQuestionForTool:()=>uD,getReferralCode:()=>hR,getReferralStats:()=>PR,getRetryInfo:()=>SL,getRetryMessage:()=>xL,getReviewItem:()=>fd,getReviewSummary:()=>md,getRolePermissions:()=>Yp,getRoleUsage:()=>Jp,getRuntimeConfigInvalidError:()=>Ko,getSSHConnection:()=>r0,getSandbox:()=>L$,getSandboxById:()=>U$,getSandboxPortUrl:()=>D$,getSandboxProvisionStatus:()=>y0,getSandboxProvisionStreamUrl:()=>h0,getSandboxUpdateStatus:()=>o0,getSandboxUrl:()=>py,getSandboxUrlForExternalId:()=>Ie,getSecretSetupLink:()=>E0,getServerHealth:()=>ho,getServiceLogs:()=>CE,getSessionAudit:()=>Kl,getSessionCost:()=>_L,getSessionCostRecord:()=>Vn,getSessionDrives:()=>a_,getSessionHealth:()=>Um,getSessionLogPage:()=>ql,getSessionMessageAuthors:()=>iu,getSessionModelUsage:()=>au,getSessionOpenBundle:()=>LA,getSessionOversight:()=>rC,getSessionParticipants:()=>Il,getSessionPolicy:()=>gC,getSessionPreviewCandidates:()=>jl,getSessionProviderSecretPool:()=>oc,getSessionTranscript:()=>Bl,getSessionTranscriptSync:()=>Fn,getSessionTurn:()=>Nn,getSessionWatch:()=>El,getShellModePart:()=>AL,getSlackChannelFile:()=>cp,getSlackInstallation:()=>tp,getSlackManifest:()=>ip,getSlackMode:()=>rp,getSsoProvider:()=>oC,getStaticFileHealthPath:()=>Xb,getSupabaseAccessToken:()=>os,getSupabaseAccessTokenWithRetry:()=>uh,getTask:()=>CI,getTaskStatus:()=>II,getTemplate:()=>XC,getTicket:()=>$I,getToolInfo:()=>oD,getToolPrimaryArg:()=>ko,getTranscriptFilename:()=>OP,getTurnCost:()=>No,getTurnError:()=>dL,getTurnErrorDetails:()=>mL,getTurnErrorRawText:()=>gL,getTurnStatus:()=>ty,getUsageRollup:()=>Qu,getUserRolesWithToken:()=>$0,getVersionDiff:()=>gl,getWebPushPublicKey:()=>Kg,getWorkingState:()=>uL,grantAccountSecretResource:()=>nc,grantSandboxProjectAccess:()=>H$,grantSecretToAgent:()=>YA,groupMessagesIntoTurns:()=>ND,groupShowSegments:()=>Jf,groupSteps:()=>Hf,hasDiffs:()=>wL,hasLocalhostUrls:()=>OM,hasPreviewTarget:()=>Jb,hasRetryingAssistantTurn:()=>Uf,heartbeatGapEvent:()=>xb,holdSessionPrompts:()=>Yl,humanizeReviewActionPath:()=>$p,humanizeSearchQuery:()=>br,humanizeToolName:()=>Ef,impersonationHeaders:()=>xi,importSsoProviderFromMetadata:()=>aC,inboxObservationSupersedes:()=>RU,initialWakeEscalationState:()=>_y,inputPath:()=>ve,installTemplate:()=>ZC,interruptSessionPrompt:()=>Hl,invalidateTokenCache:()=>is,inviteAccountMember:()=>$i,inviteProjectMember:()=>Aa,inviteRepoCollaborator:()=>Ji,isAbortError:()=>Er,isAdminBypassEnabled:()=>nh,isAgentPart:()=>qO,isAppRouteUrl:()=>Vb,isAttachment:()=>YO,isAttachmentPartRef:()=>fx,isAuthFailure:()=>Dt,isBillingError:()=>ui,isCompactionPart:()=>GO,isConfigured:()=>Gr,isContextTool:()=>NO,isDestructivePhase:()=>s0,isEmptyConversation:()=>Iy,isEmptyShowPart:()=>Bs,isErrorOutput:()=>HD,isExternalUrl:()=>VM,isFeatureDisabledError:()=>ci,isFilePart:()=>Cf,isImpersonationSessionLive:()=>Jy,isInstanceDetailPath:()=>b$,isInstanceScopedAppPath:()=>YS,isInternalLocalhostUrl:()=>BM,isInvisibleActivityPart:()=>em,isInviteSent:()=>mv,isLastUserMessage:()=>lL,isLegacyMigratedSession:()=>Rx,isManagedGithubProject:()=>nv,isNoGroupActivityTool:()=>Zg,isOfferedModel:()=>ri,isOpenCodeConfigInvalidError:()=>R$,isPaintableSavedCopy:()=>Eh,isPatchPart:()=>VO,isPersistableQueryKey:()=>eU,isPreviewUrl:()=>KM,isProxiableLocalhostUrl:()=>Zb,isQuestionTool:()=>Xg,isReasoningPart:()=>we,isRetryableTurnError:()=>dS,isRuntimeConfigInvalidError:()=>ZS,isRuntimeNotReadyResponse:()=>ex,isRuntimeReady:()=>$m,isRuntimeStartingError:()=>M$,isSandboxNotReadyError:()=>fn,isSelectableAgent:()=>Gs,isServerReachable:()=>jm,isSessionAttachmentRef:()=>eI,isSessionFresh:()=>vl,isSessionLogRestoreNote:()=>mw,isSessionStartError:()=>BA,isShellActivityTool:()=>YT,isShellMode:()=>$S,isShortOutput:()=>CL,isShowContentUnavailable:()=>xT,isShowPayloadEmpty:()=>Yn,isSnapshotPart:()=>WO,isStandaloneActivityTool:()=>tm,isStepPart:()=>HO,isSubdomainPreviewUrl:()=>Lr,isTextPart:()=>Oe,isToolPart:()=>ee,isToolPartHidden:()=>XO,isTurnErrorCode:()=>Wg,isUnderSandboxRoot:()=>Mm,isWebProxyUrl:()=>WM,isWireIdAheadOf:()=>eb,kortixAppViewerToken:()=>Uw,kortixBinding:()=>Fw,kortixPty:()=>ub,kortixToken:()=>My,latestPromptModel:()=>gk,leaveAccount:()=>Hi,linkCaptureDevice:()=>zm,linkGitHubInstallation:()=>fa,linkRepository:()=>aa,listAccountAudit:()=>Ld,listAccountAuditWebhooks:()=>Fd,listAccountInvites:()=>Ui,listAccountMembers:()=>Li,listAccountResourceGrants:()=>BR,listAccountSecretResources:()=>Qa,listAccountSessions:()=>fC,listAccountTokens:()=>Rd,listAccounts:()=>Ri,listActions:()=>YR,listAdminSandboxes:()=>$C,listAgentIdentities:()=>Hp,listAllConnections:()=>uc,listAppAgents:()=>ig,listAppDeployments:()=>pg,listAppMachines:()=>_g,listAppVolumeSnapshots:()=>Ig,listAppVolumes:()=>Ag,listApps:()=>Zd,listAssignments:()=>ld,listAuditEvents:()=>RC,listAuditWebhooks:()=>wC,listBackups:()=>X$,listBillingTransactions:()=>Eu,listCaptureDevices:()=>Vm,listCaptureEnrollmentTokens:()=>Ym,listCaptureEnrollments:()=>Xm,listChangeRequests:()=>ml,listChannelBindings:()=>mR,listColumns:()=>VI,listConnectSections:()=>Bv,listConnectToolkits:()=>Kv,listConnections:()=>lc,listConnectorAccounts:()=>us,listConnectorTools:()=>cs,listConnectors:()=>xc,listCostByProject:()=>oR,listCredentialEvents:()=>PE,listCredentials:()=>bE,listDiscoverConnectors:()=>ds,listDiscoverIntegrations:()=>qv,listDiscoverSections:()=>$c,listDriveConflicts:()=>aT,listDriveFiles:()=>lT,listDriveFolder:()=>i_,listDriveVersions:()=>yT,listEnv:()=>_m,listFeaturedMarketplaces:()=>Hd,listFields:()=>zI,listFiles:()=>tn,listFolderPrincipals:()=>iT,listGatewayLogs:()=>Pp,listGitHubInstallations:()=>ua,listGitHubRepositories:()=>da,listGitHubRepositoryBranches:()=>ga,listGroupMembers:()=>qp,listGroupProjectGrants:()=>FR,listGroups:()=>Up,listKortixProjectSessions:()=>cE,listKortixProjects:()=>oE,listKortixPty:()=>xm,listLinkableGitHubInstallations:()=>pa,listManagedGitRepositories:()=>ba,listMarketplaceCatalogItems:()=>Wd,listMarketplaceSources:()=>Jd,listMarketplaces:()=>Vd,listMemberGroups:()=>NR,listMemberProjectAccess:()=>KR,listMilestoneEvents:()=>gE,listMilestones:()=>pE,listMyAccountInvites:()=>Ki,listNotifications:()=>$g,listOAuthClients:()=>rd,listOAuthGrants:()=>Id,listPendingApprovals:()=>$a,listPendingProjectInvites:()=>Ra,listPermissions:()=>dd,listPipedreamApps:()=>jc,listPipedreamSections:()=>Lc,listPolicies:()=>qR,listProjectAccess:()=>wa,listProjectAccessRequests:()=>Pa,listProjectAgentIdentities:()=>zp,listProjectAgents:()=>ZI,listProjectAudit:()=>$d,listProjectBranches:()=>cl,listProjectCliTokens:()=>Md,listProjectCommits:()=>ll,listProjectDirectory:()=>tl,listProjectFiles:()=>el,listProjectGroupGrants:()=>Ia,listProjectPolicies:()=>qc,listProjectProviderOAuth:()=>Ga,listProjectReminders:()=>Ad,listProjectResourceGrants:()=>Da,listProjectSandboxTemplates:()=>Wc,listProjectSandboxes:()=>Zc,listProjectSecrets:()=>Na,listProjectSessions:()=>kt,listProjectSessionsPage:()=>Cl,listProjectSnapshots:()=>Vc,listProjectTriggerEventApps:()=>_u,listProjectTriggerEventTypes:()=>hu,listProjectTriggerRuns:()=>fu,listProjectTriggers:()=>cu,listProjects:()=>Pt,listProjectsForAccount:()=>Yi,listPublicMarketplaceItems:()=>b0,listPublicMarketplaces:()=>P0,listReferrals:()=>SR,listReviewItems:()=>gd,listRoles:()=>Vp,listSandboxProjectMembers:()=>V$,listSandboxShares:()=>bd,listSandboxes:()=>N$,listScimTokens:()=>QR,listServiceAccountsApi:()=>bC,listServiceTemplates:()=>RE,listServices:()=>AE,listSessionConnectRequests:()=>Fv,listSessionCosts:()=>ep,listSessionDrives:()=>bT,listSessionPrompts:()=>Gl,listSessionProviderSecretPools:()=>ic,listSessionPublicShares:()=>Ll,listSessionReminders:()=>xd,listSessionsNeedingInput:()=>Ua,listSignedInDevices:()=>zC,listSsoGroupMappings:()=>uC,listTaskEvents:()=>TI,listTasks:()=>RI,listTemplates:()=>JI,listTicketEvents:()=>UI,listTickets:()=>LI,listTriggerRuns:()=>mu,loadHttpSessionHistory:()=>Rw,loadPreviewUrlTemplate:()=>ot,looksLikeError:()=>Nf,looksLikeHtml:()=>ij,looksLikeJsonPayload:()=>ej,makeDriveFolder:()=>gT,mapApiReviewItem:()=>DR,markInstanceError:()=>m0,markNotificationsRead:()=>Ug,markSessionFresh:()=>Ln,maxWireIdClock:()=>mm,memoryRelPath:()=>DL,mergeBurstSteps:()=>zf,mergeChangeRequest:()=>bl,messageCreatedAt:()=>Wj,messageTime:()=>CS,migrateAdminSandboxProvider:()=>NC,mintWireMessageId:()=>lo,mintWireMessageIdAbove:()=>fm,mkdir:()=>on,modelInDefaultView:()=>uk,modelRefToKey:()=>ei,moveDriveFile:()=>mT,narrateFailedStep:()=>Gf,narrateStep:()=>Cr,narrationToolName:()=>Rr,narrowChatEvent:()=>wb,newestWireIdClock:()=>tb,nextConnectorPollDelay:()=>V0,normalizeActivityToolName:()=>me,normalizeAppPathname:()=>k$,normalizeCaptureAppId:()=>oO,normalizeCaptureDomain:()=>sO,normalizeExternalInput:()=>HM,normalizeName:()=>Z,normalizeToolName:()=>If,notifyHostSignal:()=>Tx,openChangeRequest:()=>_l,openEventStream:()=>mo,openStressTestStream:()=>N0,paginateConnector:()=>Bc,parseBillingError:()=>xn,parseEmbeddedFailure:()=>rj,parseFlagOverride:()=>lI,parseJsonFailure:()=>Kf,parseLocalhostUrl:()=>hr,parseMemoryView:()=>jL,parseOpenCodeErrorPayload:()=>v$,parsePresentationOutput:()=>UL,parseProxyHop:()=>Lm,parseQuestionAnswersFromOutput:()=>iy,parseReadOutput:()=>FL,parseRuntimeErrorPayload:()=>uy,parseScrapeInputUrls:()=>fS,parseScrapeOutput:()=>hS,parseSubdomainUrl:()=>Nm,parseTaskRows:()=>IL,parseWebProxyUrl:()=>GM,parseWebSearchOutput:()=>Bf,partOutcome:()=>Mo,patchKortixProject:()=>uE,patchVerb:()=>$L,pickerProviderList:()=>ok,pipedreamConnect:()=>Ec,pipedreamConnectConnection:()=>Pc,pipedreamFinalize:()=>Kc,pipedreamFinalizeConnection:()=>Sc,platformConfig:()=>I,pollConnectionOAuth2DeviceAuthorization:()=>jv,pollProjectProviderOAuth:()=>ss,previewBillingPlan:()=>Hu,previewGatewayRoute:()=>bp,previewMfaRequired:()=>tC,previewSlackIdentity:()=>uR,previewTeamsIdentity:()=>pR,probeEffectivePermission:()=>td,probeEffectivePermissions:()=>nd,probePreviewPort:()=>dU,projectArchiveRequest:()=>ol,projectCompacting:()=>DU,projectConfigAgentsToOpenCodeAgents:()=>Vw,projectConfigAgentsToRuntimeAgents:()=>Dy,projectSessionConnection:()=>hU,projectSessionForRuntimeId:()=>ZU,projectSessionStartSeed:()=>Pu,projectWorking:()=>TU,provisionProject:()=>ta,provisionProjectStream:()=>ov,provisionProjectWithToken:()=>dv,proxyLocalhostUrl:()=>Fm,proxyUrlToInternal:()=>NM,purchaseCredits:()=>Gu,putConnectionOAuth2Application:()=>Cv,rawErrorText:()=>_r,reactivateSandbox:()=>W$,reactivateSubscription:()=>Nu,readBlob:()=>rn,readDriveFile:()=>pT,readFile:()=>nn,readKortixMember:()=>Zo,readProjectFile:()=>rl,readSavedSessionCopy:()=>jw,reasoningIsRunning:()=>$o,rebuildProjectSnapshot:()=>Hc,reconcileConnection:()=>pc,reconcileMemberConnection:()=>dc,reconcileServices:()=>IE,recordPlatformLogout:()=>v0,recoverLinkResults:()=>Oo,recoverProjectSession:()=>Xl,refreshReferralCode:()=>_R,refreshSession:()=>Vt,registerAppArtifact:()=>Os,registerConnectionOAuth2Client:()=>Mv,registerDeviceToken:()=>jg,registerService:()=>EE,registerWebPushSubscription:()=>Bg,rejectProjectAccessRequest:()=>xa,relativizePath:()=>aD,reloadProjectSessionConfig:()=>tu,reloadProjectSessionConfigStream:()=>nu,removeAccountAuditWebhook:()=>Bd,removeAccountBrandingAsset:()=>Di,removeAccountMember:()=>Wi,removeGroupMember:()=>Wp,removeKortixPty:()=>vm,removeMarketplaceSource:()=>Xd,removeQueued:()=>TP,renameConnection:()=>hc,renameFile:()=>fr,renameSandbox:()=>F$,reopenChangeRequest:()=>Sl,reopenMilestone:()=>hE,reorderQueued:()=>EP,replaceColumns:()=>HI,replaceFields:()=>YI,replaceProjectRepository:()=>ca,replaceTemplates:()=>QI,replayTriggerRun:()=>yu,requestAccountDeletion:()=>MC,requestChangesOnChangeRequest:()=>xl,requestProjectAccess:()=>gv,requestProjectConnector:()=>Gd,requestProjectSecret:()=>qd,requestTopUp:()=>eR,requireKortixMember:()=>Bw,resendAccountInvite:()=>Ni,resendPendingProjectInvite:()=>Ta,resetAccountBranding:()=>ji,resetClient:()=>DE,resetGatewayRoutingPolicy:()=>_p,resetPassword:()=>Zs,resetPublicClient:()=>$E,resetSandboxUpdateStatus:()=>l0,resolveApproval:()=>Fa,resolveComposerAgent:()=>Ww,resolveComposerModel:()=>fk,resolveConnectorStart:()=>W0,resolveModelDefault:()=>dk,resolvePublicShareUrl:()=>DA,resolveScrapeResults:()=>aj,resolveWorkingTurn:()=>Zf,resolvedPlan:()=>QA,restartAppMachine:()=>xg,restartProjectSession:()=>Bn,restartSandbox:()=>B$,restoreAppVolume:()=>Mg,restoreBackup:()=>e0,restoreDriveVersion:()=>hT,restoreProjectSession:()=>Zl,retryAccountSecretResource:()=>ec,retryFailed:()=>CP,retrySessionPrompt:()=>zl,revealCredential:()=>xE,reviewItemTarget:()=>Lp,reviewSegmentForStatus:()=>e_,reviewVerdictAllowed:()=>UR,reviewVerdictForStatus:()=>kR,revokeAccountSecretResourceGrant:()=>rc,revokeAccountSession:()=>yC,revokeAccountToken:()=>Td,revokeAssignment:()=>pd,revokeCaptureDevice:()=>Hm,revokeCaptureEnrollmentToken:()=>Qm,revokeConnection:()=>mc,revokeGatewayKey:()=>Mp,revokeOAuthGrant:()=>Ed,revokePendingProjectInvite:()=>Ca,revokeProjectAccess:()=>va,revokeProjectCliToken:()=>Dd,revokeSandboxProjectAccess:()=>z$,revokeSandboxShare:()=>Sd,revokeScimToken:()=>ZR,revokeSessionPublicShare:()=>Ul,rewriteLocalhostUrl:()=>ut,rollbackApp:()=>hg,rootRuntimeSession:()=>Cx,rotateAccountSecretResource:()=>Za,rotateOAuthClientSecret:()=>ad,runConnector:()=>ys,runGatewayPlayground:()=>Op,runProjectProviderOAuthFlow:()=>_v,runtimeSessionsOf:()=>Vo,runtimeSupports:()=>Kb,sanitizePtyChunk:()=>lb,saveGitHubInstallation:()=>ma,savedCopyEmptyRoot:()=>Ty,scaleApp:()=>kg,scheduleDowngrade:()=>Ku,searchCapture:()=>af,searchConnectorTools:()=>cc,searchMyCapture:()=>yf,searchProjectFiles:()=>nl,segmentTurn:()=>Yf,selectableProjectAgents:()=>pI,sendMagicLink:()=>Ys,sendReferralEmails:()=>xR,serverCompactionRevalidateAtMs:()=>LU,serviceAction:()=>TE,sessionConnectionLabel:()=>YU,sessionListStatus:()=>zU,sessionLogActivityText:()=>rw,sessionLogAnsweredQuestionCall:()=>lw,sessionLogBurstRunning:()=>iw,sessionLogBurstSteps:()=>nw,sessionLogBurstSummary:()=>sw,sessionLogBurstWorkLabel:()=>ow,sessionLogCallStatus:()=>zx,sessionLogFullTextAction:()=>Pw,sessionLogFullTextPlan:()=>Sw,sessionLogHarnessSwitches:()=>fw,sessionLogOfV1Rows:()=>Fx,sessionLogOpenCall:()=>aw,sessionLogPromptMessage:()=>Yx,sessionLogReferencedTexts:()=>_w,sessionLogRestoreNotice:()=>yw,sessionLogRetrying:()=>vy,sessionLogShowGroupCall:()=>cw,sessionLogThreadMetrics:()=>dw,sessionLogTurnSegments:()=>ew,sessionLogTurns:()=>Yo,sessionLogWithFullTexts:()=>xw,sessionModelCandidates:()=>mk,sessionModelPin:()=>Gn,sessionParentId:()=>EA,sessionPromptActions:()=>FA,sessionStartKey:()=>GA,setAccountSecretResourceAccess:()=>sc,setActiveInstanceCookie:()=>x$,setAdminBypass:()=>th,setAdminProviderDistribution:()=>UC,setAdminProviderFallback:()=>BC,setAgentScope:()=>vu,setBillingPlan:()=>zu,setBootstrapAuthToken:()=>Pv,setCachedAuthToken:()=>bv,setCaptureEnabled:()=>ff,setCapturePolicy:()=>nf,setConnectionPolicies:()=>Uv,setConnectorAuthorizationStrategy:()=>vc,setConnectorCredential:()=>Fc,setConnectorCredentialMode:()=>kc,setConnectorName:()=>Ic,setConnectorPolicies:()=>Cc,setConnectorSecretBinding:()=>Wv,setConnectorSensitive:()=>Ac,setDefaultConnection:()=>yc,setEnterpriseDemo:()=>TC,setEnv:()=>bm,setGatewayBudget:()=>Cp,setGatewayRoutingPolicy:()=>hp,setGitHubAppFromExisting:()=>J0,setGitHubAppPat:()=>Q0,setImpersonationSession:()=>Uk,setMaintenanceConfig:()=>L0,setMemberSuperAdmin:()=>JR,setMfaRequired:()=>nC,setModelDefault:()=>wu,setPersonalProjectSecret:()=>za,setProjectModelAccess:()=>zn,setProjectModelEnablement:()=>WA,setProjectOnboardingComplete:()=>oa,setProjectOnboardingProfile:()=>uv,setProjectPolicies:()=>Gc,setProjectSecretStrategy:()=>Ba,setProjectSessionModel:()=>ou,setProjectSessionScope:()=>su,setProjectSessionSharing:()=>Tl,setProjectTriggersActivation:()=>du,setSavedCopyStore:()=>TA,setSessionArchived:()=>Dl,setSessionOversight:()=>sC,setSessionPinned:()=>Ol,setSessionProviderSecretPool:()=>ac,setSessionWatch:()=>Ml,settleSessionConnection:()=>SU,setupSSH:()=>n0,shareConnection:()=>bc,shareFolder:()=>sT,shellActivityGroupLabel:()=>JT,shellExitCode:()=>cy,shouldAttachImpersonation:()=>Zy,shouldHideResponsePart:()=>pL,shouldShowToolPart:()=>ln,shouldSuppressWorkingTurnBusy:()=>nL,showGroupItems:()=>Qf,showTurnBusyIndicator:()=>Xf,signInWithPassword:()=>zs,signInWithProvider:()=>Qs,signInWithSso:()=>ro,signOut:()=>oo,signOutDevice:()=>YC,signUp:()=>Hs,skillDocumentPath:()=>VL,skillInputDir:()=>qL,sortSessions:()=>FD,splitSessionLogTurnWork:()=>tw,splitTurnWork:()=>oy,splitUserParts:()=>JO,startApp:()=>mg,startAppMachine:()=>Pg,startConnectionOAuth2Authorization:()=>Ov,startConnectionOAuth2DeviceAuthorization:()=>Dv,startConnectorSetupLink:()=>T0,startGitHubAppManifest:()=>Y0,startProjectProviderOAuth:()=>rs,startProjectSession:()=>tt,startProjectSessionOrThrow:()=>Su,startSessionWithToken:()=>D0,startTask:()=>OI,stepLabel:()=>dn,stopApp:()=>fg,stopAppMachine:()=>Sg,stopProjectSession:()=>qn,stopSandbox:()=>q$,storeGitHubUserToken:()=>ya,stripAnsi:()=>Tf,stripInstancePrefix:()=>P$,stripTrailingSlashes:()=>ue,subAgentCalls:()=>pw,submitAccessRequest:()=>k0,submitDemoRequest:()=>U0,submitOAuthConsent:()=>R0,submitReviewItem:()=>yd,submitSecretSetupLink:()=>M0,subscribeToImpersonation:()=>Fk,supabaseClient:()=>Xk,syncConnectors:()=>wc,syncSubscription:()=>sR,systemReload:()=>FE,toDaemonPath:()=>lt,toInstanceAwarePath:()=>w$,toInternalUrl:()=>eP,toSandboxAbsolutePath:()=>en,toToolView:()=>Of,toWorkspaceRelative:()=>Om,toolCallBlock:()=>Qn,toolCallError:()=>R_,toolCallMetadata:()=>w_,toolCallRawOutput:()=>A_,toolCallStatus:()=>v_,toolInfo:()=>Ao,toolKind:()=>ae,toolViewModel:()=>WS,triggerControlsFrom:()=>LR,triggerSandboxUpdate:()=>c0,triggersRequest:()=>ib,turnEndCause:()=>vx,turnEndNotice:()=>MU,turnHasSteps:()=>WD,turnIsConfirmedActive:()=>oL,turnRendersQueued:()=>iL,turnRetryLabel:()=>QU,unassignTicket:()=>qI,unregisterDeviceToken:()=>Lg,unregisterWebPushSubscription:()=>qg,unshareFolder:()=>oT,untimedAnchorOf:()=>$f,unwrapError:()=>fe,updateAccountAuditWebhook:()=>Kd,updateAccountBranding:()=>Mi,updateAccountMemberRole:()=>Vi,updateAccountName:()=>Ii,updateAgentConfig:()=>zA,updateApp:()=>tg,updateAppAccess:()=>ag,updateAppVolume:()=>Cg,updateAuditWebhook:()=>vC,updateChangeRequest:()=>kl,updateChannelBinding:()=>fR,updateConnectionCredential:()=>gc,updateEmailPolicy:()=>fp,updateExperimentalFeature:()=>ra,updateFeatureFlag:()=>na,updateGroup:()=>Kp,updateKortixPty:()=>km,updateMilestone:()=>fE,updateNotificationPreferences:()=>Ng,updateOAuthClient:()=>id,updatePassword:()=>eo,updatePatPolicy:()=>_C,updatePolicy:()=>WR,updateProject:()=>Cn,updateProjectAccess:()=>ka,updateProjectAgent:()=>tE,updateProjectDefaultAgent:()=>Ru,updateProjectGroupGrant:()=>Ma,updateProjectSandboxProvider:()=>sa,updateProjectSession:()=>Jl,updateProjectTrigger:()=>uu,updateRole:()=>Xp,updateRolePermissions:()=>Zp,updateSandboxTemplate:()=>Jc,updateSessionPolicy:()=>mC,updateSessionReminder:()=>Is,updateSessionReminders:()=>kd,updateTask:()=>MI,updateTemplateWarmPool:()=>lv,updateTicket:()=>NI,updateTicketStatus:()=>KI,updateUserMetadata:()=>no,uploadAccountBrandingAsset:()=>Oi,uploadAppArtifactArchive:()=>lg,uploadConnectorAttachment:()=>ps,uploadDriveFile:()=>dT,uploadFile:()=>sn,uploadNativeFile:()=>Mb,uploadPromptAttachment:()=>jn,uploadSessionAttachment:()=>om,uploadSlackChannelFile:()=>lp,uploadTimeoutMsForBytes:()=>Xt,upsertCredential:()=>SE,upsertProjectGitCredential:()=>Va,upsertProjectSecret:()=>Ka,upsertSsoProvider:()=>iC,validateProjectManifest:()=>Qi,validateReferralCode:()=>bR,validateToken:()=>zi,verifyGatewayProvider:()=>yR,verifyKortixToken:()=>Gw,verifyOtp:()=>Js,verifySsoDomain:()=>cC,wakeEscalationAttemptSummary:()=>VU,wakeEscalationNote:()=>GU,wakeProgressFingerprint:()=>NU,wireIdClock:()=>Tt,wireIdClockAt:()=>Yt,wireIdClockDelta:()=>It,workedForLabel:()=>vL,workingExpiryAtMs:()=>IU,workingTurnDrawsBusyRow:()=>aL,writeActivityGroupLabel:()=>QT,writeFile:()=>mr,wsDomain:()=>jo,wsFavicon:()=>oj,wsRootDomain:()=>sj});var wk={backendUrl:"",getToken:async()=>null},ii=null,Br=null;function kk(e){Br=e}function vk(){return Br}function qr(e,t){t?.global!==!1&&(ii=e)}function I(){return Br?.()??ii??wk}function Gr(){return ii!==null||Br?.()!==void 0}function Ak(e){return new Promise(t=>setTimeout(t,e))}async function Wr(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(o&&n?.(),s>0&&await Ak(s)),i=await e(),i)return i;return i}var ai=12e4;function Rk(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Gy(e,t,n=ai){let r=e instanceof Request?e.signal:t?.signal;if(Rk(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function Vr(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var x=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},re=class extends x{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},Ze=class extends x{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},ht=class extends x{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},Ck="ENDPOINT_RETIRED";function U(e,t){let n=t?` ${t}`:"";return new x(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:Ck})}var Hr="feature_disabled";function Wy(e){if(!(e instanceof x)||e.status!==403||e.code!==Hr)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function ci(e){let t=Wy(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function li(e){let t=Wy(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function xn(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new Ze(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function ui(e){return e instanceof Ze}function Dt(e){if(e instanceof re)return!0;let t=e?.status;return t===401||t===403}function pi(e){if(!(e instanceof Ze))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function Ae(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function Re(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(Ae())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function zr(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(Ae())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var Vy="request_deadline",Tk=/^Request exceeded the \d+s server processing deadline$/,Hy=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Vy||Tk.test(n),Ik="git_mirror_unavailable",Ek=/^git mirror is temporarily unavailable$/,Mk=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ik||Ek.test(n),Ok="connectors_provider_unavailable",Dk=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ok;async function jk(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await Re(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw Ae();return{message:n,data:r}}function Lk(e,t,n){return Hy(e,t,n)||Mk(e,t,n)||Dk(e,t)||e===501&&t?.code===di||e===409&&(t?.code===gi||t?.code===mi||t?.code===fi)||e===503&&(t?.code===yi||t?.code===hi)}async function zy(e,t,n,r){let{message:s,data:o}=await jk(e,t),i=new x(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Hy(e.status,o,s)?Vy:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=xn(i));let a=e.status===403&&(o?.code==="account_mfa_required"||o?.code==="sso_required")?o.code:null;if(a){try{I().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"kortix:mfa-required":"kortix:sso-required"))}catch{}}return e.status===431&&(i=new ht(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!Lk(e.status,o,s)&&I().onError?.(i,r),{error:i,success:!1}}var Yy="X-Kortix-Impersonate",bi="kortix.impersonation",_t=null,Yr=!1,_i=new Set;function Pi(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function Jy(e,t=Date.now()){if(!e||!e.grantId||!e.accountId)return!1;let n=Date.parse(e.expiresAt);return Number.isFinite(n)&&n>t}function $k(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.grantId!="string"||typeof t?.accountId!="string"?null:{grantId:t.grantId,accountId:t.accountId,accountName:typeof t.accountName=="string"?t.accountName:null,expiresAt:typeof t.expiresAt=="string"?t.expiresAt:""}}catch{return null}}function Qy(){for(let e of _i)try{e()}catch{}}function Xy(){return Yr||(Yr=!0,_t=$k(Pi()?.getItem(bi)??null)),_t&&!Jy(_t)?(Si(),null):_t}function Uk(e){if(Yr=!0,!e){Si();return}_t=e;try{Pi()?.setItem(bi,JSON.stringify(e))}catch{}Qy()}function Si(){Yr=!0;let e=_t!==null;_t=null;try{Pi()?.removeItem(bi)}catch{}e&&Qy()}function Fk(e){return _i.add(e),()=>{_i.delete(e)}}var Nk=/(^|\/)admin\/(api|analytics)(\/|$)/;function Zy(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Nk.test(t)}function xi(e){if(e!==void 0&&!Zy(e))return{};let t=Xy();return t?{[Yy]:t.grantId}:{}}function th(e){}function nh(){return!1}function Kk(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function Jr(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function wn(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function Qr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(Kk))wn(n,s,o);return n}function ki(e,t,n){let r={...t},s=I().clientVersion?.trim();s&&!Jr(r,"x-kortix-client-version")&&wn(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(xi(e)))wn(r,i,a);let o=I().credentialHeader?.trim();return o?Jr(r,o)||wn(r,o,n):Jr(r,"authorization")||wn(r,"Authorization",`Bearer ${n}`),r}async function Zr(e,t){let n=await Xr();if(!n)throw new re;return{headers:new Headers(ki(e,Qr(e,{headers:t}),n)),rejected:()=>kn(n)}}function Bk(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function eh(e,t,n,r,s){if(t instanceof Request){let c=new Headers(ki(t.url,Qr(t,n),r));return e(new Request(t,{headers:c,...s?{signal:s}:{}}))}let o=String(t),i=ki(o,Qr(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var rh=null;async function vi(e){let t=await Wr(()=>I().getToken(),e);return t&&(rh=t),t}var Xr=vi;function kn(e=rh){e&&I().getToken.invalidate?.(e)}var wi=new Map;function qk(e){let t=wi.get(e);if(t)return t;let n=(async()=>(kn(e),Xr({attempts:2,baseDelayMs:200})))().finally(()=>wi.delete(e));return wi.set(e,n),n}async function bt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=ai}=n,o=n.fetch??I().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:Gy(e,t,s);if(i?.aborted)throw Ae();let a=await(i?Re(Xr(),i):Xr());if(!a)throw new re;let c=r&&!Bk(t)&&!Jr(Qr(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await eh(o,e,t,a,i);if(d.status!==401||!c)return d;let g=await qk(a);return!g||g===a?d:eh(o,p,t,g,i)}async function Le(e,t,n,r){let s=await bt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new x(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var sh=()=>I().backendUrl||"",Gk=new Set([502,503,504]),Wk=e=>Gk.has(e),oh=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Vk=e=>oh(e)||(e??"GET").toUpperCase()==="DELETE",Hk=2,es=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function $e(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...i}=t,a=new AbortController,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await zk(e,i,n,r,s,o,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function zk(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw Ae();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},s);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Jk(e,t,c,s,o,i,a);if(p instanceof re)return{error:p,success:!1};if(!p.ok)return await zy(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await Re(p.json(),a.activeController.signal):g?.includes("text/")?d=await Re(p.text(),a.activeController.signal):d=await Re(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return Qk(c,e,t.method,n,r,s,a)}finally{ts(a)}}function ts(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Yk(e,t,n){try{await Re(e.arrayBuffer(),t)}catch(r){if(es(r))throw r}finally{ts(n)}}async function Jk(e,t,n,r,s,o,i){let a=oh(t.method),c=Vk(t.method),p=c?Hk+1:1,d;for(let g=0;g<p;g++){g>0&&await zr(250*2**(g-1),t.signal??void 0);let m=g===0?o:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await Re(bt(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof re)return new re;if(i.didTimeout&&es(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(es(f)||g===p-1)throw f;continue}if(!a||!Wk(d.status)||g===p-1)return s||ts(i),d;await Yk(d,m.signal,i)}return d}function Qk(e,t,n,r,s,o,i){ts(i);let a=es(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new x("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(sh(),"")||t;c=new x(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(c=new x(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(sh(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&I().onError?.(c,s)):(c=new x(String(e)),r&&I().onError?.(c,s));return{error:c,success:!1}}var Ue=()=>I().backendUrl||"",di="feature_not_supported",gi="model_not_servable",mi="provision_in_flight",fi="sandbox_state_change_in_progress",yi="analytics_unavailable",hi="accounts_list_unavailable",Xk={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new x(r.message||"Database error",{code:r.code,details:r});return I().onError?.(s,t),{error:s,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new x(n.message,{name:n.name||"ApiError",stack:n.stack}):new x(String(n));return I().onError?.(r,t),{error:r,success:!1}}}};async function Zk(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await bt(`${Ue()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof re)return Vr();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>$e(`${Ue()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>$e(`${Ue()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],$e(`${Ue()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],$e(`${Ue()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:Zk};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Ai(e){return e.replace(/\/v1\/?$/,"")}async function jt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Ai(e.backendUrl);try{let r=await fetch(`${n}${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(e.timeoutMs??8e3)});return r.ok?await r.json():null}catch{return null}}async function Ri(){return u(await l.get("/accounts"))}async function Ci(e){return u(await l.post("/accounts",e))}async function Ti(e){return u(await l.get(`/accounts/${e}`))}async function Ii(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function Ei(e){return u(await l.get(`/accounts/${e}/branding`))}async function Mi(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function Oi(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function Di(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function ji(e){return u(await l.delete(`/accounts/${e}/branding`))}async function Li(e){return u(await l.get(`/accounts/${e}/members`))}async function $i(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Ui(e){return u(await l.get(`/accounts/${e}/invites`))}async function Fi(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function Ni(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Ki(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function Bi(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function ns(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}function ih(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function qi(e,t){let n=await ns(e);return{accepted:n,landing:ih(n,t)}}async function Gi(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function Wi(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function Vi(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Hi(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function ev(e){return jt(e,"/v1/accounts")}async function zi(){let e=await l.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var tv=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","genui","us_region","event_triggers","notification_center","volumes","drives","session_log","session_log_restore"];async function Pt(){return u(await l.get("/projects"))}async function Yi(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function St(e,t){return u(await l.get(`/projects/${e}`,t))}async function Ji(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Qi(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Xi(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function nv(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function vn(e,t){let n=u(await l.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function An(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Rn(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function rv(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Zi(e){return u(await l.post("/projects",e))}async function ea(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function ta(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var ch="provision_stream_unterminated",ah=200;function sv(e){let t=e.split(`
1
+ "use strict";var Kortix=(()=>{var ci=Object.defineProperty;var qk=Object.getOwnPropertyDescriptor;var Gk=Object.getOwnPropertyNames;var Wk=Object.prototype.hasOwnProperty;var Hk=(e,t)=>{for(var n in t)ci(e,n,{get:t[n],enumerable:!0})},Vk=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Gk(t))!Wk.call(e,o)&&o!==n&&ci(e,o,{get:()=>t[o],enumerable:!(r=qk(t,o))||r.enumerable});return e};var zk=e=>Vk(ci({},"__esModule",{value:!0}),e);var nB={};Hk(nB,{ABORT_REASONS:()=>mx,ABORT_REASONS_NOT_YET_EMITTED:()=>Z$,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>Pi,ACTIVE_INSTANCE_COOKIE:()=>Kr,ANALYTICS_UNAVAILABLE_CODE:()=>bi,ATTACHMENT_PART_REF_PREFIX:()=>Lx,ApiError:()=>S,AuthError:()=>re,BillingError:()=>et,CAPTURE_DEVICE_DEFAULTS:()=>UO,CAPTURE_EXCLUSION_GROUPS:()=>DO,CAPTURE_FRAME_INTERVALS_MS:()=>jO,CAPTURE_LAYERS:()=>OO,CAPTURE_MAX_HEIGHTS:()=>$O,CAPTURE_RETENTION_LIMITS:()=>LO,CONNECTION_FAULT_GRACE_MS:()=>qx,CONNECTOR_POLL_FIRST_DELAY_MS:()=>Ix,CONNECTOR_POLL_INTERVAL_MS:()=>Ex,CONNECTOR_POLL_WINDOW_MS:()=>Mx,CONTEXT_TOOLS:()=>SS,COST_MARKUP:()=>ky,ConnectorApprovalPendingError:()=>xo,ConnectorCallError:()=>jn,ConnectorPageLimitError:()=>wo,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>xS,DEFAULT_NOTIFICATION_PREFERENCES:()=>oI,DEFAULT_TRANSCRIPT_OPTIONS:()=>Bf,DESTRUCTIVE_PHASES:()=>kx,FEATURE_DISABLED_CODE:()=>Dt,FEATURE_FLAG_KEYS:()=>Cv,FEATURE_NOT_SUPPORTED_CODE:()=>fi,FILE_VERBS:()=>mt,FileExistsError:()=>rn,HeadlessAuthError:()=>Yt,HostBoundaryError:()=>Wr,IMPERSONATION_HEADER:()=>mh,INBOX_NOTIFICATION_KINDS:()=>rI,INBOX_OBSERVATION_MAX_MS:()=>Ys,INITIAL_SETTLED_CONNECTION:()=>rF,INSTANCE_SCOPED_ROUTES:()=>fx,KNOWN_TOOL_KINDS:()=>Fh,KORTIX_TRANSCRIPT_SCHEMA:()=>ke,KortixMemberError:()=>yt,MAX_PROMPT_ATTACHMENTS_BYTES:()=>vA,MAX_PROMPT_ATTACHMENT_BYTES:()=>pl,MAX_PROMPT_ATTACHMENT_FILES:()=>Oh,MEMORY_VERBS:()=>f$,MODEL_NOT_SERVABLE_CODE:()=>yi,NO_GROUP_ACTIVITY_TOOLS:()=>Y_,OPTIMISTIC_ABORT_MAX_MS:()=>Js,OPTIMISTIC_COMPACTION_MAX_MS:()=>yF,OPTIMISTIC_RECEIPT_MAX_MS:()=>Vs,PERSISTED_QUERY_CACHE_VERSION:()=>DJ,PLUMBING_TOOLS:()=>KS,PREVIEW_PROBE_TIMEOUT_MS:()=>zU,PROJECT_ACTIONS:()=>J,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>cR,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>aR,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>n_,PROVISION_IN_FLIGHT_CODE:()=>hi,PROVISION_STREAM_UNTERMINATED_CODE:()=>Rh,PublicSessionShareError:()=>Lo,REPOSITORY_DISCONNECTED_CODE:()=>An,REVIEW_CONTROL_ACTIONS:()=>_C,RUNTIME_NOT_READY_MARKERS:()=>p0,RUNTIME_PERMISSION_CAPABILITIES:()=>cI,RUNTIME_PERMISSION_REPLIES:()=>aI,RequestTooLargeError:()=>bt,RuntimeNotReadyError:()=>tn,SANDBOX_FS_ROOTS:()=>Ss,SANDBOX_PORTS:()=>Ke,SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE:()=>_i,SERVER_COMPACTION_REVALIDATE_MS:()=>Vx,SERVER_OBSERVATION_MAX_MS:()=>zs,SESSION_LIST_STATUS:()=>IF,SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES:()=>ti,SESSION_LOG_MINOR:()=>he,SESSION_LOG_SCHEMA:()=>ce,SESSION_NOTICE:()=>OF,STANDALONE_TOOLS:()=>J_,STREAM_OBSERVATION_MAX_MS:()=>Pn,SandboxNotReadyError:()=>qr,SessionNotReadyError:()=>Ct,SessionStartError:()=>Io,TRIGGER_CONTROL_ACTIONS:()=>yC,TURN_END_LEDGER_LAG_MS:()=>lF,TURN_ERROR_CODES:()=>I_,WAKE_ESCALATION_COOLDOWN_MS:()=>xF,WAKE_MAX_RESTARTS:()=>SF,WAKE_NO_PROGRESS_MS:()=>PF,WIRE_ID_BACKDATE_MS:()=>ms,WIRE_ID_CLOCK_TOLERANCE:()=>ct,WIRE_ID_TIME_MASK:()=>Ve,WIRE_ID_TIME_SCALE:()=>Xt,WIRE_MESSAGE_ID:()=>bb,__getConfigResolver:()=>Qk,__setConfigResolver:()=>Jk,abortErrorReason:()=>e0,acceptAccountInvite:()=>lo,acceptAccountInviteAndLand:()=>Hi,acceptEnterpriseOffer:()=>np,acceptInvite:()=>M0,accountInviteLanding:()=>vh,actReviewItem:()=>kd,activateConnection:()=>_c,addComputerToProject:()=>Sc,addGroupMembers:()=>Qp,addMarketplaceSource:()=>hg,addRoomPerson:()=>Gd,addRoomSession:()=>Kd,advanceWakeEscalation:()=>vF,allDescendantIds:()=>MS,appendPreviewToken:()=>BU,approveCaptureDeviceGrant:()=>Of,approveCaptureEnrollment:()=>Sf,approveProjectAccessRequest:()=>va,approveTask:()=>yE,archiveProject:()=>Dn,assignTicket:()=>kE,attachGroupToProject:()=>La,authMfa:()=>us,authUser:()=>as,authenticatedFetch:()=>j,authenticatedRequest:()=>Un,authorizePreviewUrl:()=>VU,backendApi:()=>c,bindSlackIdentity:()=>FR,bindTeamsIdentity:()=>NR,brokerProjectSecretRequest:()=>Va,browserKeyValueStorage:()=>UU,buildInstancePath:()=>hx,buildPresentationTemplateImageUrl:()=>XU,buildPresentationTemplatePdfUrl:()=>QU,buildPreviewAuthEndpoint:()=>jy,buildPublicTemplateUrl:()=>wU,buildRuntimePresentationConversionUrl:()=>Kx,buildSandboxTemplate:()=>rl,buildScrapeFailureResults:()=>$S,buildStaticFileHealthPreviewUrl:()=>PO,buildStaticFileLocalUrl:()=>bO,buildStaticFilePreviewUrl:()=>_O,buildStaticFileServicePath:()=>_P,buildTunnelEventStreamUrl:()=>LN,buildWebProxyUrl:()=>vO,bulkActReviewItems:()=>vd,bulkDeletePolicies:()=>CC,bulkImportPolicies:()=>TC,burstSummary:()=>Bs,burstSummaryLabel:()=>qS,burstWorkLabel:()=>gy,callConnector:()=>kt,canManageBilling:()=>g_,canOfferTopup:()=>TR,cancelAccountDeletion:()=>mT,cancelAccountInvite:()=>Ki,cancelSandbox:()=>A0,cancelSandboxUpdate:()=>H0,cancelScheduledChange:()=>Yu,cancelSubscription:()=>Hu,captureHealthBucket:()=>KO,changeRequestControlsFrom:()=>S_,checkAccessEmail:()=>sU,checkMcpServerSignIn:()=>mA,childMapByParent:()=>PL,claimComputer:()=>Q0,claimNext:()=>HP,claimPerSeatBilling:()=>DR,claimWarmProjectSession:()=>Vl,classifyPart:()=>ty,classifyPreviewProbeStatus:()=>Bx,classifyPtyClose:()=>Cb,classifySessionLogMessage:()=>Ow,classifyTurn:()=>Ds,cleanErrorMessage:()=>DL,cleanResultSnippet:()=>UL,cleanWorkerOutput:()=>l$,clearImpersonationSession:()=>ki,clearKortixAppViewerCache:()=>lk,clearModelDefault:()=>Eu,clearSessionFresh:()=>FA,closeChangeRequest:()=>vl,closeMilestone:()=>XE,collectTurnParts:()=>vL,commentTicket:()=>AE,commitSessionChanges:()=>Cl,compactionExpiryAtMs:()=>_F,compactionTurnInfo:()=>Sj,compareForDisplayAt:()=>js,compareMessagesForDisplay:()=>bL,compareSemver:()=>HO,completeInFlight:()=>VP,completeSlackInstall:()=>pp,completeTeamsInstall:()=>dp,composerSelectableAgents:()=>th,computeStatusFromPart:()=>Sy,configureAutoTopup:()=>Zu,configureKortix:()=>Xr,confirmCheckoutSession:()=>Gu,connectEmail:()=>Pp,connectSlack:()=>lp,connectTelegram:()=>WR,connectionFromHealth:()=>nF,connectionIsFaulted:()=>tF,connectionSharedWithEveryone:()=>eA,connectorConnect:()=>Ih,connectorFinalize:()=>Eh,connectorHeadline:()=>TU,contactEnterpriseSales:()=>rp,contextLabelForTool:()=>VL,contextToolSummary:()=>wD,contextToolTrigger:()=>kD,convertPresentationToGoogleSlides:()=>vT,convertRuntimePresentation:()=>ZU,copyFile:()=>wr,costExportUrl:()=>sp,countLiveInboxPrompts:()=>pF,countReviewItemsBySegment:()=>oC,createAccount:()=>Ei,createAccountAuditWebhook:()=>ig,createAccountSecretResource:()=>tc,createAccountToken:()=>zd,createApp:()=>Pg,createAppAccessSession:()=>Cg,createAppDeployment:()=>Ig,createAppToken:()=>wg,createAppVolume:()=>Vg,createAppVolumeSnapshot:()=>Qg,createArtifactKind:()=>fj,createAssignment:()=>hd,createAuditWebhook:()=>sT,createBackup:()=>L0,createCaptureEnrollmentToken:()=>_f,createCheckoutSession:()=>qu,createConnector:()=>Lc,createConnectorLinkInfoCache:()=>AU,createFile:()=>xr,createGatewayKey:()=>Up,createGroup:()=>Vp,createHttpSessionSyncController:()=>Qw,createInstance:()=>z0,createKortix:()=>KP,createKortixPty:()=>Gm,createKortixSession:()=>ds,createMarketplaceInstallSession:()=>MT,createMilestone:()=>JE,createModelVisibility:()=>Dk,createOAuthClient:()=>dd,createPerSeatCheckout:()=>OR,createPersistedQueryCache:()=>$U,createPolicy:()=>vC,createPortalSession:()=>Wu,createProject:()=>na,createProjectAgent:()=>jE,createProjectCliToken:()=>Zd,createProjectRepo:()=>ra,createProjectResourceGrant:()=>Fa,createProjectSession:()=>Rt,createProjectSkill:()=>la,createProjectTrigger:()=>yu,createPromptAttachmentController:()=>df,createRole:()=>od,createRoom:()=>jd,createSSEStream:()=>jN,createSandbox:()=>b0,createSandboxShare:()=>Rd,createSandboxTemplate:()=>el,createSavedCopyStore:()=>eR,createScimToken:()=>OC,createServiceAccountApi:()=>tT,createSessionPrompt:()=>zn,createSessionPublicShare:()=>Gl,createSessionQueue:()=>GP,createSessionReminder:()=>Id,createSsoGroupMapping:()=>HC,createTask:()=>gE,createTicket:()=>SE,createTunnelEventStream:()=>$N,createWarmSessionPool:()=>SN,currentSavedCopyStore:()=>Dl,declineAccountInvite:()=>Vi,declineInvite:()=>O0,deleteAccountImmediately:()=>fT,deleteAccountSecretResource:()=>oc,deleteApp:()=>xg,deleteAppDeployment:()=>jg,deleteAuditWebhook:()=>aT,deleteBackup:()=>$0,deleteConnector:()=>Fc,deleteConnectorCredential:()=>Wc,deleteCredential:()=>sM,deleteCustomLlmProvider:()=>ir,deleteDriveFile:()=>QT,deleteEnv:()=>Bm,deleteFile:()=>Et,deleteGatewayBudget:()=>jp,deleteGitHubInstallation:()=>Sa,deleteGroup:()=>Yp,deleteInstance:()=>Y0,deleteKortixProject:()=>WE,deleteMilestone:()=>eM,deleteOAuthClient:()=>fd,deletePersonalProjectSecret:()=>Xa,deletePolicy:()=>RC,deleteProjectAgent:()=>UE,deleteProjectProviderOAuth:()=>Ya,deleteProjectResourceGrant:()=>Na,deleteProjectSecret:()=>Ln,deleteProjectSession:()=>ou,deleteProjectTrigger:()=>_u,deletePromptAttachment:()=>Bt,deleteRole:()=>ad,deleteSandboxTemplate:()=>nl,deleteServiceAccountApi:()=>rT,deleteSessionPrompt:()=>Xl,deleteSessionReminder:()=>$o,deleteSessionReminders:()=>Md,deleteSsoGroupMapping:()=>VC,deleteSsoProvider:()=>GC,deleteTask:()=>hE,deleteTicket:()=>RE,denyCaptureDeviceGrant:()=>Df,denyCaptureEnrollment:()=>xf,describeAccountInvite:()=>Wi,describeConnectorTool:()=>ho,destroyAppMachine:()=>qg,destroyAppVolume:()=>Yg,detachGroupFromProject:()=>$a,detectLocalhostUrls:()=>mP,directSubsessions:()=>LF,disableServiceAccountApi:()=>nT,disconnectEmail:()=>Sp,disconnectGitHubApp:()=>DU,disconnectSlack:()=>mp,disconnectTelegram:()=>VR,discoverConnectionOAuth2:()=>oA,discoverConnectionOAuth2Resource:()=>sA,discoverConnectorAuth:()=>jc,discoverLocalSandbox:()=>w0,dismissDriveConflict:()=>qT,downloadAccountAudit:()=>SU,downloadDriveFile:()=>WT,dropClientForUrl:()=>fM,dropPublicClientForUrl:()=>_M,editQueued:()=>QP,editSessionPrompt:()=>Zl,enqueue:()=>WP,ensurePmSession:()=>DE,ensurePreviewSessionCookie:()=>Nx,ensureProjectConnectorConnection:()=>tA,ensureSandbox:()=>wx,ensureWarmProjectSession:()=>Hl,env:()=>Ab,exchangeCode:()=>os,execInApp:()=>Wg,exportAccountAudit:()=>og,extractGatewayErrorDetails:()=>be,extractInstanceRoute:()=>_n,extractSkillBaseDir:()=>cx,extractSkillContent:()=>x$,extractSkillFiles:()=>ax,extractWorkerPreview:()=>p$,failInFlight:()=>zP,fallbackBusyRowAfterTurnId:()=>Nj,familyForTool:()=>fn,featureDisabledKey:()=>di,featureFlags:()=>Em,fetchAccountStateWithToken:()=>IR,fetchAccountsWithToken:()=>Rv,fetchAttachmentPart:()=>FU,fetchCostExportCsv:()=>UR,fetchKortixAppViewer:()=>Qy,fetchProjectArchive:()=>ll,fetchProjectFileRaw:()=>kA,fetchProjectsForAccountWithToken:()=>Uv,fetchSessionAttachment:()=>Tm,fileDownloadRequest:()=>Yb,filePhase:()=>m$,fileVerb:()=>g$,files:()=>oP,finalizeAppArtifact:()=>No,finalizeConnectorSetupLink:()=>dU,findActiveTranscriptShare:()=>uR,findFiles:()=>Pr,findLastTextPart:()=>AL,findSessionAttachments:()=>GI,findText:()=>Sr,fireProjectTrigger:()=>Pu,fixSandboxWithAgent:()=>Zc,flattenModels:()=>Ek,flattenThought:()=>Aj,forkAppVolume:()=>Zg,formatBillingErrorForUI:()=>mi,formatCost:()=>t$,formatDuration:()=>wy,formatJsonFailureOutput:()=>LL,formatMessageDay:()=>Mj,formatMessageExact:()=>Oj,formatOpenCodeRuntimeError:()=>f0,formatRawOutput:()=>$L,formatRuntimeError:()=>xx,formatTokens:()=>n$,formatTranscript:()=>ZP,freshSendHint:()=>Gj,generateSessionId:()=>qP,getAccount:()=>Mi,getAccountAutomations:()=>fR,getAccountBranding:()=>Di,getAccountDeletionStatus:()=>dT,getAccountState:()=>ju,getAccountStateMinimal:()=>$u,getActiveInstanceIdFromCookie:()=>bx,getAdminProviderAnalytics:()=>PT,getAdminProviderDistribution:()=>hT,getAdminProviderFallback:()=>xT,getAdminRole:()=>yT,getAgentCardLabel:()=>vS,getAgentConfig:()=>kR,getAgentPersona:()=>FE,getAllVersions:()=>q0,getAnsweredQuestionParts:()=>CL,getApp:()=>Uo,getAppAccess:()=>vg,getAppAuthEnv:()=>kg,getAppDeployment:()=>Mg,getAppDeploymentLogs:()=>Og,getApprovalLink:()=>ET,getAuthToken:()=>Ft,getAuthTokenWithRetry:()=>Yv,getAutoTopupSettings:()=>Xu,getAutoTopupSetupStatus:()=>MR,getBillingCreditBreakdown:()=>Nu,getBillingTierConfigurations:()=>Ku,getBillingTransactionsSummary:()=>Fu,getBillingUsageHistory:()=>Bu,getCaptureAssetUrl:()=>Ef,getCaptureChunkMedia:()=>If,getCaptureDays:()=>Rf,getCaptureDeviceGrant:()=>Mf,getCaptureFrame:()=>Tf,getCapturePolicy:()=>wf,getCaptureTimeline:()=>vf,getCaptureTimelineItems:()=>Af,getCaptureWorkspace:()=>Lf,getChangeRequest:()=>Pl,getChangeRequestDiff:()=>Sl,getChangeRequestMergePreview:()=>xl,getChildSessionError:()=>UD,getChildSessionId:()=>Or,getChildSessionToolParts:()=>FD,getClient:()=>ut,getClientForUrl:()=>Me,getConnectStatus:()=>qc,getConnectionOAuth2Application:()=>rA,getConnectionOAuth2Status:()=>uA,getConnectionPolicies:()=>pA,getConnectorCatalog:()=>Nt,getConnectorConfig:()=>Mc,getConnectorPolicies:()=>Ic,getConnectorSetupLink:()=>uU,getCostSummary:()=>$R,getCurrentInstanceIdFromPathname:()=>_x,getCurrentInstanceIdFromWindow:()=>r0,getCurrentProject:()=>tf,getDefaultAccountState:()=>Lu,getDiagnostics:()=>GD,getDirectory:()=>kS,getDiscoverConnector:()=>So,getDiscoverIntegration:()=>_A,getDriveFileUrl:()=>em,getEmailInstallation:()=>_p,getEmailMode:()=>bp,getEnterpriseDemo:()=>lT,getFileStatus:()=>br,getFileWithDir:()=>zf,getFilename:()=>wS,getFolderAccess:()=>UT,getFullChangelog:()=>vx,getGatewayBreakdown:()=>Ep,getGatewayBudgets:()=>Dp,getGatewayErrors:()=>Op,getGatewayKeys:()=>$p,getGatewayLog:()=>Cp,getGatewayOverview:()=>Tp,getGatewayRoutingPolicy:()=>wp,getGatewaySeries:()=>Ip,getGatewaySessions:()=>Mp,getGitHubAppStatus:()=>IU,getGitHubInstallation:()=>ga,getGoogleAuthUrl:()=>kT,getGroup:()=>Hp,getHiddenToolParts:()=>OD,getImpersonationSession:()=>hh,getInvite:()=>E0,getJustavpsServerTypes:()=>V0,getKortixProject:()=>KE,getKortixProjectBySession:()=>qE,getKortixPtyWebSocketUrl:()=>Vm,getLatestSandboxVersion:()=>K0,getMaintenanceConfig:()=>hU,getManagedGitBackend:()=>xa,getManagedGitStatus:()=>Dv,getMarketplaceCatalogItem:()=>mg,getMarketplaceCatalogItemFile:()=>fg,getMfaRequired:()=>LC,getMilestone:()=>zE,getMobileClientPolicy:()=>Nf,getModelDefaults:()=>Tu,getMyCaptureFrame:()=>Ff,getMyCaptureTimeline:()=>Uf,getNotificationPreferences:()=>cm,getOAuthClient:()=>pd,getOAuthConsentRequest:()=>cU,getOpenCodeConfigInvalidError:()=>c0,getPartText:()=>ID,getPatPolicy:()=>XC,getPermissionForTool:()=>WD,getProject:()=>wt,getProjectActivity:()=>NE,getProjectCommit:()=>fl,getProjectCommitDiff:()=>yl,getProjectDetail:()=>In,getProjectDrive:()=>$T,getProjectFileHistory:()=>hl,getProjectGitConnectionState:()=>Nv,getProjectGitToken:()=>ta,getProjectLlmCatalog:()=>En,getProjectLlmCatalogProviders:()=>Iv,getProjectModelAccess:()=>nr,getProjectModelPicker:()=>Mn,getProjectQuota:()=>Ov,getProjectSandboxHealth:()=>$n,getProjectSandboxProviderTransition:()=>Lv,getProjectSession:()=>Wn,getProjectSessionConfigState:()=>au,getProjectSessionScope:()=>uu,getProrationPreview:()=>Ju,getProviders:()=>h0,getProxyBaseUrl:()=>SO,getPublicClientForUrl:()=>hM,getPublicMarketplaceItem:()=>rU,getPublicMarketplaceItemFile:()=>oU,getPublicSessionShare:()=>AT,getPublicSessionShareMessages:()=>RT,getPublicShareByToken:()=>fU,getPublicTemplate:()=>kU,getQuestionForTool:()=>HD,getReferralCode:()=>XR,getReferralStats:()=>tC,getRetryInfo:()=>r$,getRetryMessage:()=>o$,getReviewItem:()=>xd,getReviewSummary:()=>Sd,getRolePermissions:()=>nd,getRoleUsage:()=>rd,getRoom:()=>$d,getRuntimeConfigInvalidError:()=>Hs,getSSHConnection:()=>F0,getSandbox:()=>_0,getSandboxById:()=>P0,getSandboxPortUrl:()=>y0,getSandboxProvisionStatus:()=>X0,getSandboxProvisionStreamUrl:()=>Z0,getSandboxUpdateStatus:()=>B0,getSandboxUrl:()=>My,getSandboxUrlForExternalId:()=>Ie,getSecretSetupLink:()=>gU,getServerHealth:()=>xs,getServiceLogs:()=>uM,getSessionAudit:()=>zl,getSessionCost:()=>e$,getSessionCostRecord:()=>Zn,getSessionDrives:()=>R_,getSessionHealth:()=>sf,getSessionLogPage:()=>Jl,getSessionMessageAuthors:()=>gu,getSessionModelUsage:()=>mu,getSessionOpenBundle:()=>pR,getSessionOversight:()=>UC,getSessionParticipants:()=>$l,getSessionPolicy:()=>zC,getSessionPreviewCandidates:()=>Kl,getSessionProviderSecretPool:()=>cc,getSessionTranscript:()=>Yl,getSessionTranscriptSync:()=>Hn,getSessionTurn:()=>Vn,getSessionWatch:()=>Ul,getShellModePart:()=>c$,getSlackChannelFile:()=>fp,getSlackInstallation:()=>cp,getSlackManifest:()=>gp,getSlackMode:()=>up,getSsoProvider:()=>NC,getStaticFileHealthPath:()=>bP,getSupabaseAccessToken:()=>go,getSupabaseAccessTokenWithRetry:()=>Th,getTask:()=>uE,getTaskStatus:()=>dE,getTelegramInstallation:()=>GR,getTemplate:()=>OT,getTicket:()=>bE,getToolInfo:()=>BD,getToolPrimaryArg:()=>Ts,getTranscriptFilename:()=>eS,getTurnCost:()=>Ws,getTurnError:()=>zj,getTurnErrorDetails:()=>Jj,getTurnErrorRawText:()=>Yj,getTurnStatus:()=>xy,getUsageRollup:()=>op,getUserRolesWithToken:()=>bU,getVersionDiff:()=>_l,getWebPushPublicKey:()=>um,getWorkingState:()=>Hj,grantAccountSecretResource:()=>sc,grantSandboxProjectAccess:()=>T0,grantSecretToAgent:()=>AR,groupMessagesIntoTurns:()=>xL,groupShowSegments:()=>hy,groupSteps:()=>my,hasDiffs:()=>s$,hasLocalhostUrls:()=>fO,hasPreviewTarget:()=>hP,hasRetryingAssistantTurn:()=>sy,heartbeatGapEvent:()=>qb,holdSessionPrompts:()=>nu,humanizeReviewActionPath:()=>Gp,humanizeSearchQuery:()=>Tr,humanizeToolName:()=>Xf,impersonationHeaders:()=>vi,importSsoProviderFromMetadata:()=>KC,inboxObservationSupersedes:()=>uF,initialWakeEscalationState:()=>Uy,inputPath:()=>ve,installTemplate:()=>DT,interruptSessionPrompt:()=>eu,invalidateTokenCache:()=>mo,inviteAccountMember:()=>Ni,inviteProjectMember:()=>Ia,inviteRepoCollaborator:()=>Zi,isAbortError:()=>Br,isAdminBypassEnabled:()=>Sh,isAgentPart:()=>vD,isAppRouteUrl:()=>gP,isAttachment:()=>ED,isAttachmentPartRef:()=>jx,isAuthFailure:()=>Lt,isBillingError:()=>gi,isCompactionPart:()=>AD,isConfigured:()=>Zr,isContextTool:()=>xD,isDestructivePhase:()=>N0,isEmptyConversation:()=>Jy,isEmptyShowPart:()=>Jo,isErrorOutput:()=>TL,isExternalUrl:()=>CO,isFeatureDisabledError:()=>pi,isFilePart:()=>Yf,isImpersonationSessionLive:()=>fh,isInstanceDetailPath:()=>t0,isInstanceScopedAppPath:()=>yx,isInternalLocalhostUrl:()=>kO,isInvisibleActivityPart:()=>wm,isInviteSent:()=>Kv,isLastUserMessage:()=>Wj,isLegacyMigratedSession:()=>zx,isManagedGithubProject:()=>Tv,isNoGroupActivityTool:()=>xm,isOfferedModel:()=>ii,isOpenCodeConfigInvalidError:()=>l0,isPaintableSavedCopy:()=>Jh,isPatchPart:()=>CD,isPersistableQueryKey:()=>jU,isPreviewUrl:()=>wO,isProxiableLocalhostUrl:()=>PP,isQuestionTool:()=>Sm,isReasoningPart:()=>we,isRepositoryDisconnectedError:()=>lh,isRetryableTurnError:()=>OS,isRuntimeConfigInvalidError:()=>Px,isRuntimeNotReadyResponse:()=>Sx,isRuntimeReady:()=>of,isRuntimeStartingError:()=>m0,isSandboxNotReadyError:()=>bn,isSelectableAgent:()=>Xo,isServerReachable:()=>nf,isSessionAttachmentRef:()=>$I,isSessionFresh:()=>Il,isSessionLogRestoreNote:()=>$w,isSessionStartError:()=>bR,isShellActivityTool:()=>MI,isShellMode:()=>ox,isShortOutput:()=>u$,isShowContentUnavailable:()=>sI,isShowPayloadEmpty:()=>ar,isSnapshotPart:()=>RD,isStandaloneActivityTool:()=>km,isStepPart:()=>TD,isSubdomainPreviewUrl:()=>Hr,isTextPart:()=>Oe,isToolPart:()=>ee,isToolPartHidden:()=>DD,isTurnErrorCode:()=>mm,isUnderSandboxRoot:()=>Zm,isWebProxyUrl:()=>RO,isWireIdAheadOf:()=>Sb,kortixAppViewerToken:()=>uk,kortixBinding:()=>pk,kortixPty:()=>Eb,kortixToken:()=>Xy,latestPromptModel:()=>$k,leaveAccount:()=>Ji,linkCaptureDevice:()=>yf,linkGitHubInstallation:()=>ba,linkRepository:()=>pa,listAccountAudit:()=>ng,listAccountAuditWebhooks:()=>sg,listAccountInvites:()=>Bi,listAccountMembers:()=>Fi,listAccountResourceGrants:()=>wC,listAccountSecretResources:()=>ec,listAccountSessions:()=>JC,listAccountTokens:()=>Vd,listAccounts:()=>Ii,listActions:()=>IC,listAdminSandboxes:()=>_T,listAgentIdentities:()=>ed,listAllConnections:()=>gc,listAppAgents:()=>Ag,listAppDeployments:()=>Eg,listAppMachines:()=>Ug,listAppVolumeSnapshots:()=>Jg,listAppVolumes:()=>Hg,listApps:()=>bg,listAssignments:()=>yd,listAuditEvents:()=>cT,listAuditWebhooks:()=>oT,listBackups:()=>D0,listBillingTransactions:()=>Uu,listCaptureDevices:()=>mf,listCaptureEnrollmentTokens:()=>hf,listCaptureEnrollments:()=>Pf,listChangeRequests:()=>bl,listChannelBindings:()=>YR,listColumns:()=>CE,listConnectSections:()=>yA,listConnectToolkits:()=>fA,listConnections:()=>dc,listConnectorAccounts:()=>_o,listConnectorMoves:()=>$c,listConnectorTools:()=>yo,listConnectors:()=>vc,listCostByProject:()=>jR,listCredentialEvents:()=>nM,listCredentials:()=>tM,listCustomLlmProviders:()=>or,listDiscoverConnectors:()=>Po,listDiscoverIntegrations:()=>hA,listDiscoverSections:()=>Kc,listDriveConflicts:()=>KT,listDriveFiles:()=>GT,listDriveFolder:()=>A_,listDriveVersions:()=>XT,listEnv:()=>Fm,listFeaturedMarketplaces:()=>gg,listFields:()=>IE,listFiles:()=>sn,listFolderPrincipals:()=>BT,listGatewayLogs:()=>Rp,listGitHubInstallations:()=>ma,listGitHubRepositories:()=>ya,listGitHubRepositoryBranches:()=>ha,listGroupMembers:()=>Jp,listGroupProjectGrants:()=>PC,listGroups:()=>Wp,listKortixProjectSessions:()=>GE,listKortixProjects:()=>BE,listKortixPty:()=>qm,listLinkableGitHubInstallations:()=>fa,listManagedGitRepositories:()=>wa,listMarketplaceCatalogItems:()=>pg,listMarketplaceSources:()=>yg,listMarketplaces:()=>dg,listMemberGroups:()=>SC,listMemberProjectAccess:()=>xC,listMilestoneEvents:()=>YE,listMilestones:()=>VE,listMyAccountInvites:()=>Gi,listNotifications:()=>im,listOAuthClients:()=>ud,listOAuthGrants:()=>Jd,listPendingApprovals:()=>Ba,listPendingProjectInvites:()=>Ea,listPermissions:()=>bd,listPipedreamApps:()=>Nc,listPipedreamSections:()=>Bc,listPolicies:()=>kC,listProjectAccess:()=>Ra,listProjectAccessRequests:()=>ka,listProjectAgentIdentities:()=>td,listProjectAgents:()=>LE,listProjectAudit:()=>rg,listProjectBranches:()=>gl,listProjectCliTokens:()=>Xd,listProjectCommits:()=>ml,listProjectDirectory:()=>il,listProjectFiles:()=>sl,listProjectGroupGrants:()=>Da,listProjectPolicies:()=>zc,listProjectProviderOAuth:()=>za,listProjectReminders:()=>Od,listProjectResourceGrants:()=>Ua,listProjectSandboxTemplates:()=>Jc,listProjectSandboxes:()=>ol,listProjectSecrets:()=>Ga,listProjectSessions:()=>At,listProjectSessionsPage:()=>Ll,listProjectSnapshots:()=>Qc,listProjectTriggerEventApps:()=>vu,listProjectTriggerEventTypes:()=>ku,listProjectTriggerRuns:()=>xu,listProjectTriggers:()=>fu,listProjects:()=>xt,listProjectsForAccount:()=>Xi,listPublicMarketplaceItems:()=>tU,listPublicMarketplaces:()=>nU,listReferrals:()=>nC,listReviewItems:()=>Pd,listRoles:()=>Zp,listRoomMessages:()=>Fd,listRoomPeople:()=>Hd,listRooms:()=>Ld,listSandboxProjectMembers:()=>C0,listSandboxShares:()=>Ad,listSandboxes:()=>x0,listScimTokens:()=>MC,listServiceAccountsApi:()=>eT,listServiceTemplates:()=>lM,listServices:()=>cM,listSessionConnectRequests:()=>gA,listSessionCosts:()=>ap,listSessionDrives:()=>tI,listSessionPrompts:()=>Ql,listSessionProviderSecretPools:()=>lc,listSessionPublicShares:()=>ql,listSessionReminders:()=>Td,listSessionsNeedingInput:()=>Ka,listSignedInDevices:()=>TT,listSsoGroupMappings:()=>WC,listTaskEvents:()=>pE,listTasks:()=>lE,listTemplates:()=>ME,listTicketEvents:()=>PE,listTickets:()=>_E,listTriggerRuns:()=>Su,loadHttpSessionHistory:()=>Jw,loadPreviewUrlTemplate:()=>it,looksLikeError:()=>ay,looksLikeHtml:()=>KL,looksLikeJsonPayload:()=>jL,makeDriveFolder:()=>YT,mapApiReviewItem:()=>fC,markInstanceError:()=>J0,markNotificationsRead:()=>am,markRoomRead:()=>Bd,markSessionFresh:()=>Kn,maxWireIdClock:()=>Lm,memoryRelPath:()=>y$,mergeBurstSteps:()=>fy,mergeChangeRequest:()=>kl,messageCreatedAt:()=>Rj,messageTime:()=>YS,migrateAdminSandboxProvider:()=>ST,mintWireMessageId:()=>fs,mintWireMessageIdAbove:()=>jm,mkdir:()=>un,modelInDefaultView:()=>Lk,modelRefToKey:()=>kn,moveConnector:()=>Uc,moveDriveFile:()=>JT,narrateFailedStep:()=>py,narrateStep:()=>Ur,narrationToolName:()=>$r,narrowChatEvent:()=>Gb,newestWireIdClock:()=>xb,nextConnectorPollDelay:()=>CU,normalizeActivityToolName:()=>me,normalizeAppPathname:()=>i0,normalizeCaptureAppId:()=>BO,normalizeCaptureDomain:()=>NO,normalizeExternalInput:()=>TO,normalizeName:()=>Z,normalizeToolName:()=>Qf,notifyHostSignal:()=>Jx,openChangeRequest:()=>wl,openEventStream:()=>bs,openStressTestStream:()=>xU,paginateConnector:()=>Vc,parseBillingError:()=>Rn,parseEmbeddedFailure:()=>FL,parseFlagOverride:()=>HI,parseJsonFailure:()=>cy,parseLocalhostUrl:()=>Rr,parseMemoryView:()=>h$,parseOpenCodeErrorPayload:()=>a0,parsePresentationOutput:()=>P$,parseProxyHop:()=>rf,parseQuestionAnswersFromOutput:()=>Ry,parseReadOutput:()=>S$,parseRuntimeErrorPayload:()=>Ey,parseScrapeInputUrls:()=>jS,parseScrapeOutput:()=>US,parseSubdomainUrl:()=>cf,parseTaskRows:()=>d$,parseWebProxyUrl:()=>AO,parseWebSearchOutput:()=>ly,partOutcome:()=>$s,patchKortixProject:()=>HE,patchVerb:()=>b$,pickerProviderList:()=>Ik,pipedreamConnect:()=>Dc,pipedreamConnectConnection:()=>wc,pipedreamFinalize:()=>Hc,pipedreamFinalizeConnection:()=>kc,platformConfig:()=>C,pollConnectionOAuth2DeviceAuthorization:()=>lA,pollProjectProviderOAuth:()=>po,postRoomMessage:()=>Nd,previewBillingPlan:()=>ep,previewGatewayRoute:()=>Ap,previewMfaRequired:()=>jC,previewSlackIdentity:()=>BR,previewTeamsIdentity:()=>KR,probeEffectivePermission:()=>cd,probeEffectivePermissions:()=>ld,probePreviewPort:()=>YU,projectArchiveRequest:()=>ul,projectCompacting:()=>hF,projectConfigAgentsToOpenCodeAgents:()=>_k,projectConfigAgentsToRuntimeAgents:()=>eh,projectSessionConnection:()=>eF,projectSessionForRuntimeId:()=>jF,projectSessionStartSeed:()=>Ru,projectWorking:()=>dF,provisionProject:()=>oa,provisionProjectStream:()=>Mv,provisionProjectWithToken:()=>Fv,proxyLocalhostUrl:()=>af,proxyUrlToInternal:()=>xO,purchaseCredits:()=>Qu,putConnectionOAuth2Application:()=>nA,putCustomLlmProvider:()=>sr,rawErrorText:()=>Cr,reactivateSandbox:()=>R0,reactivateSubscription:()=>Vu,readBlob:()=>cn,readDriveFile:()=>HT,readFile:()=>an,readKortixMember:()=>oi,readProjectFile:()=>cl,readSavedSessionCopy:()=>ak,reasoningIsRunning:()=>Ks,rebuildProjectSnapshot:()=>Xc,reconcileConnection:()=>mc,reconcileMemberConnection:()=>fc,reconcileServices:()=>dM,recordPlatformLogout:()=>aU,recoverLinkResults:()=>Us,recoverProjectSession:()=>su,refreshReferralCode:()=>ZR,refreshSession:()=>Jt,registerAppArtifact:()=>Fo,registerConnectionOAuth2Client:()=>iA,registerDeviceToken:()=>rm,registerService:()=>gM,registerWebPushSubscription:()=>pm,rejectProjectAccessRequest:()=>Aa,relativizePath:()=>qD,releaseDeviceToken:()=>sm,reloadProjectSessionConfig:()=>cu,reloadProjectSessionConfigStream:()=>lu,removeAccountAuditWebhook:()=>cg,removeAccountBrandingAsset:()=>$i,removeAccountMember:()=>zi,removeGroupMember:()=>Xp,removeKortixPty:()=>Hm,removeMarketplaceSource:()=>_g,removeProjectSkill:()=>ua,removeQueued:()=>JP,removeRoomPerson:()=>Wd,removeRoomSession:()=>qd,renameConnection:()=>Pc,renameFile:()=>vr,renameSandbox:()=>S0,reopenChangeRequest:()=>Al,reopenMilestone:()=>ZE,reorderQueued:()=>XP,replaceColumns:()=>TE,replaceFields:()=>EE,replaceProjectRepository:()=>da,replaceTemplates:()=>OE,replayTriggerRun:()=>wu,repositoryDisconnectedReason:()=>uh,requestAccountDeletion:()=>gT,requestChangesOnChangeRequest:()=>Rl,requestProjectAccess:()=>Bv,requestProjectConnector:()=>ug,requestProjectSecret:()=>lg,requestTopUp:()=>ER,requireKortixMember:()=>mk,resendAccountInvite:()=>qi,resendPendingProjectInvite:()=>Oa,resetAccountBranding:()=>Ui,resetClient:()=>yM,resetGatewayRoutingPolicy:()=>vp,resetPassword:()=>ss,resetPublicClient:()=>bM,resetSandboxUpdateStatus:()=>W0,resolveApproval:()=>qa,resolveComposerAgent:()=>hk,resolveComposerModel:()=>Bk,resolveConnectorStart:()=>RU,resolveModelDefault:()=>jk,resolvePublicShareUrl:()=>lR,resolveScrapeResults:()=>qL,resolveWorkingTurn:()=>Py,resolvedPlan:()=>CR,restartAppMachine:()=>Kg,restartProjectSession:()=>Yn,restartSandbox:()=>k0,restoreAppVolume:()=>Xg,restoreBackup:()=>j0,restoreDriveVersion:()=>ZT,restoreProjectSession:()=>iu,retryAccountSecretResource:()=>rc,retryFailed:()=>YP,retrySessionPrompt:()=>tu,revealCredential:()=>oM,reviewItemTarget:()=>qp,reviewSegmentForStatus:()=>P_,reviewVerdictAllowed:()=>bC,reviewVerdictForStatus:()=>sC,revokeAccountSecretResourceGrant:()=>ic,revokeAccountSession:()=>QC,revokeAccountToken:()=>Yd,revokeAssignment:()=>_d,revokeCaptureDevice:()=>ff,revokeCaptureEnrollmentToken:()=>bf,revokeConnection:()=>hc,revokeGatewayKey:()=>Fp,revokeOAuthGrant:()=>Qd,revokePendingProjectInvite:()=>Ma,revokeProjectAccess:()=>Ta,revokeProjectCliToken:()=>eg,revokeSandboxProjectAccess:()=>I0,revokeSandboxShare:()=>Cd,revokeScimToken:()=>DC,revokeSessionPublicShare:()=>Wl,rewriteLocalhostUrl:()=>dt,rollbackApp:()=>$g,rootRuntimeSession:()=>Yx,rotateAccountSecretResource:()=>nc,rotateOAuthClientSecret:()=>md,runConnector:()=>ko,runGatewayPlayground:()=>Np,runProjectProviderOAuthFlow:()=>Hv,runtimeSessionsOf:()=>Qs,runtimeSupports:()=>cP,sanitizePtyChunk:()=>Ib,saveGitHubInstallation:()=>_a,savedCopyEmptyRoot:()=>Yy,scaleApp:()=>Gg,scheduleDowngrade:()=>zu,searchCapture:()=>Cf,searchConnectorTools:()=>pc,searchMyCapture:()=>$f,searchProjectFiles:()=>al,segmentTurn:()=>yy,selectableProjectAgents:()=>zI,sendMagicLink:()=>ts,sendReferralEmails:()=>rC,serverCompactionRevalidateAtMs:()=>bF,serviceAction:()=>pM,sessionConnectionLabel:()=>MF,sessionListStatus:()=>EF,sessionLogActivityText:()=>Aw,sessionLogAnsweredQuestionCall:()=>Mw,sessionLogBurstRunning:()=>Tw,sessionLogBurstSteps:()=>vw,sessionLogBurstSummary:()=>Rw,sessionLogBurstWorkLabel:()=>Cw,sessionLogCallStatus:()=>hw,sessionLogFullTextAction:()=>qw,sessionLogFullTextPlan:()=>Gw,sessionLogHarnessSwitches:()=>Uw,sessionLogOfV1Rows:()=>cw,sessionLogOpenCall:()=>Iw,sessionLogPromptMessage:()=>_w,sessionLogReferencedTexts:()=>Bw,sessionLogRestoreNotice:()=>Fw,sessionLogRetrying:()=>Wy,sessionLogShowGroupCall:()=>Ew,sessionLogThreadMetrics:()=>Lw,sessionLogTurnSegments:()=>ww,sessionLogTurns:()=>ei,sessionLogWithFullTexts:()=>Ww,sessionModelCandidates:()=>Nk,sessionModelFallback:()=>Uk,sessionModelPin:()=>Qn,sessionParentId:()=>iR,sessionPickStands:()=>Fk,sessionPromptActions:()=>mR,sessionStartKey:()=>SR,setAccountAutomationsPaused:()=>yR,setAccountSecretResourceAccess:()=>ac,setActiveInstanceCookie:()=>o0,setAdminBypass:()=>Ph,setAdminProviderDistribution:()=>bT,setAdminProviderFallback:()=>wT,setAgentScope:()=>Mu,setBillingPlan:()=>tp,setBootstrapAuthToken:()=>zv,setCachedAuthToken:()=>Vv,setCaptureEnabled:()=>jf,setCapturePolicy:()=>kf,setConnectionPolicies:()=>dA,setConnectorAuthorizationStrategy:()=>Cc,setConnectorCredential:()=>Gc,setConnectorCredentialMode:()=>Rc,setConnectorName:()=>Oc,setConnectorPolicies:()=>Ec,setConnectorSecretBinding:()=>bA,setConnectorSensitive:()=>Tc,setDefaultConnection:()=>bc,setEnterpriseDemo:()=>uT,setEnv:()=>Nm,setGatewayBudget:()=>Lp,setGatewayRoutingPolicy:()=>kp,setGitHubAppFromExisting:()=>MU,setGitHubAppPat:()=>OU,setImpersonationSession:()=>pv,setMaintenanceConfig:()=>_U,setMemberSuperAdmin:()=>EC,setMfaRequired:()=>$C,setModelDefault:()=>Iu,setPersonalProjectSecret:()=>Qa,setProjectModelAccess:()=>rr,setProjectModelEnablement:()=>xR,setProjectOnboardingComplete:()=>ca,setProjectOnboardingProfile:()=>$v,setProjectPolicies:()=>Yc,setProjectSecretStrategy:()=>Ha,setProjectSessionModel:()=>du,setProjectSessionScope:()=>pu,setProjectSessionSharing:()=>jl,setProjectTriggersActivation:()=>bu,setSavedCopyStore:()=>tR,setSessionArchived:()=>Bl,setSessionOversight:()=>FC,setSessionPinned:()=>Nl,setSessionProviderSecretPool:()=>uc,setSessionWatch:()=>Fl,setTelegramAllowedUsers:()=>HR,settleSessionConnection:()=>oF,setupSSH:()=>U0,shareConnection:()=>xc,shareFolder:()=>FT,shellActivityGroupLabel:()=>OI,shellExitCode:()=>Ty,shouldAttachImpersonation:()=>_h,shouldHideResponsePart:()=>Vj,shouldShowToolPart:()=>gn,shouldSuppressWorkingTurnBusy:()=>Uj,showGroupItems:()=>_y,showTurnBusyIndicator:()=>by,signInWithPassword:()=>es,signInWithProvider:()=>rs,signInWithSso:()=>ls,signOut:()=>ps,signOutDevice:()=>IT,signUp:()=>Zo,skillDocumentPath:()=>C$,skillInputDir:()=>v$,sortSessions:()=>SL,splitSessionLogTurnWork:()=>kw,splitTurnWork:()=>Ay,splitUserParts:()=>MD,startApp:()=>Dg,startAppMachine:()=>Ng,startConnectionOAuth2Authorization:()=>aA,startConnectionOAuth2DeviceAuthorization:()=>cA,startConnectorSetupLink:()=>pU,startGitHubAppManifest:()=>EU,startProjectProviderOAuth:()=>uo,startProjectSession:()=>nt,startProjectSessionOrThrow:()=>Cu,startSessionWithToken:()=>yU,startTask:()=>fE,stepLabel:()=>yn,stopApp:()=>Lg,stopAppMachine:()=>Bg,stopProjectSession:()=>Jn,stopSandbox:()=>v0,storeGitHubUserToken:()=>Pa,stripAnsi:()=>Jf,stripInstancePrefix:()=>n0,stripTrailingSlashes:()=>le,subAgentCalls:()=>Dw,submitAccessRequest:()=>iU,submitDemoRequest:()=>PU,submitOAuthConsent:()=>lU,submitReviewItem:()=>wd,submitSecretSetupLink:()=>mU,subscribeToImpersonation:()=>dv,supabaseClient:()=>vv,syncConnectors:()=>Ac,syncSubscription:()=>LR,systemReload:()=>SM,toDaemonPath:()=>pt,toInstanceAwarePath:()=>s0,toInternalUrl:()=>SP,toSandboxAbsolutePath:()=>on,toToolView:()=>ey,toWorkspaceRelative:()=>ef,toolCallBlock:()=>lr,toolCallError:()=>z_,toolCallMetadata:()=>G_,toolCallRawOutput:()=>V_,toolCallStatus:()=>H_,toolInfo:()=>Es,toolKind:()=>ae,toolViewModel:()=>dx,triggerControlsFrom:()=>hC,triggerSandboxUpdate:()=>G0,triggersRequest:()=>Rb,turnEndCause:()=>Hx,turnEndNotice:()=>fF,turnHasSteps:()=>RL,turnIsConfirmedActive:()=>Bj,turnRendersQueued:()=>Kj,turnRetryLabel:()=>DF,unassignTicket:()=>vE,unregisterDeviceToken:()=>om,unregisterWebPushSubscription:()=>dm,unshareFolder:()=>NT,untimedAnchorOf:()=>oy,unwrapError:()=>fe,updateAccountAuditWebhook:()=>ag,updateAccountBranding:()=>Li,updateAccountMemberRole:()=>Yi,updateAccountName:()=>Oi,updateAgentConfig:()=>vR,updateApp:()=>Sg,updateAppAccess:()=>Rg,updateAppVolume:()=>zg,updateAuditWebhook:()=>iT,updateChangeRequest:()=>Tl,updateChannelBinding:()=>JR,updateConnectionCredential:()=>yc,updateEmailPolicy:()=>xp,updateExperimentalFeature:()=>ia,updateFeatureFlag:()=>sa,updateGroup:()=>zp,updateKortixPty:()=>Wm,updateMilestone:()=>QE,updateNotificationPreferences:()=>lm,updateOAuthClient:()=>gd,updatePassword:()=>is,updatePatPolicy:()=>ZC,updatePolicy:()=>AC,updateProject:()=>On,updateProjectAccess:()=>Ca,updateProjectAgent:()=>$E,updateProjectDefaultAgent:()=>Du,updateProjectGroupGrant:()=>ja,updateProjectSandboxProvider:()=>aa,updateProjectSession:()=>ru,updateProjectTrigger:()=>hu,updateRole:()=>sd,updateRolePermissions:()=>id,updateRoom:()=>Ud,updateSandboxTemplate:()=>tl,updateSessionPolicy:()=>YC,updateSessionReminder:()=>jo,updateSessionReminders:()=>Ed,updateTask:()=>mE,updateTemplateWarmPool:()=>jv,updateTicket:()=>xE,updateTicketStatus:()=>wE,updateUserMetadata:()=>cs,uploadAccountBrandingAsset:()=>ji,uploadAppArtifactArchive:()=>Tg,uploadConnectorAttachment:()=>bo,uploadDriveFile:()=>VT,uploadFile:()=>ln,uploadNativeFile:()=>Zb,uploadPromptAttachment:()=>Bn,uploadSessionAttachment:()=>Cm,uploadSlackChannelFile:()=>yp,uploadTimeoutMsForBytes:()=>nn,upsertCredential:()=>rM,upsertProjectGitCredential:()=>Ja,upsertProjectSecret:()=>Wa,upsertSsoProvider:()=>BC,validateProjectManifest:()=>ea,validateReferralCode:()=>eC,validateToken:()=>Qi,verifyGatewayProvider:()=>QR,verifyKortixToken:()=>yk,verifyOtp:()=>ns,verifySsoDomain:()=>qC,wakeEscalationAttemptSummary:()=>TF,wakeEscalationNote:()=>RF,wakeProgressFingerprint:()=>wF,wireIdClock:()=>Tt,wireIdClockAt:()=>Zt,wireIdClockDelta:()=>It,workedForLabel:()=>a$,workingExpiryAtMs:()=>gF,workingTurnDrawsBusyRow:()=>qj,writeActivityGroupLabel:()=>DI,writeFile:()=>kr,wsDomain:()=>Ns,wsFavicon:()=>BL,wsRootDomain:()=>NL});var Yk={backendUrl:"",getToken:async()=>null},li=null,Qr=null;function Jk(e){Qr=e}function Qk(){return Qr}function Xr(e,t){t?.global!==!1&&(li=e)}function C(){return Qr?.()??li??Yk}function Zr(){return li!==null||Qr?.()!==void 0}function Xk(e){return new Promise(t=>setTimeout(t,e))}async function eo(e,t,n){let r=Math.max(1,t?.attempts??1),o=t?.baseDelayMs??0,s=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(s&&n?.(),o>0&&await Xk(o)),i=await e(),i)return i;return i}var ui=12e4;function Zk(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function ah(e,t,n=ui){let r=e instanceof Request?e.signal:t?.signal;if(Zk(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function to(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var S=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:o,...s}=n;Object.assign(this,s),r&&(this.name=r),o&&(this.stack=o);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},re=class extends S{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},et=class extends S{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},bt=class extends S{constructor(t=431,n,r){let o="Request headers are too large";super(r||n?.message||o,{status:t,detail:{message:n?.message||o,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},ev="ENDPOINT_RETIRED";function F(e,t){let n=t?` ${t}`:"";return new S(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:ev})}var Dt="feature_disabled";function ch(e){if(!(e instanceof S)||e.status!==403||e.code!==Dt)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function pi(e){let t=ch(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function di(e){let t=ch(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}var An="repository_disconnected",tv=new Set(["app_uninstalled","app_suspended","repo_not_accessible"]);function lh(e){return!!e&&typeof e=="object"&&e.code===An}function uh(e){if(e?.status!=="error")return null;let t=e.last_error_code;return t&&tv.has(t)?t:null}function Rn(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new et(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function gi(e){return e instanceof et}function Lt(e){if(e instanceof re)return!0;let t=e?.status;return t===401||t===403}function mi(e){if(!(e instanceof et))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function Ae(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function Re(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(Ae())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function no(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(Ae())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var ph="request_deadline",nv=/^Request exceeded the \d+s server processing deadline$/,dh=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===ph||nv.test(n),rv="git_mirror_unavailable",ov=/^git mirror is temporarily unavailable$/,sv=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===rv||ov.test(n),iv="connectors_provider_unavailable",av=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===iv;async function cv(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await Re(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw Ae();return{message:n,data:r}}function lv(e,t,n){return dh(e,t,n)||sv(e,t,n)||av(e,t)||e===403&&t?.code===Dt||e===501&&t?.code===fi||e===409&&(t?.code===yi||t?.code===hi||t?.code===_i||t?.code===An)||e===503&&(t?.code===bi||t?.code===Pi)}async function gh(e,t,n,r){let{message:o,data:s}=await cv(e,t),i=new S(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:dh(e.status,s,o)?ph:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});e.status===402&&(i=Rn(i));let a=e.status===403&&(s?.code==="account_mfa_required"||s?.code==="sso_required")?s.code:null;if(a){try{C().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"kortix:mfa-required":"kortix:sso-required"))}catch{}}return e.status===431&&(i=new bt(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!lv(e.status,s,o)&&C().onError?.(i,r),{error:i,success:!1}}var mh="X-Kortix-Impersonate",xi="kortix.impersonation",Pt=null,ro=!1,Si=new Set;function wi(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function fh(e,t=Date.now()){if(!e||!e.grantId||!e.accountId)return!1;let n=Date.parse(e.expiresAt);return Number.isFinite(n)&&n>t}function uv(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.grantId!="string"||typeof t?.accountId!="string"?null:{grantId:t.grantId,accountId:t.accountId,accountName:typeof t.accountName=="string"?t.accountName:null,expiresAt:typeof t.expiresAt=="string"?t.expiresAt:""}}catch{return null}}function yh(){for(let e of Si)try{e()}catch{}}function hh(){return ro||(ro=!0,Pt=uv(wi()?.getItem(xi)??null)),Pt&&!fh(Pt)?(ki(),null):Pt}function pv(e){if(ro=!0,!e){ki();return}Pt=e;try{wi()?.setItem(xi,JSON.stringify(e))}catch{}yh()}function ki(){ro=!0;let e=Pt!==null;Pt=null;try{wi()?.removeItem(xi)}catch{}e&&yh()}function dv(e){return Si.add(e),()=>{Si.delete(e)}}var gv=/(^|\/)admin\/(api|analytics)(\/|$)/;function _h(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!gv.test(t)}function vi(e){if(e!==void 0&&!_h(e))return{};let t=hh();return t?{[mh]:t.grantId}:{}}function Ph(e){}function Sh(){return!1}function mv(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function oo(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Cn(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function so(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(mv))Cn(n,o,s);return n}function Ri(e,t,n){let r={...t},o=C().clientVersion?.trim();o&&!oo(r,"x-kortix-client-version")&&Cn(r,"X-Kortix-Client-Version",o);for(let[i,a]of Object.entries(vi(e)))Cn(r,i,a);let s=C().credentialHeader?.trim();return s?oo(r,s)||Cn(r,s,n):oo(r,"authorization")||Cn(r,"Authorization",`Bearer ${n}`),r}async function jt(e,t){let n=await io();if(!n)throw new re;return{headers:new Headers(Ri(e,so(e,{headers:t}),n)),rejected:()=>Tn(n)}}function fv(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function bh(e,t,n,r,o){if(t instanceof Request){let l=new Headers(Ri(t.url,so(t,n),r));return e(new Request(t,{headers:l,...o?{signal:o}:{}}))}let s=String(t),i=Ri(s,so(t,n),r),a=s.startsWith("/")&&!s.startsWith("//");return e(s,{...n,headers:i,...a?{credentials:"same-origin"}:{},...o?{signal:o}:{}})}var xh=null;async function Ci(e){let t=await eo(()=>C().getToken(),e);return t&&(xh=t),t}var io=Ci;function Tn(e=xh){e&&C().getToken.invalidate?.(e)}var Ai=new Map;function yv(e){let t=Ai.get(e);if(t)return t;let n=(async()=>(Tn(e),io({attempts:2,baseDelayMs:200})))().finally(()=>Ai.delete(e));return Ai.set(e,n),n}async function St(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=ui}=n,s=n.fetch??C().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:ah(e,t,o);if(i?.aborted)throw Ae();let a=await(i?Re(io(),i):io());if(!a)throw new re;let l=r&&!fv(t)&&!oo(so(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await bh(s,e,t,a,i);if(d.status!==401||!l)return d;let g=await yv(a);return!g||g===a?d:bh(s,p,t,g,i)}async function je(e,t,n,r){let o=await St(e,t,n);if(o.ok)return o;let s=await o.text().catch(()=>"");throw new S(s||`${r} (HTTP ${o.status})`,{status:o.status,response:o})}var wh=()=>C().backendUrl||"",hv=new Set([502,503,504]),_v=e=>hv.has(e),kh=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},bv=e=>kh(e)||(e??"GET").toUpperCase()==="DELETE",Pv=2,ao=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function $e(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:o=3e4,deadlineCoversBody:s=!1,...i}=t,a=new AbortController,l={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>l.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await Sv(e,i,n,r,o,s,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function Sv(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw Ae();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},o);let l={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await wv(e,t,l,o,s,i,a);if(p instanceof re)return{error:p,success:!1};if(!p.ok)return await gh(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await Re(p.json(),a.activeController.signal):g?.includes("text/")?d=await Re(p.text(),a.activeController.signal):d=await Re(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(l){return kv(l,e,t.method,n,r,o,a)}finally{co(a)}}function co(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function xv(e,t,n){try{await Re(e.arrayBuffer(),t)}catch(r){if(ao(r))throw r}finally{co(n)}}async function wv(e,t,n,r,o,s,i){let a=kh(t.method),l=bv(t.method),p=l?Pv+1:1,d;for(let g=0;g<p;g++){g>0&&await no(250*2**(g-1),t.signal??void 0);let m=g===0?s:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await Re(St(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof re)return new re;if(i.didTimeout&&ao(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(ao(f)||g===p-1)throw f;continue}if(!a||!_v(d.status)||g===p-1)return o||co(i),d;await xv(d,m.signal,i)}return d}function kv(e,t,n,r,o,s,i){co(i);let a=ao(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new S("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(wh(),"")||t;l=new S(`Request timed out after ${Math.round(s/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:s})}else e instanceof Error?(l=new S(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(wh(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&C().onError?.(l,o)):(l=new S(String(e)),r&&C().onError?.(l,o));return{error:l,success:!1}}var Ue=()=>C().backendUrl||"",fi="feature_not_supported",yi="model_not_servable",hi="provision_in_flight",_i="sandbox_state_change_in_progress",bi="analytics_unavailable",Pi="accounts_list_unavailable",vv={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let o=new S(r.message||"Database error",{code:r.code,details:r});return C().onError?.(o,t),{error:o,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new S(n.message,{name:n.name||"ApiError",stack:n.stack}):new S(String(n));return C().onError?.(r,t),{error:r,success:!1}}}};async function Av(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await St(`${Ue()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:s.signal,credentials:"omit"},{timeoutMs:null,fetch:o})}catch(a){if(a instanceof re)return to();throw a}finally{clearTimeout(i)}}var c={putRaw:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>$e(`${Ue()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>$e(`${Ue()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],$e(`${Ue()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],$e(`${Ue()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:Av};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Ti(e){return e.replace(/\/v1\/?$/,"")}async function $t(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Ti(e.backendUrl);try{let r=await fetch(`${n}${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(e.timeoutMs??8e3)});return r.ok?await r.json():null}catch{return null}}async function Ii(){return u(await c.get("/accounts"))}async function Ei(e){return u(await c.post("/accounts",e))}async function Mi(e){return u(await c.get(`/accounts/${e}`))}async function Oi(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function Di(e){return u(await c.get(`/accounts/${e}/branding`))}async function Li(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function ji(e,t,n,r){let o=new FormData;return o.append("file",n,r??(n instanceof File?n.name:t)),u(await c.upload(`/accounts/${e}/branding/assets/${t}`,o))}async function $i(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function Ui(e){return u(await c.delete(`/accounts/${e}/branding`))}async function Fi(e){return u(await c.get(`/accounts/${e}/members`))}async function Ni(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Bi(e){return u(await c.get(`/accounts/${e}/invites`))}async function Ki(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function qi(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Gi(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function Wi(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function lo(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}function vh(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function Hi(e,t){let n=await lo(e);return{accepted:n,landing:vh(n,t)}}async function Vi(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function zi(e,t){return u(await c.delete(`/accounts/${e}/members/${t}`))}async function Yi(e,t,n){return u(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Ji(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function Rv(e){return $t(e,"/v1/accounts")}async function Qi(){let e=await c.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var Cv=["marketplace","connectors_api_discover","agentmail_email","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","genui","us_region","event_triggers","notification_center","volumes","drives","session_log","session_log_restore","connectors_v2","agent_rooms","goals"];async function xt(){return u(await c.get("/projects"))}async function Xi(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/projects${t}`))}async function wt(e,t){return u(await c.get(`/projects/${e}`,t))}async function Zi(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function ea(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function ta(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function Tv(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function In(e,t){let n=u(await c.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function En(e,t){return u(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Mn(e,t){return u(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function Iv(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function na(e){return u(await c.post("/projects",e))}async function ra(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function oa(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Rh="provision_stream_unterminated",Ah=200;function Ev(e){let t=e.split(`
2
2
  `).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
3
- `);try{return JSON.parse(n)}catch(r){let s=n.length>ah?`${n.slice(0,ah)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function ov(e,t,n={}){let r=await l.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let c=await r.json().catch(()=>null);throw new x(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.code})}let s=r.body?.getReader();if(!s)throw new Error("Provision stream is unavailable on this runtime (no response body)");let o=new TextDecoder,i="",a=null;try{for(;;){let{done:c,value:p}=await s.read();if(c)break;i+=o.decode(p,{stream:!0});let d=i.indexOf(`
3
+ `);try{return JSON.parse(n)}catch(r){let o=n.length>Ah?`${n.slice(0,Ah)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${o})`,{cause:r})}}async function Mv(e,t,n={}){let r=await c.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let l=await r.json().catch(()=>null);throw new S(l?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:l?.code})}let o=r.body?.getReader();if(!o)throw new Error("Provision stream is unavailable on this runtime (no response body)");let s=new TextDecoder,i="",a=null;try{for(;;){let{done:l,value:p}=await o.read();if(l)break;i+=s.decode(p,{stream:!0});let d=i.indexOf(`
4
4
 
5
5
  `);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2),d=i.indexOf(`
6
6
 
7
- `);let m=sv(g);if(m){if(t(m),m.type==="error")throw new x(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new x("Provision stream ended without a result",{code:ch});return a}async function iv(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await l.get(`/projects/quota${t}`))}async function av(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Cn(e,t){return u(await l.patch(`/projects/${e}`,t))}async function na(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function ra(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function sa(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function cv(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function lv(e,t){throw U("updateTemplateWarmPool")}async function oa(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function uv(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Tn(e){return u(await l.delete(`/projects/${e}`))}async function pv(e,t){return jt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function dv(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Ai(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function ia(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function aa(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function ca(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function la(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ua(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function pa(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function da(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function ga(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await l.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function ma(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function fa(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function ya(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function ha(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function _a(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function ba(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await l.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function gv(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Pa(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function Sa(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function xa(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function wa(e){return u(await l.get(`/projects/${e}/access`))}async function ka(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function va(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function mv(e){return"status"in e&&e.status==="invited"}async function Aa(e,t,n,r){return u(await l.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Ra(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function Ca(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ta(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ia(e){return u(await l.get(`/projects/${e}/group-grants`))}async function Ea(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function Ma(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function Oa(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function Da(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function ja(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function La(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function $a(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Ua(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Fa(e,t,n,r={}){let s=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function Na(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Ka(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function Ba(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function qa(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Ga(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function rs(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function ss(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Wa(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var fv=2e3,yv=3e3,hv=10*6e4;async function _v(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,c=()=>o?.()??!1,p=await rs(t,n,r);if(c())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(fv,p.interval_ms||yv),g=p.expires_at||a()+hv;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await ss(t,n,p.flow_id)}catch{continue}if(c())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return c()?{status:"cancelled"}:{status:"expired"}}async function Va(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function Ha(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function za(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Ya(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var Ja=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Lt=(e,t)=>`${Ja(e)}/${encodeURIComponent(t)}`,lh=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Qa(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${Ja(e)}${n}`))}async function Xa(e,t){return u(await l.post(Ja(e),t))}async function Za(e,t,n){return u(await l.put(`${Lt(e,t)}/value`,{value:n}))}async function ec(e,t){return u(await l.post(`${Lt(e,t)}/retry`))}async function tc(e,t){return u(await l.delete(Lt(e,t)))}async function nc(e,t,n,r){return u(await l.put(`${Lt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function rc(e,t,n,r){return u(await l.delete(`${Lt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function sc(e,t,n,r){return u(await l.put(`${Lt(e,t)}/access`,{mode:n,user_ids:r}))}async function oc(e,t,n){return u(await l.get(lh(e,t,n)))}async function ic(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function ac(e,t,n,r){return u(await l.put(lh(e,t,n),{secret_ids:r}))}async function os(){return vi()}async function uh(e){return Wr(()=>I().getToken(),e,is)}function is(){kn()}function bv(e){e===null&&kn()}function Pv(e){}async function $t(){return os()}async function Sv(e){return uh(e)}async function L(e,t,n){try{return await bt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof re)return Vr();throw r}}function as(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Ut(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${as(e,"catalog")}${r}`)).connectors??[]}async function cs(e){let t=[];for(let n of await Ut(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function cc(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await cs(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?o.push(a):s.every(p=>c.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function ls(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await Ut(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===r);if(!s)return null;for(let o of s.actions){let i=`${s.slug}.${o.path}`;if(i===t)return{tool:i,connector:s.slug,action:o.path,risk:o.risk,description:o.description||o.name,inputSchema:o.inputSchema,outputSchema:o.outputSchema??null}}return null}function xv(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var wv=9e4;async function xt(e,t,n={},r={}){let{connector:s,action:o}=xv(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(as(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??wv,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function us(e,t){let n=await l.get(as(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function kv(e,t){if(e&&typeof e=="object"){let n=e;for(let r of["reason","error","message","detail"])if(typeof n[r]=="string"&&n[r])return n[r]}return`HTTP ${t}`}function vv(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}async function ps(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(o["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=vv(I().backendUrl),a=as(e,"attachments"),c=await L(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new x(kv(d,c.status),{status:c.status,code:String(d&&typeof d=="object"?d.code??c.status:c.status),details:d,response:c,endpoint:a});return d}function Av(e){if(e.owner_type!=="project")return!1;let t=e.shared_with??[];return t.length===0||t.some(n=>n.principal_type==="project")}async function lc(e){return u(await l.get(`/projects/${e}/connections`))}async function uc(e){return u(await l.get(`/projects/${e}/connections/all`))}async function pc(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function dc(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function gc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Fe(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function Rv(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function Cv(e,t,n){return u(await l.put(Fe(e,t,"application"),n))}async function Tv(e,t){return u(await l.get(Fe(e,t,"application")))}async function Iv(e,t,n){return u(await l.post(Fe(e,t,"discover"),n))}async function Ev(e,t,n={}){return u(await l.post(Fe(e,t,"discover-resource"),n))}async function Mv(e,t,n){return u(await l.post(Fe(e,t,"register"),n))}async function Ov(e,t,n){return u(await l.post(Fe(e,t,"authorize"),n))}async function Dv(e,t,n){return u(await l.post(Fe(e,t,"device"),n))}async function jv(e,t,n){return u(await l.post(Fe(e,t,`device/${encodeURIComponent(n)}`),{}))}async function Lv(e,t){return u(await l.get(Fe(e,t,"status")))}async function mc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function fc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function yc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function hc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function _c(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function bc(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Pc(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function Sc(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function xc(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await l.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function wc(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function kc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function vc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Ac(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Rc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Cc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function $v(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function Uv(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Tc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Ic(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function ph(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var Ec=ph;async function Fv(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Mc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function Oc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function Nv(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function Dc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function jc(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}async function Lc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function Kv(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function Bv(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function ds(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function $c(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function gs(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var qv=ds,Gv=gs;async function Uc(){return u(await l.get("/connectors/connect-status"))}async function Fc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Nc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function Wv(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function dh(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Kc=dh;var In=class extends x{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds:c,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=s,this.action=o,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},ms=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},fs=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,s){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=s,Object.setPrototypeOf(this,new.target.prototype)}},Ce=e=>typeof e=="string"&&e?e:null;function gh(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function Vv(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function Hv(e,t,n){if(!(e instanceof x)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Ce(r.reason)??Ce(r.error)??e.message,o=/^upstream_(\d{3})\b/.exec(s),i=typeof r.upstream_status=="number"?r.upstream_status:o?Number(o[1]):null;return new In(Ce(r.message)??Ce(r.hint)??s,{status:e.status,code:i===null?gh(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Ce(r.connector)??t,action:Ce(r.action)??n,binding:Ce(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:Vv(e.response),connectUrl:Ce(r.connect_url),hint:Ce(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Ce(r.requested_account)})}function zv(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function ys(e,t,n,r={},s={}){let o=t.trim(),i=n.trim();if(!o||!i)throw new Error("connector slug and action are required");let a;try{a=await xt(e,`${o}.${i}`,r,s)}catch(c){throw Hv(c,o,i)}if(a.status==="pending_approval")throw new ms(o,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new In(c,{status:200,code:a.upstream_error?"upstream_error":gh(c),details:a,data:a,reason:c,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return zv(a)}async function*Bc(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,c=r;for(let p=0;c;p++){if(p>=i)throw new fs(t,n,i,c);let d=await ys(e,t,n,c,a);yield d,c=o(d,c)}}async function qc(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function Gc(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Wc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Vc(e){return u(await l.get(`/projects/${e}/snapshots`))}async function En(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Hc(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function zc(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Yc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Jc(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Qc(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Xc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Zc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Mn(e){let t=new URL(I().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Kortix backend: ${n.origin}`);let{headers:r}=await Zr(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function el(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function tl(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function nl(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await l.get(`/projects/${e}/files/search?${r.toString()}`))}async function rl(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var Yv=10*6e4;async function sl(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=`${I().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await Le(o,{method:"GET"},{timeoutMs:Yv},"Failed to download")).blob()}async function ol(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Mn(`${I().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function Jv(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${I().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await Le(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var il=52428800,Qv=104857600,mh=20;var _s=e=>`/projects/${encodeURIComponent(e)}/attachments`,bs={showErrors:!1,deadlineCoversBody:!0},fh=3e4,Xv=12e4,Zv=6e4,eA=5*6e4,tA=6e4,nA=6e4;function hs(){return new x("Request aborted",{name:"AbortError",code:"ABORTED"})}function On(e){if(e?.aborted)throw hs()}function rA(e){return!(e instanceof x)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Dn(e,t,n=!1){let r;for(let s=0;;s++){On(t);try{return await e()}catch(o){let i=n&&o instanceof x&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(rA(o)||i))throw o;r??=Date.now()+(n?eA:Zv);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await zr(a,t)}catch{throw On(t),o}}}}function sA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function al(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&sA(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!i)throw new Error("Invalid attachment upload handle");return e}async function yh(e,t,n,r){return u(await l.post(_s(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...bs,signal:n,timeout:fh}),"Failed to start attachment upload")}async function hh(e,t,n,r){let s=al({...await Dn(()=>yh(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function _h(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new x(r,{status:e,details:n,code:String(n?.statusCode??e)})}function oA(e){if(!(e instanceof x))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function iA(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?o(f):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new x("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},tA)},m=()=>{d(hs()),i.abort()};i.open(t.method,t.url);for(let[f,_]of Object.entries(t.headers))i.setRequestHeader(f,_);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(_h(i.status,i.responseText))},i.onerror=()=>d(new x("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(hs()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function aA(e,t,n){let r=I().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?hs():new x(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw _h(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function cA(e,t,n){On(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?iA(r,e,t,n):aA(e,t,n)}async function lA(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let i=s.upload;try{await Dn(()=>cA(i,t,r),r.signal)}catch(a){let c=oA(a);if(c!==409){if(o||!(c===400||c===401||c===403))throw a;o=!0,s=await hh(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return bh(e,t,s,r)}async function bh(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${_s(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){On(r.signal);let a=i.received_bytes,c=Math.min(a+s,t.size),p=t.slice(a,c),d=await Dn(async()=>u(await l.putRaw(`${o}/chunks/${a/s}`,p,{...bs,signal:r.signal,timeout:fh}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==c)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:c},r.onUpload?.(i),r.onProgress?.(c,t.size)}return i}async function jn(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");On(n.signal);let r=n.resume?al({...n.resume},t):al({...await Dn(()=>yh(e,t,n.signal),n.signal),received_bytes:0},t);n.onUpload?.(r),r.received_bytes<t.size&&(r.upload.kind==="direct"&&Date.parse(r.upload.expires_at)-Date.now()<nA&&(r=await hh(e,t,r,n)),r=r.upload.kind==="direct"?await lA(e,t,r,n):await bh(e,t,r,n)),n.onProcessing?.();let s=`${_s(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Dn(async()=>u(await l.post(`${s}/complete`,{},{...bs,signal:n.signal,timeout:Xv}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof x&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Ft(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${_s(e)}/${encodeURIComponent(t)}`,{...bs,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function cl(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/branches${r}`))}async function ll(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/commits${r}`))}async function ul(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function pl(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function dl(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await l.get(`/projects/${e}/files/history?${r.toString()}`))}async function gl(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await l.get(`/projects/${e}/version-diff?${n.toString()}`))}async function ml(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit)),n?.cursor&&r.set("cursor",n.cursor);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function fl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function yl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function hl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function _l(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function bl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Pl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Sl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function xl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function wl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function kl(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var Nt=new Set,uA=500;function Ln(e){e&&(Nt.add(e),Nt.size>uA&&Nt.delete(Nt.values().next().value))}function vl(e){return!!e&&Nt.has(e)}function pA(e){e&&Nt.delete(e)}var ce="kortix.session/2",_e=1,Ph=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var se=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),H=e=>typeof e=="string",Te=e=>H(e)&&e.length>0,Ke=e=>e===null||H(e),Y=(e,t)=>e===void 0||t(e),Ne=(...e)=>t=>e.includes(t),$n=e=>Number.isInteger(e)&&e>=0,Kt=e=>typeof e=="number",wh=e=>e.schema===ce&&$n(e.v),wt=e=>Y(e,H),Al=e=>e===void 0||se(e)&&Object.values(e).every(t=>se(t)&&H(t.version)),kh=e=>e===null||se(e)&&H(e.provider)&&H(e.model)&&wt(e.variant),dA=e=>e===null||se(e)&&Kt(e.input)&&Kt(e.output)&&Kt(e.cache_read)&&Kt(e.cache_write)&&Y(e.reasoning,Kt)&&Y(e.cost,Kt),Sh=e=>se(e)&&(e.type==="text"&&H(e.text)||e.type==="attachment"&&H(e.mime)),gA=e=>se(e)&&Array.isArray(e.content)&&e.content.every(Sh)&&Y(e.model_content,t=>Array.isArray(t)&&t.every(Sh))&&typeof e.is_error=="boolean",xh={text:e=>H(e.text)&&Y(e.bytes,$n)&&wt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>H(e.text),attachment:e=>H(e.mime)&&wt(e.ref)&&Y(e.bytes,$n)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>H(e.call_id)&&H(e.name)&&Te(e.kind)&&Ne("pending","running","complete","error")(e.status)&&Y(e.result,gA),compaction:e=>Ke(e.summary)&&Ke(e.first_kept_message_id),subtask:e=>H(e.thread_id)&&H(e.agent)&&H(e.description),step:e=>Ne("start","finish")(e.phase),harness:e=>Te(e.harness)&&Te(e.kind)&&typeof e.model_visible=="boolean"};function mA(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!se(r)||!Te(r.id)||n.has(r.id)||!Object.hasOwn(xh,r.type)||!xh[r.type](r)||!Al(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function fA(e){return se(e)&&wh(e)&&Te(e.message_id)&&Te(e.thread_id)&&Number.isInteger(e.seq)&&Ne("user","assistant","system")(e.role)&&Ne("turn","compaction","context")(e.kind)&&Ne("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&Y(e.hidden_reason,Ne("failed_attempt","aborted","retracted","reverted","superseded"))&&Y(e.origin,Ne("prompt","steer","command","automation","subagent","notification"))&&Y(e.agent,Ke)&&Y(e.reply_to,Ke)&&Y(e.parent_message_id,Ke)&&wt(e.native_agent_id)&&wt(e.context_ref)&&kh(e.model)&&dA(e.usage)&&Ne("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||se(e.error)&&Te(e.error.code)&&H(e.error.message))&&H(e.created_at)&&Ke(e.completed_at)&&se(e.producer)&&Te(e.producer.harness)&&H(e.producer.harness_version)&&H(e.producer.adapter_version)&&Al(e.ext)&&mA(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function yA(e){return se(e)&&wh(e)&&Te(e.thread_id)&&Ke(e.parent_thread_id)&&(e.spawned_by===null||se(e.spawned_by))&&H(e.created_at)}function hA(e){return se(e)&&Y(e.schema,t=>t===ce)&&Y(e.v,$n)&&wt(e.session_id)&&Y(e.title,Ke)&&wt(e.created_at)&&Y(e.restore_grade,Ne("native","converted","partial"))&&Y(e.todos,Array.isArray)&&Y(e.pending,t=>se(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&Y(e.selection,t=>se(t)&&Y(t.agent,Ke)&&kh(t.model??null))&&Y(e.harness,t=>se(t)&&H(t.current)&&Array.isArray(t.history))&&Al(e.ext)}function Ps(e){return se(e)&&$n(e.generation)&&typeof e.has_more=="boolean"&&hA(e.session)&&Array.isArray(e.threads)&&e.threads.every(yA)&&(e.thread_id===null||Te(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>fA(t)&&t.thread_id===e.thread_id)}var _A=e=>Ps(e)&&e.messages.length>0;function bA(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let s=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(s.length<=t)return s}return null}var vh={paintable:_A,fit:bA,capturedAt:()=>0},PA=new WeakMap;function Ah(e,t,n){PA.set(e,{read:(r,s)=>t.read(r,s),write:async(r,s,o)=>{await t.write(r,s,o),await n(r,s)}})}function Ss(e){return!!e&&typeof e.then=="function"}function Rh(e,t){return Ss(e)?e.then(t):t(e)}function Ch(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=R=>{try{let T=t.getItem(R);return Ss(T)?T.catch(()=>null):T}catch{return null}},c=async R=>{try{await t.removeItem(R)}catch{}},p=R=>{if(!R)return[];try{let T=JSON.parse(R);return T?.v===1&&Array.isArray(T.entries)?T.entries:[]}catch{return[]}},d=Promise.resolve(),g=R=>{let T=d.then(R,R);return d=T.catch(()=>{}),T},m=async R=>{try{await t.setItem(i,JSON.stringify({v:1,entries:R}))}catch{}},f=async()=>p(await a(i));return{indexKey:i,safeGet:a,safeRemove:c,enqueue:g,loadIndex:f,saveIndex:m,evict:async(R,T)=>{let b=[...R].sort((h,S)=>h.u-S.u),M=b.reduce((h,S)=>h+S.b,0);for(;b.length>r||M>s;){let h=b.findIndex(P=>P.s!==T);if(h===-1)break;let[S]=b.splice(h,1);M-=S.b,await c(`${n}${S.s}`)}return b},touch:R=>{g(async()=>{let T=await f(),b=T.find(M=>M.s===R);b&&(b.u=o(),await m(T))})},forgetScope:R=>g(async()=>{await c(`${n}${R}`);let T=await f(),b=T.filter(M=>M.s!==R);b.length!==T.length&&await m(b)})}}function Eh(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var SA=12,xA=15e5,wA=3e5,kA=336*60*60*1e3,Mh="kortix.saved-copy";function vA(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},o=s(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(o+a>t)break;o+=a,i+=1}for(;i>0;i-=1){let a=s(i);if(a.length<=t)return a}return null}function AA(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var RA={paintable:Eh,fit:vA,capturedAt:AA};function CA(e){let t=Ih(e,RA),n=Ih({...e,namespace:`${e.namespace??Mh}.log`},vh),r={...t,remove:async(s,o)=>{await Promise.all([t.remove(s,o),n.remove(s,o)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return Ah(r,n,t.remove),r}function Ih(e,t){let{storage:n,userId:r,maxSessions:s=SA,maxBytes:o=xA,maxEnvelopeBytes:i=wA,maxAgeMs:a=kA,namespace:c=Mh,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,g=Ch({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:_,enqueue:y,loadIndex:v,saveIndex:R,evict:T,touch:b,forgetScope:M}=g,h=(P,k)=>`${d}${P}/${k}`,S=P=>{try{let k=n.removeItem(P);Ss(k)&&k.catch(()=>{})}catch{}};return{keyFor:h,read(P,k){let C=`${P}/${k}`;return Rh(f(h(P,k)),j=>{if(!j)return null;let w;try{w=JSON.parse(j)}catch{return S(h(P,k)),M(C),null}return!w||w.v!==1||w.user!==r||p()-w.at>a||!t.paintable(w.e)?(S(h(P,k)),M(C),null):(b(C),w.e)})},write(P,k,C){let j=`${P}/${k}`;if(!t.paintable(C))return M(j);let w={v:1,user:r,at:p(),e:C},D=t.fit(w,i);if(D===null)return M(j);let xe=t.capturedAt(C);return y(async()=>{let N=await v(),z=N.find(ft=>ft.s===j);if(z&&xe>0&&z.c>xe)return;let G=N.filter(ft=>ft.s!==j),B={s:j,b:D.length,u:p(),c:xe},je=await T([...G,B],j),si=h(P,k);try{await n.setItem(si,D)}catch{let ft=je.filter(yt=>yt.s!==j).sort((yt,yk)=>yt.u-yk.u)[0];ft&&(await _(`${d}${ft.s}`),je=je.filter(yt=>yt.s!==ft.s));try{await n.setItem(si,D)}catch{await _(si),je=je.filter(yt=>yt.s!==j)}}await R(je)})},remove(P,k){return M(`${P}/${k}`)},clear(){return y(async()=>{let P=await v();for(let k of P)await _(`${d}${k.s}`);await _(m)})}}}var Oh=null;function TA(e){Oh=e}function Rl(){return Oh}var IA=new Set;function Dh(e){for(let t of IA)try{t(e)}catch{}}var jh=async(e,t,n,r)=>{let s=new URLSearchParams;n.thread!==void 0&&s.set("thread",n.thread),n.before_seq!==void 0&&s.set("before_seq",String(n.before_seq)),n.limit!==void 0&&s.set("limit",String(n.limit));let o=s.toString(),i=await l.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${o?`?${o}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data};function EA(e){let t=typeof e.parent_session_id=="string"?e.parent_session_id:e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var MA=50,Lh=200,OA=Lh;function $h(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function Cl(e,t){let n=await l.get(`/projects/${e}/sessions${$h(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function kt(e,t){return u(await l.get(`/projects/${e}/sessions${$h(t)}`))}async function Tl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Il(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function El(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Ml(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Ol(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Dl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function DA(e,t){let n=e.public_url??e.public_path??e.proxy_path??e.public_token??"";if(!n)return"";if(/^https?:\/\//.test(n))return n;if(t)try{return new URL(n,t).toString()}catch{return n}return n}function jA(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function jl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Ll(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function $l(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Ul(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function vt(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Ln(n?.session_id),n}async function Fl(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Ln(r.session.session_id),r}async function Nl(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Ln(n.session_id),n}async function Un(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Kl(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function Bl(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function Fn(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function ql(e,t,n={},r){let s;try{s=await jh(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Ps(s))throw new Error("The response is not a session log page");return s}async function Nn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function LA(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function $A(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Kn(e,t,n){let r=n.placement??$A(n.delivery);return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Gl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Wl(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Vl(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Hl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function zl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Yl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Jl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function Ql(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return Rl()?.remove(e,t),n}async function Xl(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function Zl(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Bn(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function qn(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return Dh(t),n}async function eu(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function UA(e){let t=e.split(`
7
+ `);let m=Ev(g);if(m){if(t(m),m.type==="error")throw new S(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{o.cancel().catch(()=>{})}if(!a)throw new S("Provision stream ended without a result",{code:Rh});return a}async function Ov(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await c.get(`/projects/quota${t}`))}async function Dv(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function On(e,t){return u(await c.patch(`/projects/${e}`,t))}async function sa(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function ia(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function aa(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function Lv(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function jv(e,t){throw F("updateTemplateWarmPool")}async function ca(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function $v(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Dn(e){return u(await c.delete(`/projects/${e}`))}async function Uv(e,t){return $t(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function Fv(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Ti(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let o=await r.json().catch(()=>null);return o?.project_id?{ok:!0,project:o}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function la(e,t,n){return u(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function ua(e,t,n){return u(await c.post(`/projects/${e}/skills/remove`,t,{showErrors:!1,...n}))}async function Nv(e){return u(await c.get(`/projects/${e}/git/connection`),"Failed to read the Git connection")}async function pa(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function da(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function ga(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ma(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function fa(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function ya(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let o=n?.search?.trim();return o&&r.set("search",o),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await c.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function ha(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await c.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function _a(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function ba(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Pa(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function Sa(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await c.delete(`/projects/github/installation?${n.toString()}`))}async function xa(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function wa(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await c.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function Bv(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function ka(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function va(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Aa(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Ra(e){return u(await c.get(`/projects/${e}/access`))}async function Ca(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function Ta(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function Kv(e){return"status"in e&&e.status==="invited"}async function Ia(e,t,n,r){return u(await c.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Ea(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function Ma(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Oa(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Da(e){return u(await c.get(`/projects/${e}/group-grants`))}async function La(e,t,n,r){return u(await c.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function ja(e,t,n,r){return u(await c.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function $a(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function Ua(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function Fa(e,t){return u(await c.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function Na(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function Ba(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Ka(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function qa(e,t,n,r={}){let o=r.note?.trim();return u(await c.post(`/projects/${e}/approvals/${t}`,{decision:n,...o?{note:o}:{}}))}async function Ga(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Wa(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function Ha(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Va(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function za(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function uo(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function po(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Ya(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var qv=2e3,Gv=3e3,Wv=10*6e4;async function Hv(e){let{projectId:t,provider:n,input:r,onChallenge:o,isCancelled:s,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,l=()=>s?.()??!1,p=await uo(t,n,r);if(l())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(qv,p.interval_ms||Gv),g=p.expires_at||a()+Wv;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await po(t,n,p.flow_id)}catch{continue}if(l())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return l()?{status:"cancelled"}:{status:"expired"}}async function Ja(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function Ln(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Qa(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Xa(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var Za=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Ut=(e,t)=>`${Za(e)}/${encodeURIComponent(t)}`,Ch=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function ec(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${Za(e)}${n}`))}async function tc(e,t){return u(await c.post(Za(e),t))}async function nc(e,t,n){return u(await c.put(`${Ut(e,t)}/value`,{value:n}))}async function rc(e,t){return u(await c.post(`${Ut(e,t)}/retry`))}async function oc(e,t){return u(await c.delete(Ut(e,t)))}async function sc(e,t,n,r){return u(await c.put(`${Ut(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function ic(e,t,n,r){return u(await c.delete(`${Ut(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function ac(e,t,n,r){return u(await c.put(`${Ut(e,t)}/access`,{mode:n,user_ids:r}))}async function cc(e,t,n){return u(await c.get(Ch(e,t,n)))}async function lc(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function uc(e,t,n,r){return u(await c.put(Ch(e,t,n),{secret_ids:r}))}async function go(){return Ci()}async function Th(e){return eo(()=>C().getToken(),e,mo)}function mo(){Tn()}function Vv(e){e===null&&Tn()}function zv(e){}async function Ft(){return go()}async function Yv(e){return Th(e)}async function j(e,t,n){try{return await St(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof re)return to();throw r}}function fo(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Nt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`${fo(e,"catalog")}${r}`)).connectors??[]}async function yo(e){let t=[];for(let n of await Nt(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function pc(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await yo(e)){let l=`${a.tool} ${a.description}`.toLowerCase();!r||l.includes(r)?s.push(a):o.every(p=>l.includes(p))&&i.push(a)}return[...s,...i].slice(0,n.limit??20)}async function ho(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let o=(await Nt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===r);if(!o)return null;for(let s of o.actions){let i=`${o.slug}.${s.path}`;if(i===t)return{tool:i,connector:o.slug,action:s.path,risk:s.risk,description:s.description||s.name,inputSchema:s.inputSchema,outputSchema:s.outputSchema??null}}return null}function Jv(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var Qv=9e4;async function kt(e,t,n={},r={}){let{connector:o,action:s}=Jv(t),i=r.account?.trim(),a=r.approvalContext?.trim(),l=u(await c.post(fo(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??Qv,signal:r.signal}));return l.ok&&l.binding!==void 0&&!("output"in l)&&(l.output=l.data),l}async function _o(e,t){let n=await c.get(fo(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function Xv(e,t){if(e&&typeof e=="object"){let n=e;for(let r of["reason","error","message","detail"])if(typeof n[r]=="string"&&n[r])return n[r]}return`HTTP ${t}`}function Zv(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}async function bo(e,t,n){let r=n.filename.trim(),o=n.contentType.trim();if(!r)throw new Error("filename is required");if(!o)throw new Error("contentType is required");let s={"Content-Type":o,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(s["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(s["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=Zv(C().backendUrl),a=fo(e,"attachments"),l=await j(`${i}${a}`,{method:"POST",headers:s,body:t},{timeoutMs:6e4}),p=await l.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!l.ok)throw new S(Xv(d,l.status),{status:l.status,code:String(d&&typeof d=="object"?d.code??l.status:l.status),details:d,response:l,endpoint:a});return d}function eA(e){if(e.owner_type!=="project")return!1;let t=e.shared_with??[];return t.length===0||t.some(n=>n.principal_type==="project")}async function dc(e){return u(await c.get(`/projects/${e}/connections`))}async function gc(e){return u(await c.get(`/projects/${e}/connections/all`))}async function mc(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function fc(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function yc(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function Fe(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function tA(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function nA(e,t,n){return u(await c.put(Fe(e,t,"application"),n))}async function rA(e,t){return u(await c.get(Fe(e,t,"application")))}async function oA(e,t,n){return u(await c.post(Fe(e,t,"discover"),n))}async function sA(e,t,n={}){return u(await c.post(Fe(e,t,"discover-resource"),n))}async function iA(e,t,n){return u(await c.post(Fe(e,t,"register"),n))}async function aA(e,t,n){return u(await c.post(Fe(e,t,"authorize"),n))}async function cA(e,t,n){return u(await c.post(Fe(e,t,"device"),n))}async function lA(e,t,n){return u(await c.post(Fe(e,t,`device/${encodeURIComponent(n)}`),{}))}async function uA(e,t){return u(await c.get(Fe(e,t,"status")))}async function hc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function _c(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function bc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function Pc(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Sc(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function xc(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function wc(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function kc(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function vc(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await c.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function Ac(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Rc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Cc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Tc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Ic(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Ec(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function pA(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function dA(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Mc(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Oc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Ih(e,t,n={}){return u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var Dc=Ih;async function gA(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Lc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function jc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function mA(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function $c(e){return u(await c.get(`/projects/${e}/connector-moves`)).moves}async function Uc(e,t,n={}){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function Fc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Nc(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/apps${s?`?${s}`:""}`))}async function Bc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function fA(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),o=u(await c.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in o)return o;let s=o.cursor?.trim()||void 0;return{provider:"composio",toolkits:o.items,nextCursor:s,hasMore:!!s}}async function yA(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function Po(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await c.get(`/connectors/projects/${e}/discover/connectors${s?`?${s}`:""}`))}async function Kc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function So(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var hA=Po,_A=So;async function qc(){return u(await c.get("/connectors/connect-status"))}async function Gc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Wc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function bA(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Eh(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Hc=Eh;var jn=class extends S{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:o,action:s,binding:i,upstreamStatus:a,retryAfterSeconds:l,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=o,this.action=s,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=l??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},xo=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},wo=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,o){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=o,Object.setPrototypeOf(this,new.target.prototype)}},Ce=e=>typeof e=="string"&&e?e:null;function Mh(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function PA(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function SA(e,t,n){if(!(e instanceof S)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},o=Ce(r.reason)??Ce(r.error)??e.message,s=/^upstream_(\d{3})\b/.exec(o),i=typeof r.upstream_status=="number"?r.upstream_status:s?Number(s[1]):null;return new jn(Ce(r.message)??Ce(r.hint)??o,{status:e.status,code:i===null?Mh(o):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:o,connector:Ce(r.connector)??t,action:Ce(r.action)??n,binding:Ce(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:PA(e.response),connectUrl:Ce(r.connect_url),hint:Ce(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Ce(r.requested_account)})}function xA(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function ko(e,t,n,r={},o={}){let s=t.trim(),i=n.trim();if(!s||!i)throw new Error("connector slug and action are required");let a;try{a=await kt(e,`${s}.${i}`,r,o)}catch(l){throw SA(l,s,i)}if(a.status==="pending_approval")throw new xo(s,i,a);if(!a.ok||a.upstream_error){let l=a.upstream_error??a.reason??"connector_error";throw new jn(l,{status:200,code:a.upstream_error?"upstream_error":Mh(l),details:a,data:a,reason:l,connector:s,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return xA(a)}async function*Vc(e,t,n,r,o){let{next:s,maxPages:i=100,...a}=o,l=r;for(let p=0;l;p++){if(p>=i)throw new wo(t,n,i,l);let d=await ko(e,t,n,l,a);yield d,l=s(d,l)}}async function zc(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function Yc(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Jc(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Qc(e){return u(await c.get(`/projects/${e}/snapshots`))}async function $n(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Xc(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Zc(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function el(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function tl(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function nl(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function rl(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function ol(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Un(e){let t=new URL(C().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Kortix backend: ${n.origin}`);let{headers:r}=await jt(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function sl(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function il(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await c.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function al(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await c.get(`/projects/${e}/files/search?${r.toString()}`))}async function cl(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await c.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var wA=10*6e4;async function ll(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=`${C().backendUrl||""}/projects/${e}/files/archive${o}`;return await(await je(s,{method:"GET"},{timeoutMs:wA},"Failed to download")).blob()}async function ul(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"";return Un(`${C().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${o}`)}async function kA(e,t,n,r){let o=new URLSearchParams({path:t});n&&o.set("ref",n);let s=o.toString()?`?${o.toString()}`:"",i=`${C().backendUrl||""}/projects/${e}/files/raw${s}`;return await(await je(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var pl=52428800,vA=104857600,Oh=20;var Ao=e=>`/projects/${encodeURIComponent(e)}/attachments`,Ro={showErrors:!1,deadlineCoversBody:!0},Dh=3e4,AA=12e4,RA=6e4,CA=5*6e4,TA=6e4,IA=6e4;function vo(){return new S("Request aborted",{name:"AbortError",code:"ABORTED"})}function Fn(e){if(e?.aborted)throw vo()}function EA(e){return!(e instanceof S)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Nn(e,t,n=!1){let r;for(let o=0;;o++){Fn(t);try{return await e()}catch(s){let i=n&&s instanceof S&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(EA(s)||i))throw s;r??=Date.now()+(n?CA:RA);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await no(a,t)}catch{throw Fn(t),s}}}}function MA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function dl(e,t,n){let r=e?.upload,o=e?.received_bytes,s=Number.isSafeInteger(o)&&o>=0&&o<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&MA(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(o===0||o===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(o===t.size||o%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!s||!i)throw new Error("Invalid attachment upload handle");return e}async function Lh(e,t,n,r){return u(await c.post(Ao(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Ro,signal:n,timeout:Dh}),"Failed to start attachment upload")}async function jh(e,t,n,r){let o=dl({...await Nn(()=>Lh(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function $h(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new S(r,{status:e,details:n,code:String(n?.statusCode??e)})}function OA(e){if(!(e instanceof S))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function DA(e,t,n,r){return new Promise((o,s)=>{let i=new e,a=0,l=!1,p,d=f=>{l||(l=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?s(f):o())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new S("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},TA)},m=()=>{d(vo()),i.abort()};i.open(t.method,t.url);for(let[f,_]of Object.entries(t.headers))i.setRequestHeader(f,_);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d($h(i.status,i.responseText))},i.onerror=()=>d(new S("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(vo()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function LA(e,t,n){let r=C().fetch??fetch,o;try{o=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(s){throw n.signal?.aborted||s instanceof Error&&s.name==="AbortError"?vo():new S(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw $h(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function jA(e,t,n){Fn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?DA(r,e,t,n):LA(e,t,n)}async function $A(e,t,n,r){let o=n,s=!1;for(r.onProgress?.(0,t.size);o.upload.kind==="direct";){let i=o.upload;try{await Nn(()=>jA(i,t,r),r.signal)}catch(a){let l=OA(a);if(l!==409){if(s||!(l===400||l===401||l===403))throw a;s=!0,o=await jh(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return Uh(e,t,o,r)}async function Uh(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${Ao(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Fn(r.signal);let a=i.received_bytes,l=Math.min(a+o,t.size),p=t.slice(a,l),d=await Nn(async()=>u(await c.putRaw(`${s}/chunks/${a/o}`,p,{...Ro,signal:r.signal,timeout:Dh}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==l)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:l},r.onUpload?.(i),r.onProgress?.(l,t.size)}return i}async function Bn(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");Fn(n.signal);let r=n.resume?dl({...n.resume},t):dl({...await Nn(()=>Lh(e,t,n.signal),n.signal),received_bytes:0},t);n.onUpload?.(r),r.received_bytes<t.size&&(r.upload.kind==="direct"&&Date.parse(r.upload.expires_at)-Date.now()<IA&&(r=await jh(e,t,r,n)),r=r.upload.kind==="direct"?await $A(e,t,r,n):await Uh(e,t,r,n)),n.onProcessing?.();let o=`${Ao(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Nn(async()=>u(await c.post(`${o}/complete`,{},{...Ro,signal:n.signal,timeout:AA}),"Failed to complete attachment upload"),n.signal,!0)}catch(s){throw r.upload.kind==="direct"&&s instanceof S&&s.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),s}}async function Bt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${Ao(e)}/${encodeURIComponent(t)}`,{...Ro,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function gl(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/branches${r}`))}async function ml(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/commits${r}`))}async function fl(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function yl(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let o=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${o}`))}async function hl(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await c.get(`/projects/${e}/files/history?${r.toString()}`))}async function _l(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await c.get(`/projects/${e}/version-diff?${n.toString()}`))}async function bl(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit)),n?.cursor&&r.set("cursor",n.cursor);let o=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/change-requests${o}`,{showErrors:!1,timeout:15e3}))}async function Pl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function Sl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function xl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function wl(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function kl(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function vl(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Al(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Rl(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Cl(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function Tl(e,t,n){return u(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var Kt=new Set,UA=500;function Kn(e){e&&(Kt.add(e),Kt.size>UA&&Kt.delete(Kt.values().next().value))}function Il(e){return!!e&&Kt.has(e)}function FA(e){e&&Kt.delete(e)}var ce="kortix.session/2",he=1,Fh=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var oe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),V=e=>typeof e=="string",Te=e=>V(e)&&e.length>0,Be=e=>e===null||V(e),Y=(e,t)=>e===void 0||t(e),Ne=(...e)=>t=>e.includes(t),qn=e=>Number.isInteger(e)&&e>=0,qt=e=>typeof e=="number",Kh=e=>e.schema===ce&&qn(e.v),vt=e=>Y(e,V),El=e=>e===void 0||oe(e)&&Object.values(e).every(t=>oe(t)&&V(t.version)),qh=e=>e===null||oe(e)&&V(e.provider)&&V(e.model)&&vt(e.variant),NA=e=>e===null||oe(e)&&qt(e.input)&&qt(e.output)&&qt(e.cache_read)&&qt(e.cache_write)&&Y(e.reasoning,qt)&&Y(e.cost,qt),Nh=e=>oe(e)&&(e.type==="text"&&V(e.text)||e.type==="attachment"&&V(e.mime)),BA=e=>oe(e)&&Array.isArray(e.content)&&e.content.every(Nh)&&Y(e.model_content,t=>Array.isArray(t)&&t.every(Nh))&&typeof e.is_error=="boolean",Bh={text:e=>V(e.text)&&Y(e.bytes,qn)&&vt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>V(e.text),attachment:e=>V(e.mime)&&vt(e.ref)&&Y(e.bytes,qn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>V(e.call_id)&&V(e.name)&&Te(e.kind)&&Ne("pending","running","complete","error")(e.status)&&Y(e.result,BA),compaction:e=>Be(e.summary)&&Be(e.first_kept_message_id),subtask:e=>V(e.thread_id)&&V(e.agent)&&V(e.description),step:e=>Ne("start","finish")(e.phase),harness:e=>Te(e.harness)&&Te(e.kind)&&typeof e.model_visible=="boolean"};function KA(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!oe(r)||!Te(r.id)||n.has(r.id)||!Object.hasOwn(Bh,r.type)||!Bh[r.type](r)||!El(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function Ml(e){return oe(e)&&Kh(e)&&Te(e.message_id)&&Te(e.thread_id)&&Number.isInteger(e.seq)&&Ne("user","assistant","system")(e.role)&&Ne("turn","compaction","context")(e.kind)&&Ne("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&Y(e.hidden_reason,Ne("failed_attempt","aborted","retracted","reverted","superseded"))&&Y(e.origin,Ne("prompt","steer","command","automation","subagent","notification"))&&Y(e.agent,Be)&&Y(e.reply_to,Be)&&Y(e.parent_message_id,Be)&&vt(e.native_agent_id)&&vt(e.context_ref)&&qh(e.model)&&NA(e.usage)&&Ne("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||oe(e.error)&&Te(e.error.code)&&V(e.error.message))&&V(e.created_at)&&Be(e.completed_at)&&oe(e.producer)&&Te(e.producer.harness)&&V(e.producer.harness_version)&&V(e.producer.adapter_version)&&El(e.ext)&&KA(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function Ol(e){return oe(e)&&Kh(e)&&Te(e.thread_id)&&Be(e.parent_thread_id)&&(e.spawned_by===null||oe(e.spawned_by))&&V(e.created_at)}function qA(e){return oe(e)&&Y(e.schema,t=>t===ce)&&Y(e.v,qn)&&vt(e.session_id)&&Y(e.title,Be)&&vt(e.created_at)&&Y(e.restore_grade,Ne("native","converted","partial"))&&Y(e.todos,Array.isArray)&&Y(e.pending,t=>oe(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&Y(e.selection,t=>oe(t)&&Y(t.agent,Be)&&qh(t.model??null))&&Y(e.harness,t=>oe(t)&&V(t.current)&&Array.isArray(t.history))&&El(e.ext)}function Gt(e){return oe(e)&&qn(e.generation)&&typeof e.has_more=="boolean"&&qA(e.session)&&Array.isArray(e.threads)&&e.threads.every(Ol)&&(e.thread_id===null||Te(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>Ml(t)&&t.thread_id===e.thread_id)}var GA=e=>Gt(e)&&e.messages.length>0;function WA(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let o=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(o.length<=t)return o}return null}var Gh={paintable:GA,fit:WA,capturedAt:()=>0},HA=new WeakMap;function Wh(e,t,n){HA.set(e,{read:(r,o)=>t.read(r,o),write:async(r,o,s)=>{await t.write(r,o,s),await n(r,o)}})}function Co(e){return!!e&&typeof e.then=="function"}function Hh(e,t){return Co(e)?e.then(t):t(e)}function Vh(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:o,now:s}=e,i=`${n}index`,a=R=>{try{let I=t.getItem(R);return Co(I)?I.catch(()=>null):I}catch{return null}},l=async R=>{try{await t.removeItem(R)}catch{}},p=R=>{if(!R)return[];try{let I=JSON.parse(R);return I?.v===1&&Array.isArray(I.entries)?I.entries:[]}catch{return[]}},d=Promise.resolve(),g=R=>{let I=d.then(R,R);return d=I.catch(()=>{}),I},m=async R=>{try{await t.setItem(i,JSON.stringify({v:1,entries:R}))}catch{}},f=async()=>p(await a(i));return{indexKey:i,safeGet:a,safeRemove:l,enqueue:g,loadIndex:f,saveIndex:m,evict:async(R,I)=>{let b=[...R].sort((h,x)=>h.u-x.u),M=b.reduce((h,x)=>h+x.b,0);for(;b.length>r||M>o;){let h=b.findIndex(P=>P.s!==I);if(h===-1)break;let[x]=b.splice(h,1);M-=x.b,await l(`${n}${x.s}`)}return b},touch:R=>{g(async()=>{let I=await f(),b=I.find(M=>M.s===R);b&&(b.u=s(),await m(I))})},forgetScope:R=>g(async()=>{await l(`${n}${R}`);let I=await f(),b=I.filter(M=>M.s!==R);b.length!==I.length&&await m(b)})}}function Jh(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var VA=12,zA=15e5,YA=3e5,JA=336*60*60*1e3,Qh="kortix.saved-copy";function QA(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let o=a=>{let l=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:l,message_count:l.length,complete:!1,next_cursor:String(l[0].info.id)}})},s=o(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(s+a>t)break;s+=a,i+=1}for(;i>0;i-=1){let a=o(i);if(a.length<=t)return a}return null}function XA(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var ZA={paintable:Jh,fit:QA,capturedAt:XA};function eR(e){let t=Yh(e,ZA),n=Yh({...e,namespace:`${e.namespace??Qh}.log`},Gh),r={...t,remove:async(o,s)=>{await Promise.all([t.remove(o,s),n.remove(o,s)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return Wh(r,n,t.remove),r}function Yh(e,t){let{storage:n,userId:r,maxSessions:o=VA,maxBytes:s=zA,maxEnvelopeBytes:i=YA,maxAgeMs:a=JA,namespace:l=Qh,now:p=()=>Date.now()}=e,d=`${l}:${r}:`,g=Vh({storage:n,prefix:d,maxSessions:o,maxBytes:s,now:p}),{indexKey:m,safeGet:f,safeRemove:_,enqueue:y,loadIndex:k,saveIndex:R,evict:I,touch:b,forgetScope:M}=g,h=(P,v)=>`${d}${P}/${v}`,x=P=>{try{let v=n.removeItem(P);Co(v)&&v.catch(()=>{})}catch{}};return{keyFor:h,read(P,v){let T=`${P}/${v}`;return Hh(f(h(P,v)),L=>{if(!L)return null;let w;try{w=JSON.parse(L)}catch{return x(h(P,v)),M(T),null}return!w||w.v!==1||w.user!==r||p()-w.at>a||!t.paintable(w.e)?(x(h(P,v)),M(T),null):(b(T),w.e)})},write(P,v,T){let L=`${P}/${v}`;if(!t.paintable(T))return M(L);let w={v:1,user:r,at:p(),e:T},D=t.fit(w,i);if(D===null)return M(L);let Se=t.capturedAt(T);return y(async()=>{let N=await k(),z=N.find(ht=>ht.s===L);if(z&&Se>0&&z.c>Se)return;let G=N.filter(ht=>ht.s!==L),K={s:L,b:D.length,u:p(),c:Se},Le=await I([...G,K],L),ai=h(P,v);try{await n.setItem(ai,D)}catch{let ht=Le.filter(_t=>_t.s!==L).sort((_t,Kk)=>_t.u-Kk.u)[0];ht&&(await _(`${d}${ht.s}`),Le=Le.filter(_t=>_t.s!==ht.s));try{await n.setItem(ai,D)}catch{await _(ai),Le=Le.filter(_t=>_t.s!==L)}}await R(Le)})},remove(P,v){return M(`${P}/${v}`)},clear(){return y(async()=>{let P=await k();for(let v of P)await _(`${d}${v.s}`);await _(m)})}}}var Xh=null;function tR(e){Xh=e}function Dl(){return Xh}var nR=new Set;function Zh(e){for(let t of nR)try{t(e)}catch{}}var rR=new Set;function e_(e){for(let t of rR)try{t(e)}catch{}}var Gn=async(e,t,n,r)=>{let o=new URLSearchParams;n.thread!==void 0&&o.set("thread",n.thread),n.before_seq!==void 0&&o.set("before_seq",String(n.before_seq)),n.limit!==void 0&&o.set("limit",String(n.limit));let s=o.toString(),i=await c.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${s?`?${s}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data},oR=40;async function sR(e,t,n,r,o){try{let s=await e(t,n,r,o);return Gt(s)?s:null}catch{return null}}function t_(e,t,n,r){return sR(e,t,n,{limit:oR},r)}function iR(e){let t=typeof e.parent_session_id=="string"?e.parent_session_id:e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var aR=50,n_=200,cR=n_;function r_(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function Ll(e,t){let n=await c.get(`/projects/${e}/sessions${r_(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function At(e,t){return u(await c.get(`/projects/${e}/sessions${r_(t)}`))}async function jl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function $l(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Ul(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Fl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Nl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Bl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function lR(e,t){let n=e.public_url??e.public_path??e.proxy_path??e.public_token??"";if(!n)return"";if(/^https?:\/\//.test(n))return n;if(t)try{return new URL(n,t).toString()}catch{return n}return n}function uR(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function Kl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function ql(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Gl(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Wl(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Rt(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return!t?.initial_prompt&&!t?.fork_from_session_id&&Kn(n?.session_id),n}async function Hl(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await c.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Kn(r.session.session_id),r}async function Vl(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Kn(n.session_id),n}async function Wn(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function zl(e,t,n,r){let o=new URLSearchParams;n&&o.set("limit",String(n)),r?.cursor&&o.set("cursor",r.cursor),r?.includeEvents!=null&&o.set("include_events",String(r.includeEvents));let s=o.toString();return u(await c.get(`/projects/${e}/sessions/${t}/audit${s?`?${s}`:""}`,{showErrors:r?.showErrors}))}async function Yl(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let o=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/transcript${o?`?${o}`:""}`))}async function Hn(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await c.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Jl(e,t,n={},r){let o;try{o=await Gn(e,t,n,r?.signal)}catch(s){if(s?.status===404)return null;throw s}if(!Gt(o))throw new Error("The response is not a session log page");return o}async function Vn(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function pR(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let o=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/snapshot${o?`?${o}`:""}`,{signal:n?.signal,showErrors:!1}))}function dR(e){if(e)return e==="interrupt"?"transcript":"composer"}async function zn(e,t,n){let r=n.placement??dR(n.delivery);return u(await c.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Ql(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Xl(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Zl(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function eu(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function tu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function nu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function ru(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function ou(e,t){let n=u(await c.delete(`/projects/${e}/sessions/${t}`));return Dl()?.remove(e,t),e_(t),n}async function su(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function iu(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Yn(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Jn(e,t){let n=u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}));return Zh(t),n}async function au(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function gR(e){let t=e.split(`
8
8
  `).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));if(t.length===0)return null;try{return JSON.parse(t.join(`
9
- `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function tu(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function nu(e,t,n,r,s={}){let o=await l.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!o.ok){let d=await o.json().catch(()=>null);throw new x(d?.error||`Reload failed: HTTP ${o.status}`,{status:o.status,code:d?.code,data:d})}let i=o.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,c="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;c+=a.decode(g,{stream:!0});let m=c.indexOf(`
9
+ `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function cu(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function lu(e,t,n,r,o={}){let s=await c.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,o);if(!s.ok){let d=await s.json().catch(()=>null);throw new S(d?.error||`Reload failed: HTTP ${s.status}`,{status:s.status,code:d?.code,data:d})}let i=s.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,l="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;l+=a.decode(g,{stream:!0});let m=l.indexOf(`
10
10
 
11
- `);for(;m!==-1;){let f=c.slice(0,m);c=c.slice(m+2),m=c.indexOf(`
11
+ `);for(;m!==-1;){let f=l.slice(0,m);l=l.slice(m+2),m=l.indexOf(`
12
12
 
13
- `);let _=UA(f);if(_){if(r(_),_.type==="error")throw new x(_.error,{status:_.status,code:_.code,data:{reason:_.reason}});_.type==="done"&&(p=_.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function ru(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function su(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function ou(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Gn(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function iu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function au(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function FA(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function cu(e){return u(await l.get(`/projects/${e}/triggers`))}async function lu(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function uu(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function pu(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function du(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function Uh(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.limit!=null&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function gu(e,t,n){let r={};return n?.payload!==void 0&&(r.payload=n.payload),n?.dryRun!==void 0&&(r.dry_run=n.dryRun),u(await l.post(`/projects/${e}/triggers/${t}/fire`,r))}async function mu(e,t,n){return u(await l.get(`/projects/${e}/triggers/${t}/runs${Uh(n)}`))}async function fu(e,t){return u(await l.get(`/projects/${e}/trigger-runs${Uh(t)}`))}async function yu(e,t,n,r){return u(await l.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function hu(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await l.get(`/projects/${e}/triggers/event-types?${n}`))}async function _u(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var et=new Map;function bu(e,t){return`${e}::${t}`}function Fh(e,t){et.delete(e),et.set(e,t)}function Nh(e,t){let n=bu(e,t),r=et.get(n);return r&&Fh(n,r),r}function xs(e,t,n){let r=bu(e,t);if(!et.has(r)&&et.size>=512){let s=et.keys().next().value;s!==void 0&&et.delete(s)}Fh(r,n)}function Kh(e,t){et.delete(bu(e,t))}function NA(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Wn(){return NA(I().backendUrl||"http://localhost:8008/v1")}function Bh(){let e=I().sandboxId;return e?`${Wn()}/p/${e}/8000`:""}function KA(e,t=8e3){return`${Wn()}/p/${e}/${t}`}function Ie(e,t=8e3){return KA(e,t)}function Pu(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var ws=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function BA(e){return e instanceof Error&&e.name==="SessionStartError"}function qA(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new ws(s,{status:n,code:r,terminal:!0}):null}function qh(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,o=new URLSearchParams;r&&r>0&&o.set("wait_ms",String(Math.floor(r))),s&&o.set("repository_mode",s),typeof n=="object"&&n?.keepStopped&&o.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&o.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=o.size>0?`?${o.toString()}`:"";return l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function tt(e,t,n){let r=await qh(e,t,n);if(!r.success||!r.data){let s=qA(r.error);if(s&&!(s.status===404&&vl(t)))throw s;return null}return Gh(e,t,r.data)}async function Su(e,t,n){let r=await qh(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return Gh(e,t,r.data)}function Gh(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&xs(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Ie(r),sandboxId:r}),n}function GA(e,t){return["session-start",e,t]}async function xu(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function wu(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function ku(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await l.delete(`/projects/${e}/model-defaults?${n}`))}async function WA(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Wh(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function VA(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function ks(e){let t=e.connectors_required?Wh(e.connectors_required):void 0,n=e.connectors_personal?Wh(e.connectors_personal):void 0;if(t&&n&&!VA(t,n))throw new Error("connectors_personal must match connectors_required when both fields are present");let r={...e};return delete r.connectors_personal,(t!==void 0||n!==void 0)&&(r.connectors_required=t??n),r}async function vu(e,t,n){let r=ks(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function HA(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Au(n.block):null}}async function zA(e,t,n){let r=Au(n,!0),s=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Au(s.block):null}}function Au(e,t=!1){let n=ks(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function YA(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Ru(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var vs="Use setBillingPlan().",Vh="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Cu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",monthly_usd:null,status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function JA(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function QA(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,monthlyUsd:t.monthly_usd??null};let n=e??Cu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:JA(r),label:s,sublabel:null,monthlyUsd:null}}function Hh(e){return!!e&&e.can_manage_billing!==!1}function XA(e){return e?.subscription?.can_purchase_credits===!0&&Hh(e)}async function zh(e){let t=await l.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?Cu():t.data}function Yh(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString();return n?`?${n}`:""}async function Tu(e){return zh(`/billing/account-state${Yh(e)}`)}async function Iu(e){return zh(`/billing/account-state/minimal${Yh(e)}`)}async function Eu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await l.get(`/billing/transactions${n?`?${n}`:""}`))}async function Mu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await l.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Ou(){return u(await l.get("/billing/credit-breakdown"))}async function Du(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function ju(){return u(await l.get("/billing/tier-configurations"))}async function ZA(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return jt(e,`/v1/billing/account-state${t}`)}async function Lu(e){throw U("createCheckoutSession",vs)}async function $u(e,t){throw U("confirmCheckoutSession",vs)}async function Uu(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Fu(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Nu(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Ku(e,t,n){throw U("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Bu(e){throw U("cancelScheduledChange",Vh)}async function qu(e,t){throw U("getProrationPreview",Vh)}async function Gu(e){return u(await l.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Wu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function eR(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Vu(e){return u(await l.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function tR(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function Hu(e){return u(await l.post("/billing/plan/preview",{monthly_usd:e.monthlyUsd,account_id:e.accountId}),"Failed to preview the plan change")}async function zu(e){return u(await l.post("/billing/plan",{monthly_usd:e.monthlyUsd,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale,account_id:e.accountId}),"Failed to set billing plan")}async function Yu(e){return u(await l.post("/billing/enterprise-offer/checkout",{success_url:e.successUrl,cancel_url:e.cancelUrl,account_id:e.accountId}),"Failed to start the Enterprise checkout")}async function Ju(e={}){return u(await l.post("/billing/enterprise/contact",{account_id:e.accountId,...e.note?{note:e.note}:{}}),"Failed to reach Kortix sales")}async function nR(e){throw U("createPerSeatCheckout",vs)}async function rR(e){throw U("claimPerSeatBilling",vs)}async function sR(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Qu(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await l.get(`/usage${n?`?${n}`:""}`))}function Zu(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function As(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Rs(e){return e.size>0?`?${e}`:""}async function ep(e={}){let t=new URLSearchParams;return Zu(t,e),e.ownerId&&t.set("owner_id",e.ownerId),As(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/session-costs${Rs(t)}`))}async function Vn(e,t={}){let n=new URLSearchParams;return Zu(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Rs(n)}`))}async function oR(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),As(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/cost-by-project${Rs(t)}`))}async function iR(e={}){let t=new URLSearchParams;return Zu(t,e),e.sessionId&&t.set("session_id",e.sessionId),As(t,e),u(await l.get(`/usage/cost-summary${Rs(t)}`))}function Xu(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let s=t;s.ownerId&&n.set("owner_id",s.ownerId)}As(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${I().backendUrl||""}${r}?${n}`}async function aR(e,t={}){let n=Xu(e==="projects"?"projects":"sessions",t),r=await Le(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),s=r.headers.get("x-kortix-row-cap"),o=s!=null?Number(s):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(o)?o:null}}async function Jh(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function cR(e){return Jh("slack",e)}function lR(e){return Jh("teams",e)}async function Qh(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function uR(e){return Qh("slack",e)}function pR(e){return Qh("teams",e)}async function tp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function np(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var dR={oauth_available:!1,install_url:null};async function rp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?dR:t.data}async function Xh(e,t,n){return u(await l.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function sp(e,t){return Xh("slack",e,t)}function op(e,t){return Xh("teams",e,t)}async function ip(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function ap(e){let t=await l.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function cp(e,t){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function lp(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function up(e){let t=e.connectionId??e.connection_id??null,n=e.connectorSlug??e.connector_slug??e.connectionSlug??e.connection_slug??"kortix_email";return{...e,connectionId:t,connectorSlug:n}}var gR={provider:"agentmail",managed_available:!1};async function pp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?up(r.data):null}async function dp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?gR:t.data}async function gp(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return up(n)}async function mp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function fp(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return up(r)}async function mR(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function fR(e,t,n){return u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function yp(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function hp(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function _p(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function bp(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Pp(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await l.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function Sp(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function xp(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function wp(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function kp(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function vp(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ap(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Rp(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Cp(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Tp(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Ip(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Ep(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Mp(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Op(e,t,n,r,s){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function yR(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function hR(){throw U("getReferralCode")}async function _R(){throw U("refreshReferralCode")}async function bR(e){throw U("validateReferralCode")}async function PR(){throw U("getReferralStats")}async function SR(e={}){throw U("listReferrals")}async function xR(e){throw U("sendReferralEmails")}var Dp="call:";function Lp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Dp)&&e.length>Dp.length?{type:"connector_call",executionId:e.slice(Dp.length)}:{type:"review_item",reviewItemId:e}}function e_(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function wR(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[e_(n.status)]+=1;return t}function kR(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function jp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function $p(e){let t=e.indexOf(".");return t<=0?jp(e):`(${jp(e.slice(0,t))}) ${jp(e.slice(t+1))}`}function vR(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Cs=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},F=e=>typeof e=="string"&&e?e:void 0,Ee=e=>Array.isArray(e)?e:void 0,Zh=e=>typeof e=="number"?e:0,AR=e=>e.split(`
14
- `).map(t=>t.trim()).filter(Boolean);function RR(e,t){let n=Cs(e.advanced),r=F(e.description),s=Ee(e.whatChanged)??(r?AR(r):t.summary?[t.summary]:[]);return{crId:F(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:F(e.impact)??"",verification:Ee(e.verification)??[],previewUrl:F(e.previewUrl)??F(e.preview_url),conflicts:Ee(e.conflicts),requestedChanges:Ee(e.requested_changes)??[],advanced:{headRef:F(n.headRef)??F(e.head_ref)??"",baseRef:F(n.baseRef)??F(e.base_ref)??"",headSha:F(n.headSha)??F(e.head_sha)??F(e.head_commit_sha)??"",baseSha:F(n.baseSha)??F(e.base_sha)??"",additions:Zh(n.additions),deletions:Zh(n.deletions),files:Ee(n.files)??[],mergeMode:F(n.mergeMode)??"merge"}}}function CR(e,t){let n=Ee(e.actions);if(n)return{actions:n.map((c,p)=>({id:F(c.id)??`${t.review_item_id}-${p}`,title:F(c.title)??"Action",connector:F(c.connector)??"",action:F(c.action)??"",consequence:F(c.consequence)??"",risk:F(c.risk)??t.risk,icon:F(c.icon)??"generic",argsPreview:Ee(c.argsPreview)??[],policySource:F(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=F(e.action_path)??"",{connector:s,action:o}=vR(r),i=Cs(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:F(e.execution_id)??t.review_item_id,title:r?$p(r):t.title||"Run action",connector:s,action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:F(e.approval_context),connectorRisk:F(e.risk)??null,policySource:"Requires approval"}]}}function TR(e,t){return{artifactKind:F(e.artifactKind)??"document",artifactLabel:F(e.artifactLabel)??"Output",previewUrl:F(e.previewUrl)??F(e.preview_url),preview:F(e.preview),files:Ee(e.files),note:F(e.note)??t.summary??""}}function IR(e,t){return{question:F(e.question)??t.title??"",context:F(e.context),options:Ee(e.options)??[]}}function ER(e,t){return{note:F(e.note)??t.summary??"",children:Ee(e.children)??[]}}function MR(e){let t=Cs(e.detail);switch(e.kind){case"change":return RR(t,e);case"approval":return CR(t,e);case"output":return TR(t,e);case"decision":return IR(t,e);case"batch":return ER(t,e)}}function OR(e,t){let n=typeof e.number=="number"?e.number:void 0,r=F(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function DR(e,t={}){let n=Cs(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?F(n.action_path):void 0,i=e.kind==="change"?OR(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?$p(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:MR(e)}}var J={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},jR=[J.PROJECT_WRITE,J.PROJECT_TRIGGER_CREATE,J.PROJECT_TRIGGER_FIRE,J.PROJECT_TRIGGER_UPDATE,J.PROJECT_TRIGGER_DELETE];function LR(e){let t=r=>e[r]?.allowed===!0,n=t(J.PROJECT_WRITE);return{canCreate:n&&t(J.PROJECT_TRIGGER_CREATE),canFire:t(J.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(J.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(J.PROJECT_TRIGGER_DELETE)}}var $R=[J.PROJECT_WRITE,J.PROJECT_GITOPS_PUSH,J.PROJECT_GITOPS_MERGE,J.PROJECT_REVIEW_ACT];function t_(e){let t=r=>e[r]?.allowed===!0,n=t(J.PROJECT_WRITE);return{canOpen:n&&t(J.PROJECT_GITOPS_PUSH),canMerge:n&&t(J.PROJECT_GITOPS_MERGE),canClose:n}}function UR(e,t,n){let r=Lp(e.id);if(r.type==="connector_call"){let s=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&s?.canResolve!==!1&&s?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return t_(n).canMerge}return n[J.PROJECT_WRITE]?.allowed===!0&&n[J.PROJECT_REVIEW_ACT]?.allowed===!0}function $(e){return l.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function Up(e){return A(await $(`/accounts/${e}/iam/groups`)).groups}async function Fp(e,t){return A(await $(`/accounts/${e}/iam/groups/${t}`))}async function Np(e,t){return A(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Kp(e,t,n){return A(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Bp(e,t){return A(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function qp(e,t){return A(await $(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Gp(e,t,n){return A(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function FR(e,t){return A(await $(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Wp(e,t,n){return A(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function NR(e,t){return A(await $(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function KR(e,t){let n=A(await $(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function nt(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function BR(e,t={}){let n=nt({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await $(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function qR(e,t={}){let n=nt({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await $(`/accounts/${e}/iam/policies${n}`)).policies}async function GR(e,t){return A(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function WR(e,t,n){return A(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function VR(e,t){return A(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function HR(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function zR(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Vp(e){return A(await $(`/accounts/${e}/iam/roles`)).roles}async function Hp(e){return A(await $(`/accounts/${e}/iam/agent-identities`)).agents}async function zp(e){return A(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function Yp(e,t){return A(await $(`/accounts/${e}/iam/roles/${t}/permissions`))}async function YR(e){return A(await $(`/accounts/${e}/iam/actions`)).actions}async function Jp(e,t){return A(await $(`/accounts/${e}/iam/roles/${t}/usage`))}async function Qp(e,t){return A(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Xp(e,t,n){return A(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Zp(e,t,n){return A(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function ed(e,t){return A(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function JR(e,t,n){return A(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function QR(e){return A(await $(`/accounts/${e}/iam/scim/tokens`)).tokens}async function XR(e,t){return A(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function ZR(e,t){return A(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function eC(e){return A(await $(`/accounts/${e}/iam/mfa-required`))}async function tC(e){return A(await $(`/accounts/${e}/iam/mfa-required/preview`))}async function nC(e,t){return A(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function rC(e){return A(await $(`/accounts/${e}/iam/session-oversight`))}async function sC(e,t){return A(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function oC(e){return A(await $(`/accounts/${e}/iam/sso/provider`)).provider}async function iC(e,t){return A(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function aC(e,t){return A(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function cC(e){return A(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function lC(e){return A(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function uC(e){return A(await $(`/accounts/${e}/iam/sso/mappings`)).mappings}async function pC(e,t){return A(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function dC(e,t){return A(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function gC(e){return A(await $(`/accounts/${e}/iam/session-policy`))}async function mC(e,t){return A(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function fC(e){return A(await $(`/accounts/${e}/iam/sessions`)).sessions}async function yC(e,t){return A(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function hC(e){return A(await $(`/accounts/${e}/iam/pat-policy`))}async function _C(e,t){return A(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function bC(e){return A(await $(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function PC(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function SC(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function xC(e,t){return A(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function wC(e){return A(await $(`/accounts/${e}/audit/webhooks`)).webhooks}async function kC(e,t){return A(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function vC(e,t,n){return A(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function AC(e,t){return A(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function RC(e,t={}){let n=nt({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return A(await $(`/accounts/${e}/audit${n}`))}async function td(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),A(await $(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function nd(e,t,n){return n.length===0?[]:A(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function CC(e){return A(await $(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function TC(e,t){return A(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function rd(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function sd(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function od(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function id(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function ad(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function cd(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function IC(e){return nt({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function ld(e,t){return u(await $(`/accounts/${e}/iam/assignments${IC(t)}`)).assignments}async function ud(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await l.post(`/accounts/${e}/iam/assignments`,n))}async function pd(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function dd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await $(`/accounts/${e}/iam/permissions${n}`)).permissions}async function EC(){let e=await l.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function MC(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function OC(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function DC(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function jC(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function LC(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function $C(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function UC(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function FC(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function NC(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function KC(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function BC(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var n_="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function qC(e){throw U("getGoogleAuthUrl",n_)}async function GC(e,t){throw U("convertPresentationToGoogleSlides",n_)}async function gd(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind),t?.sessionId&&n.set("session_id",t.sessionId),t?.limit!=null&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function md(e){return u(await l.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function fd(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function yd(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function hd(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function _d(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}async function bd(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Pd(e){return u(await l.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Sd(e,t){let n=await l.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var Ts=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function r_(e,t=""){return`${Wn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function s_(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new Ts(s,t.status)}return r}async function WC(e){return s_(r_(e))}async function VC(e){return s_(r_(e,"/messages"))}async function xd(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function wd(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Is(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Es(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var HC=4;async function o_(e,t){let n=new Array(e.length),r=0,s=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(HC,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?o.done.push(i):o.failed.push({reminder:i,error:c.error})}),o}function kd(e,t,n){return o_(t,r=>Is(e,r.sessionId,r.reminderId,n))}function vd(e,t){return o_(t,n=>Es(e,n.sessionId,n.reminderId))}async function Ad(e){return u(await l.get(`/projects/${e}/reminders`))}async function Rd(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function Cd(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await l.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Td(e,t,n){let r=new URLSearchParams;t&&r.set("account_id",t),n?.deleteRevoked&&r.set("delete_revoked","true");let s=r.size>0?`?${r.toString()}`:"";return u(await l.delete(`/accounts/tokens/${encodeURIComponent(e)}${s}`))}async function Id(){return u(await l.get("/oauth/grants")).grants}async function Ed(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function zC(){return u(await l.get("/accounts/me/devices")).devices}async function YC(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Md(e){return u(await l.get(`/projects/${e}/cli-token`))}async function Od(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function Dd(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function Bt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function jd(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function Ld(e,t){let n=Bt(jd(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function $d(e,t){let n=Bt(jd({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Ud(e,t){let n=Bt(jd(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Fd(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Nd(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Kd(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Bd(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function qd(e,t){return u(await l.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function Gd(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function JC(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function Wd(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function Vd(){return u(await l.get("/marketplace/marketplaces"))}async function Hd(){return u(await l.get("/marketplace/marketplaces/featured"))}async function zd(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Yd(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Jd(){return u(await l.get("/marketplace/sources"))}async function Qd(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Xd(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function QC(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function XC(e){throw U("getTemplate")}async function ZC(e,t){throw U("installTemplate")}async function Zd(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function eg(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Ms(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function tg(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function ng(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function rg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function sg(e,t){let n=await Ms(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await l.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),s=new TextEncoder().encode(JSON.stringify(r)),o="";for(let i of s)o+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(o)}`}}async function og(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function ig(e,t){return u(await l.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function ag(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function cg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Os(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Ds(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function eT(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function tT(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest("SHA-256",t.buffer);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}async function lg(e,t,n={}){let r=await eT(t),s=n.mediaType??"application/gzip",o=await Os(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),Ds(e,o.artifact.artifact_id,{sha256:await tT(r),size_bytes:r.byteLength})}async function ug(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function pg(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function dg(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function gg(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function mg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function fg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function yg(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function hg(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var be=(e,t)=>`/projects/${e}/apps/${t}`;async function _g(e,t){return u(await l.get(`${be(e,t)}/machines`),"Failed to list machines").machines}async function bg(e,t,n,r){return u(await l.post(`${be(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Pg=(e,t,n)=>bg(e,t,n,"start"),Sg=(e,t,n)=>bg(e,t,n,"stop"),xg=(e,t,n)=>bg(e,t,n,"restart");async function wg(e,t,n){return u(await l.delete(`${be(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function kg(e,t,n,r={}){return u(await l.put(`${be(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function vg(e,t,n){return u(await l.post(`${be(e,t)}/exec`,n),"Failed to run the command")}async function Ag(e,t){return u(await l.get(`${be(e,t)}/volumes`),"Failed to list volumes").volumes}async function Rg(e,t,n){return u(await l.post(`${be(e,t)}/volumes`,n),"Failed to create the volume")}async function Cg(e,t,n,r){return u(await l.patch(`${be(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function Tg(e,t,n,r){u(await l.delete(`${be(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Ig(e,t,n){return u(await l.get(`${be(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Eg(e,t,n){return u(await l.post(`${be(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Mg(e,t,n,r){return u(await l.post(`${be(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function Og(e,t,n,r){return u(await l.post(`${be(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function ue(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var de=e=>`/drives/${encodeURIComponent(e)}`;async function nT(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new x("Files not found",{status:404});return t[0]}async function rT(e,t){return u(await l.get(`${de(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function sT(e,t){return u(await l.put(`${de(e)}/access`,t),"Failed to share folder")}async function oT(e,t){let n=u(await l.delete(`${de(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function iT(e){return u(await l.get(`${de(e)}/principals`),"Failed to load people")}async function aT(e){return u(await l.get(`${de(e)}/conflicts`),"Failed to load conflicts").conflicts}async function cT(e,t){u(await l.post(`${de(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function lT(e,t="/"){return(await i_(e,t)).entries}async function i_(e,t="/"){return u(await l.get(`${de(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function Dg(e,t,n){let r=ue(I().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${de(e)}/files/content?${new URLSearchParams(s)}`}async function uT(e,t,n){let r=await L(Dg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function pT(e,t,n){let r=await L(Dg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function dT(e,t,n,r){return u(await l.putRaw(`${de(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function gT(e,t){return u(await l.post(`${de(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function mT(e,t,n){return u(await l.post(`${de(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function fT(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${de(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function yT(e){return u(await l.get(`${de(e)}/versions`),"Failed to load versions").versions}async function hT(e,t){u(await l.post(`${de(e)}/restore`,{versionId:t}),"Failed to restore version")}var _T=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function bT(e,t){return(await a_(e,t)).drives}async function a_(e,t){return u(await l.get(_T(e,t)),"Failed to load session files")}async function jg(e){return u(await l.post("/notifications/device-token",e))}async function Lg(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var PT=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered"];async function $g(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await l.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function Ug(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await l.post("/notifications/read",t))}var ST={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1},capture_device_down:{push:!0,email:!0},capture_device_recovered:{push:!0,email:!1}};async function Fg(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function Ng(e){return u(await l.put("/notifications/preferences",e))}async function Kg(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function Bg(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await l.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function qg(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function Hn(e){return u(await l.get(`/projects/${e}/model-access`))}async function zn(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function xT(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:o,previewIsLinkOnly:i}=e;return t||n?!1:s?o&&!i:r==="error"}function Gg(e){return typeof e=="string"&&e.trim().length>0}function c_(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Gg(t)||Gg(n)||Gg(r)}function wT(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function Yn(e){if(!e)return!0;let t=wT(e.items);return t?!t.some(c_):!c_(e)}var ke="kortix.transcript.v1",l_=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function Wg(e){return typeof e=="string"&&l_.includes(e)}var kT=["once","always","reject"],vT=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var d_="kortix-v1-import",AT={harness:d_,harness_version:ke,adapter_version:"1"},Vg={schema:ce,v:1},RT={opencode:"[Tool execution was interrupted]",pi:"No result provided"},CT="[Old tool result content cleared]",TT="The following tool was executed by the user",IT=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),ET=e=>IT.get(e)??(e.includes("_")?"mcp":"other"),MT=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),OT=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),K=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q=e=>typeof e=="string"?e:void 0,Be=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Us=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,g_=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),qt=e=>Be(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Gt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function Hg(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>Hg(r,t[s]));if(!K(e)||!K(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>Hg(e[r],Us(t,r)))}function Ls(e,t){if(Hg(e,t))return;if(e===void 0)return{del:!0};if(!K(e)||!K(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=Ls(Us(e,r),Us(t,r));s&&g_(n,r,s)}return{sub:n}}function $s(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=K(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=$s(Us(n,r),s);o===void 0?delete n[r]:g_(n,r,o)}return n}var Jn=e=>Object.values(e??{}).find(t=>t.version===ke),Fs=(e,t)=>({[e]:{version:ke,...t}}),m_=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},u_=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),DT=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),jT=e=>{if(K(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==ke&&K(n.data?.details));return t?t.data.details:{}};function LT(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Gt(e.started_at)??t.created,i=Gt(e.ended_at)??o,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:o}};if(e.status==="error")return{status:"error",...s,error:u_(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let c=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...m_(d,t)}]:[]),p=Gt(r?.cleared_at);return{status:"completed",...s,output:u_(r?.content),title:e.title??"",metadata:{...jT(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...c.length&&{attachments:c}}}function f_(e,t){let n=DT(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...m_(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:LT(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function $T(e){return Wg(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function y_(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:OT.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:Gt(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...s&&{finish:s},...e.error&&{error:$T(e.error)},...n}}function h_(e,t){return e.role==="assistant"?y_(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function __(e,t,n){let r=`${e.message_id}-summary`;return{info:y_({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function UT(e,t,n){let r=n||e.producer.harness===d_;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=Jn(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Gt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=f_(d,i);return g===void 0?[]:[$s(g,Jn(d.ext)?.data)]}),c=[{runtime_session_id:o,info:$s(h_(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=$s(__(e,p,i),s?.summary);c.push({runtime_session_id:o,info:d.info,parts:d.parts})}return c}var zg=e=>Be(K(e.info)&&K(e.info.time)?e.info.time.created:void 0)??-1/0,js=e=>String(K(e.info)?e.info.id:""),b_=(e,t)=>zg(e)-zg(t)||(js(e)<js(t)?-1:js(e)>js(t)?1:0),p_=e=>{let t=Jn(e.ext);return t?t.native_id??null:e.thread_id};function Ns(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>UT(a,p_(i),Jn(i.ext)!==void 0))),s=Jn(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?p_(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(b_)}}function FT(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:K(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=Q(t.p),r=Q(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...Q(t.v)!==void 0&&{variant:t.v}}}function NT(e){if(!K(e.tokens))return null;let t=e.tokens,n=K(t.cache)?t.cache:{};return{input:Be(t.input)??0,output:Be(t.output)??0,cache_read:Be(n.read)??0,cache_write:Be(n.write)??0,...Be(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Be(e.cost)!==void 0&&{cost:e.cost}}}var KT=e=>({code:Q(e.code)||Q(e.name)||"UnknownError",message:Q(K(e.data)?e.data.message:void 0)??""});function P_(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:Q(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...Q(e.url)!==void 0&&{url:e.url}}}function BT(e,t,n,r){let s=e.state,o=K(s.time)?s.time:{};K(s.input)||r.tool_input++;let i=K(s.metadata)&&Be(s.metadata.exit)!==void 0?{exit_code:s.metadata.exit}:{},a,c,p=s.input??null;if(s.status==="completed"){let m=(Array.isArray(s.attachments)?s.attachments:[]).filter(K).map(_=>{let{bytes:y,...v}=P_(_,n,r);return{type:"attachment",...v}}),f=qt(o.compacted);a="complete",c={content:[...Q(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:CT}],cleared_at:f}}}else if(s.status==="error"){let m=Q(s.error);a="error",c={content:m!==void 0?[{type:"text",text:m}]:[],is_error:!0,...m!==void 0&&{error:{message:m}},...i}}else if(n.live)a=s.status==="pending"?"pending":"running",a==="pending"&&Q(s.raw)&&!(K(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=RT[n.h];a="error",c={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=qt(o.start),g=qt(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:ET(e.tool),input:p,status:a,...c&&{result:c},...Q(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function qT(e,t,n,r,s,o){let i=(a,c=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:c,...c&&{fallback_text:TT}});if(!K(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...P_(e,s,o),...Q(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&K(e.state)?BT(e,t,s,o):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:Q(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(Q(e.type)||"unknown")}}function GT(e){let t=e.map((s,o)=>K(s)&&typeof s.id=="string"&&s.id?s.id:`#${o}`),n=new Set(t),r=new Set;return t.map(s=>{if(!r.has(s))return r.add(s),s;let o=2;for(;n.has(`${s}#${o}`);)o++;return n.add(`${s}#${o}`),`${s}#${o}`})}function WT(e,t,n,r,s,o){let i=K(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],c=i.role==="user"?a.find(w=>K(w)&&w.type==="compaction"):void 0,p=t&&K(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=c?p:d==="assistant"?i:void 0,m=g&&K(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",_=g&&K(g.time)?qt(g.time.completed):null,y=o.live?"streaming":"interrupted",v=g?m?f?"aborted":"error":_?"complete":y:c?y:"complete",R=qt(K(i.time)?i.time.created:void 0)??"",T=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(w=>K(w)&&w.type==="text"&&typeof w.text=="string"?[w.text]:[]).join(""):null,b={tool_input:0,cut_point:0,attachment:0},M=GT(a),h=a.map((w,D)=>qT(w,M[D],c,T,o,b)),S=h.some(w=>w.type==="text"||w.type==="attachment"||w.type==="tool_call"||w.type==="harness"&&w.model_visible),P=!s&&d!=="system"&&(c?v==="complete":!m||f&&S),k=o.live&&P&&v!=="streaming"&&h.some(w=>w.type==="tool_call"&&(w.status==="pending"||w.status==="running"))?"streaming":v,C=s?"superseded":P||!m?void 0:f?"aborted":"failed_attempt";return c&&K(c)&&Q(c.tail_start_id)===void 0&&b.cut_point++,{m:{...Vg,message_id:Q(i.id)??"",thread_id:n,seq:r,role:d,kind:c?"compaction":"turn",status:k,in_context:P,...C&&{hidden_reason:C},agent:Q(i.agent)??null,...d==="assistant"&&{reply_to:Q(i.parentID)??null},model:FT(i),usage:g?NT(g):null,finish:!g||c?null:f?"aborted":m?"error":MT.get(i.finish)??null,error:m?KT(m):null,created_at:R,completed_at:g||c?_:R||null,producer:AT,blocks:h},lost:b}}function VT(e,t,n,r,s){let o={};t.runtime_session_id!==r&&(o.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:Gt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=Ls(t.parts[d],f_(p,i));g&&(p.ext=Fs(s,{data:g}))}):o.parts=t.parts;let a=Ls(t.info,h_(e,i));a&&(o.info=a);let c=e.blocks.find(p=>p.type==="compaction");if(n&&c){let p=Ls({info:n.info,parts:n.parts},__(e,c,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Fs(s,{data:o}))}function HT(e,t,n){if(t){for(let r of[!0,!1])for(let s of e)if(!(s.runtime_session_id===t||!Array.isArray(s.parts))){for(let o of s.parts)if(!(!K(o)||o.type!=="tool"||!K(o.state))&&(r?K(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function Ks(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(b_),s=new Map;for(let b of r){let M=s.get(b.runtime_session_id);M?M.push(b):s.set(b.runtime_session_id,[b])}let o=e.root_id,i=s.has(o),a=new Map,c=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of s.keys()){let M=i&&b===o?void 0:HT(r,b,c);M&&p.set(b,M)}let d=[...r].reverse().find(b=>b.runtime_session_id===null||!p.has(b.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=b=>b!==null&&p.has(b)?b:m,_=qt(r.map(zg).find(Number.isFinite))??"",y=[];for(let[b,M]of s){if(b!==g&&(b===null||!p.has(b)))continue;let h=b===g,S=h?r.filter(N=>N.runtime_session_id!==g&&f(N.runtime_session_id)===m):[],P=[...S,...M],k=new Set(S),C=new Map,j=new Set;for(let N of P){let z=K(N.info)?N.info:{};if(z.role!=="user"||!Array.isArray(N.parts)||!N.parts.some(B=>K(B)&&B.type==="compaction"))continue;let G=P.find(B=>!j.has(B)&&B.runtime_session_id===N.runtime_session_id&&K(B.info)&&B.info.role==="assistant"&&B.info.summary===!0&&B.info.parentID===z.id);G&&(C.set(N,G),j.add(G))}let w=[];for(let N of P){if(j.has(N))continue;let z=C.get(N),{m:G,lost:B}=WT(N,z,h?m:b,w.length+1,k.has(N),n);if(VT(G,N,z,b,n.h),G.in_context)for(let je of["tool_input","cut_point","attachment"])n.counts[je]+=B[je];w.push(G)}let D=b===null?void 0:p.get(b),xe=w.find(N=>N.role==="user"&&N.kind==="turn");y.push({...Vg,thread_id:h?m:b,parent_thread_id:D?f(D.row.runtime_session_id):null,spawned_by:D&&typeof D.part.callID=="string"?{message_id:Q(D.row.info?.id)??"",call_id:D.part.callID}:null,agent:xe?.agent??null,title:null,created_at:w[0]?.created_at||_,messages:w,ext:Fs(n.h,b===null?{}:{native_id:b})})}y.sort((b,M)=>b.parent_thread_id===null?-1:M.parent_thread_id===null?1:T(b)-T(M));let v=y[0]?.messages.filter(b=>b.role==="user"&&b.kind==="turn").at(-1),R=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...Vg,session_id:e.session_id,title:null,created_at:_,restore_grade:R?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:v?.agent??null,model:v?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:y,...g!==o&&{ext:Fs(n.h,{data:{root_id:o}})}};function T(b){return r.findIndex(M=>M.runtime_session_id===b.thread_id)}}var Yg={schema:ce,v:1},zT=Object.freeze({}),S_=new WeakMap;function Qn(e){let t=S_.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},o=Ks({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return S_.set(e,{state:e.state,block:o}),o}var Jg=new WeakMap;function Qg(e){if(Jg.has(e))return Jg.get(e);let t={...Yg,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:ke}},messages:[{...Yg,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=Ns({...Yg,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return Jg.set(e,r),r}function oe(e){return Qg(e)}var ge=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",qe=e=>ge(e)?oe(e):e;function w_(e){let t=oe(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:zT}var k_=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function v_(e){return e.status==="complete"?"completed":e.status}var x_=new WeakMap;function A_(e){if(e.status!=="complete")return"";let t=x_.get(e);return t===void 0&&x_.set(e,t=k_(e)),t}function R_(e){return e.status==="error"?e.result?.error?.message||k_(e):void 0}function me(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function YT(e){return me(e)==="bash"}function Xg(e){let t=me(e);return t==="question"||t==="ask"}function JT(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var C_=new Set(["show","show_user"]);function Zg(e){return C_.has(me(e))}function QT(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function em(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Bs(e))}function Bs(e){let t=ge(e)?oe(e):e,n=me(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:Yn(t.state?.input)}var T_=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function tm(e){return T_.has(me(e))}var XT=50*1024*1024,nm="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",ZT=new RegExp(`^kortix-attachment://(${nm})/(${nm})/(${nm})$`);function sm(e){if(typeof e!="string")return null;let t=ZT.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function eI(e){return sm(e)!==null}var rm=new WeakMap;async function om(e,t,n,r={}){if(n.size>XT)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:rm.get(n)?.get(s);if(o?.promise)return o.promise;let i=o??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=rm.get(n)??new Map;c.set(s,i),rm.set(n,c)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=l.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(c=>{throw i.promise=void 0,c}),i.promise}async function im(e,t){let n=sm(e);if(!n)throw new Error("Invalid attachment reference");let r=I().backendUrl.replace(/\/$/,""),s=await L(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new x("Could not load attachment",{status:s.status});return s.blob()}var tI=new Set(["show","show_user"]);function nI(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var Ge=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Xn=e=>typeof e=="string"&&e.length>0?e:null,I_=e=>typeof e=="string"?Xn(e.split("/").pop()):null;function qs(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function rI(e){if(Array.isArray(e))return e;if(typeof e!="string"||!e.trim())return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function sI(e){let t=e.blocks.filter(Ge).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&Ge(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function oI(e,t){for(let n of nI(e))t(qs(n,"attachment"),qs(n,"filename")??I_(qs(n,"path")),qs(n,"mime"))}function iI(e,t){for(let n of[e,...rI(e.items)])Ge(n)&&t(n.attachment,I_(n.path),null)}function aI(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=Ge(r)&&Array.isArray(r.blocks)?sI(r):r;if(!Ge(s)||!Ge(s.info)||!Array.isArray(s.parts))continue;let o=Xn(s.info.id);if(!o)continue;let i=Xn(s.info.role)??"unknown",a=(c,p,d)=>{let g=sm(c);!g||n.has(c)||(n.add(c),t.push({url:c,attachment_id:g.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let c of s.parts)Ge(c)&&(c.type==="file"?a(c.url,Xn(c.filename),Xn(c.mime)):c.type==="text"&&typeof c.text=="string"?oI(c.text,a):c.type==="tool"&&typeof c.tool=="string"&&tI.has(me(c.tool))&&Ge(c.state)&&Ge(c.state.input)&&iI(c.state.input,a))}return t}function rt(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function cI(e,t){if(e==null)return t;let n=e.trim().toLowerCase();return["1","true","yes","y","on"].includes(n)?!0:["0","false","no","n","off"].includes(n)?!1:t}function lI(e){if(e==null)return;let t=e.trim().toLowerCase();if(["1","true","yes","y","on"].includes(t))return!0;if(["0","false","no","n","off"].includes(t))return!1}function am(e,t,n){return e!==void 0?e:cI(rt(t),n)}var cm={get disableMobileAdvertising(){return am(I().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return am(I().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return am(I().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var uI=new Set(["project-manager"]);function Gs(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:cm.enableProjects||!uI.has(e.name)}function pI(e){let t=e.agents.filter(Gs),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function E_(){return{projects:{list:Pt,listForAccount:Yi,get:St,detail:vn,create:Zi,createRepo:ea,provision:ta,update:Cn,archive:Tn,llmCatalog:An,modelPicker:Rn,modelAccess:Hn,setModelAccess:zn,sandboxHealth:En,sandboxTemplates:Wc,sessions:kt,createSession:vt},github:{linkRepository:aa,replaceProjectRepository:ca,getInstallation:la,listInstallations:ua,listLinkableInstallations:pa,listRepositories:da,listRepositoryBranches:ga,linkInstallation:fa,saveInstallation:ma,deleteInstallation:ha,storeUserToken:ya},gitBackend:{get:_a,repositories:ba},connectStatus:Uc,marketplace:{items:o=>Wd(o),item:o=>zd(o),itemFile:(o,i)=>Yd(o,i),marketplaces:()=>Vd(),featured:()=>Hd(),sources:{list:()=>Jd(),add:o=>Qd(o),remove:o=>Xd(o)}}}}function M_(){return{billing:{accountState:Tu,accountStateMinimal:Iu,transactions:Eu,transactionsSummary:Mu,creditBreakdown:Ou,usageHistory:Du,usageRollup:Qu,sessionCosts:{list:ep,get:Vn},tierConfigurations:ju,setPlan:zu,previewPlan:Hu,acceptEnterpriseOffer:Yu,contactSales:Ju,checkout:{createSession:n=>Lu(n),confirmSession:(n,r)=>$u(n,r)},subscription:{createPortalSession:(n,r)=>Uu(n,r),cancel:(n,r)=>Fu(n,r),reactivate:n=>Nu(n),scheduleDowngrade:(n,r,s)=>Ku(n,r,s),cancelScheduledChange:n=>Bu(n),prorationPreview:(n,r)=>qu(n,r)},credits:{purchase:n=>Gu(n),autoTopupSettings:n=>Wu(n),configureAutoTopup:n=>Vu(n)}},sandboxShares:{list:bd,create:Pd,revoke:Sd}}}var We={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function st(){let e=rt("BACKEND_URL")||I().backendUrl;return e||"http://localhost:8008/v1"}function At(e){let t=ue(e);return t.endsWith("/v1")?t:`${t}/v1`}function Zn(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=Zn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return Zn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function dI(e){return e==="running"||e==="active"?"active":e==="queued"||e==="branching"||e==="provisioning"?"provisioning":e==="failed"||e==="error"?"error":e==="stopped"||e==="completed"||e==="archived"?"stopped":e||"unknown"}function Ws(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${st()}/p/${n.external_id}/${We.KORTIX_MASTER}`:""),status:dI(n?.status||t.status),metadata:{...t.metadata??{},project_id:e.project_id,session_id:t.session_id,project_name:e.name,runtime_status:n?.status,error:t.error},created_at:n?.created_at||t.created_at,updated_at:n?.updated_at||t.updated_at}}async function lm(){let e=await Pt(),t=[];for(let n of e){let r=await kt(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Ws(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function um(e){let t=await l.get(`/sessions/${encodeURIComponent(e)}`,{showErrors:!1});if(t.success&&t.data)return t.data;if(t.error?.status===400||t.error?.status===404)return null;throw t.error??new Error("Session request failed")}async function Vs(e){let t=await um(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await er(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function er(e){let t=await lm();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}var Wt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function ie(e,t,n){let r=n?.fetch??I().fetch??((p,d)=>fetch(p,d)),s=ue(n?.backendUrl??I().backendUrl??"");if(!s)throw new Wt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let o={accept:"application/json"};t.body!==void 0&&(o["content-type"]="application/json"),t.bearer&&(o.authorization=`Bearer ${t.bearer}`);let i=await r(`${At(s)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new Wt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return c}function Hs(e,t){return ie("/auth/signup",{body:e},t)}function zs(e,t){return ie("/auth/sign-in/password",{body:e},t)}function Ys(e,t){return ie("/auth/sign-in/magic-link",{body:e},t)}function Js(e,t){return ie("/auth/verify-otp",{body:e},t)}function Qs(e,t){return ie("/auth/sign-in/oauth",{body:e},t)}function Xs(e,t){return ie("/auth/oauth/exchange",{body:e},t)}function Vt(e,t){return ie("/auth/refresh",{body:e},t)}function Zs(e,t){return ie("/auth/password/reset",{body:e},t)}function eo(e,t,n){return ie("/auth/password/update",{body:e,bearer:t},n)}function to(e,t){return ie("/auth/user",{bearer:e},t)}function no(e,t,n){return ie("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function ro(e,t){return ie("/auth/sign-in/sso",{body:e},t)}var so={enroll:(e,t,n)=>ie("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function oo(e,t={},n){return ie("/auth/sign-out",{body:t,bearer:e},n)}function io(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,c=0,p=new Set,d=y=>(y.expires_at??0)*1e3,g=y=>d(y)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let y of[...p])try{y(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let y=c,v=(async()=>{let R=await e.storage.get();if(y===c&&R)try{let T=JSON.parse(R);T.session?.access_token&&T.session?.refresh_token&&(r=T.session,s=T.user??null)}catch{r=null}return o=!0,r})();i=v,v.then(()=>{i===v&&(i=null)},()=>{i===v&&(i=null)})}return i}async function _(){if(await f(),!r)return null;if(!a){let y=r.refresh_token,v=c,R=Vt({refresh_token:y},e.request).then(async T=>(v!==c||(r=T.session,T.user&&(s=T.user),await m()),r)).catch(async T=>{if(v!==c)return r;let b=T&&typeof T=="object"&&"status"in T?T.status:0;if(b>=400&&b<500)return r=null,s=null,await m(),null;throw T}).finally(()=>{a===R&&(a=null)});a=R}return a}return{subscribe(y){return p.add(y),()=>{p.delete(y)}},current:()=>r,user:()=>s,load:f,async set(y,v){await f(),c+=1,a=null,r=y,v!==void 0&&(s=v),y||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await _().catch(()=>r))?.access_token??null:r.access_token:null},refresh:_,async clear(){c+=1,a=null,r=null,s=null,o=!0,await m()}}}function O_(){return{list:Ri,get:Ti,create:Ci,secretResources:{list:Qa,create:Xa,rotate:Za,retry:ec,remove:tc,grant:nc,revoke:rc,setAccess:sc},updateName:Ii,branding:{get:Ei,update:Mi,uploadAsset:Oi,removeAsset:Di,reset:ji},leave:Hi,members:Li,invite:$i,removeMember:Wi,updateMemberRole:Vi,invites:Ui,cancelInvite:Fi,resendInvite:Ni,tokens:{list:Rd,create:Cd,revoke:Td},connectedApps:{list:Id,revoke:Ed},audit:{log:Ld,export:Ud,webhooks:{list:Fd,create:Nd,update:Kd,remove:Bd}}}}function D_(){return{assignments:{list:ld,create:ud,revoke:pd},permissions:{list:dd,forRole:Yp},roles:{list:Vp,create:Qp,update:Xp,setPermissions:Zp,remove:ed,usage:Jp},groups:{list:Up,get:Fp,create:Np,update:Kp,remove:Bp,members:{list:qp,add:Gp,remove:Wp}},agentIdentities:Hp,oauthClients:{list:rd,get:sd,create:od,update:id,rotateSecret:ad,remove:cd},can:td,canBatch:nd}}function j_(){let e={signUp:Hs,signInWithPassword:zs,sendMagicLink:Ys,verifyOtp:Js,signInWithProvider:Qs,exchangeCode:Xs,refresh:Vt,resetPassword:Zs,updatePassword:eo,updateUserMetadata:no,signInWithSso:ro,mfa:so,user:to,signOut:oo,session:io},t=O_(),n=D_();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Ki,describe:Bi,accept:ns,acceptAndLand:qi,decline:Gi}}}var tr=new Map,pm=new Map;function dm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function L_(e){return tr.get(dm(e))??null}function $_(){return[...tr.values()].filter(e=>typeof e=="string")}function U_(e){return tr.has(dm(e))}async function ot(e){let t=dm(e),n=tr.get(t);if(n!==void 0)return n;let r=pm.get(t);if(r)return r;let s=(async()=>{try{let o=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let i=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return tr.set(t,i),i}catch{return null}finally{pm.delete(t)}})();return pm.set(t,s),s}function F_(e){let{apiBaseUrl:t}=e;return U_(t)||ot(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:L_(t)}}function N_(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new x(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let s=I().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),F_({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function K_(e,t){let n=null;async function r(){n||(n=Un(e,t,{showErrors:!1}).then(s=>{let o=Gn(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,c=s.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Ht={url:null,sandboxId:null,dbSandboxId:null,version:0},mI=new Set;function ao(e,t=null,n=null){if(!(Ht.url===e&&Ht.sandboxId===t&&Ht.dbSandboxId===n)){Ht={url:e,sandboxId:t,dbSandboxId:n,version:Ht.version+1};for(let r of mI)r()}}function B_(){return Ht.url}var nr=new Map;function q_(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Rt=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function G_(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await tt(e,t,Math.min(3e4,o()));for(;Date.now()<s&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,o()))),i=await tt(e,t,Math.min(3e4,o()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new x(q_(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new x("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ie(c);return ao(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function W_(e,t,n){let r=null;function s(){if(r)return r;let p=Nh(e,t);return p&&(r=p),r}let o=G_(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=ot(I().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Pu(p.session):null,_=f?.sandbox?.external_id,y=f?.runtime_session_id;if(_&&y){let b=Ie(_);return ao(b,_),r={runtimeSessionId:y,opencodeSessionId:y,runtimeUrl:b,sandboxId:_},xs(e,t,r),await m,r}let v=`${e}
15
- ${t}`,R=nr.get(v);if(R)return r=await R,await m,r;let T=o(g);nr.set(v,T);try{return r=await T,await m,r}finally{nr.get(v)===T&&nr.delete(v)}}function a(p){let d=s();if(!d)throw new Rt(p);return d}function c(){r=null,Kh(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:c}}var q=["directory","workspace"],V_=["messageID","model","agent","noReply","tools","format","system","variant","parts"],E=(e,t,n=q,r=[],s)=>({method:e,path:t,query:n,body:r,bodyParam:s}),fI={"session.list":E("GET","/session",[...q,"scope","path","roots","start","search","limit"]),"session.get":E("GET","/session/{sessionID}"),"session.create":E("POST","/session",q,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":E("DELETE","/session/{sessionID}"),"session.update":E("PATCH","/session/{sessionID}",q,["title","metadata","permission","time"]),"session.status":E("GET","/session/status"),"session.messages":E("GET","/session/{sessionID}/message",[...q,"limit","before"]),"session.prompt":E("POST","/session/{sessionID}/message",q,V_),"session.promptAsync":E("POST","/session/{sessionID}/prompt_async",q,V_),"session.abort":E("POST","/session/{sessionID}/abort"),"session.revert":E("POST","/session/{sessionID}/revert",q,["messageID","partID"]),"session.unrevert":E("POST","/session/{sessionID}/unrevert"),"session.summarize":E("POST","/session/{sessionID}/summarize",q,["providerID","modelID","auto"]),"session.command":E("POST","/session/{sessionID}/command",q,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":E("POST","/session/{sessionID}/share"),"session.unshare":E("DELETE","/session/{sessionID}/share"),"session.fork":E("POST","/session/{sessionID}/fork",q,["messageID"]),"session.diff":E("GET","/session/{sessionID}/diff",[...q,"messageID"]),"session.todo":E("GET","/session/{sessionID}/todo"),"permission.list":E("GET","/permission"),"permission.reply":E("POST","/permission/{requestID}/reply",q,["reply","message"]),"question.list":E("GET","/question"),"question.reply":E("POST","/question/{requestID}/reply",q,["answers"]),"question.reject":E("POST","/question/{requestID}/reject"),"part.update":E("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",q,[],"part"),"part.delete":E("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":E("GET","/file",[...q,"path"]),"file.read":E("GET","/file/content",[...q,"path"]),"find.files":E("GET","/find/file",[...q,"query","dirs","type","limit"]),"vcs.diff":E("GET","/vcs/diff",[...q,"mode","context"]),"global.health":E("GET","/global/health",[]),"global.dispose":E("POST","/global/dispose",[]),"global.config.get":E("GET","/global/config",[]),"global.config.update":E("PATCH","/global/config",[],[],"config"),"provider.list":E("GET","/provider"),"provider.auth":E("GET","/provider/auth"),"provider.oauth.authorize":E("POST","/provider/{providerID}/oauth/authorize",q,["method","inputs"]),"provider.oauth.callback":E("POST","/provider/{providerID}/oauth/callback",q,["method","code"]),"auth.set":E("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":E("GET","/agent"),"app.skills":E("GET","/skill"),"app.log":E("POST","/log",q,["service","level","message","extra"]),"command.list":E("GET","/command"),"tool.ids":E("GET","/experimental/tool/ids"),"tool.list":E("GET","/experimental/tool",[...q,"provider","model"]),"mcp.status":E("GET","/mcp"),"mcp.add":E("POST","/mcp",q,["name","config"]),"mcp.connect":E("POST","/mcp/{name}/connect"),"mcp.disconnect":E("POST","/mcp/{name}/disconnect"),"mcp.auth.start":E("POST","/mcp/{name}/auth"),"mcp.auth.callback":E("POST","/mcp/{name}/auth/callback",q,["code"]),"mcp.auth.remove":E("DELETE","/mcp/{name}/auth"),"project.list":E("GET","/project"),"project.current":E("GET","/project/current"),"path.get":E("GET","/path")};function yI(e,t){let n=[];for(let r of e.query){let s=t[r];s!=null&&n.push(`${r}=${encodeURIComponent(String(s))}`)}return n.length?`?${n.join("&")}`:""}function hI(e,t,n={},r={}){let s=fI[t],o=s.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(s.bodyParam)i=n[s.bodyParam],a=i!==void 0;else for(let p of s.body)p in n&&(i={...i,[p]:n[p]},a=!0);let c=new Headers(r.headers);return a&&c.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${o}${yI(s,n)}`,{method:s.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function _I(e){if(!e)return"stream";let t=e.split(";")[0]?.trim()??"";return t.startsWith("application/json")||t.endsWith("+json")?"json":t==="multipart/form-data"?"formData":["application/","audio/","image/","video/"].some(n=>t.startsWith(n))?"blob":t.startsWith("text/")?"text":"json"}async function bI(e,t){let n=e.fetch??globalThis.fetch,r;try{r=await n(t)}catch(i){return{error:i||{},request:t,response:void 0}}if(r.headers.get("content-type")==="text/html")throw new Error("The session runtime does not serve this request (it answered text/html)");if(r.ok){let i=_I(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let s=await r.text(),o=s;try{o=JSON.parse(s)}catch{}return{error:o||{},request:t,response:r}}function gm(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let s=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!s.ok)throw Object.assign(new Error(`SSE failed: ${s.status} ${s.statusText}`),{status:s.status});if(!s.body)throw new Error("No body in SSE response");let o=s.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{o.cancel().catch(()=>{})}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:c,value:p}=await o.read();if(c)break;a=(a+p).replace(/\r\n/g,`
13
+ `);let _=gR(f);if(_){if(r(_),_.type==="error")throw new S(_.error,{status:_.status,code:_.code,data:{reason:_.reason}});_.type==="done"&&(p=_.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function uu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function pu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function du(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Qn(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function gu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function mu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function mR(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function fu(e){return u(await c.get(`/projects/${e}/triggers`))}async function yu(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function hu(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function _u(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function fR(e){return u(await c.get(`/accounts/${e}/automations`))}async function yR(e,t){return u(await c.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function bu(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function o_(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.limit!=null&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function Pu(e,t,n){let r={};return n?.payload!==void 0&&(r.payload=n.payload),n?.dryRun!==void 0&&(r.dry_run=n.dryRun),u(await c.post(`/projects/${e}/triggers/${t}/fire`,r))}async function Su(e,t,n){return u(await c.get(`/projects/${e}/triggers/${t}/runs${o_(n)}`))}async function xu(e,t){return u(await c.get(`/projects/${e}/trigger-runs${o_(t)}`))}async function wu(e,t,n,r){return u(await c.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function ku(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await c.get(`/projects/${e}/triggers/event-types?${n}`))}async function vu(e){return u(await c.get(`/projects/${e}/triggers/event-apps`))}var tt=new Map;function Au(e,t){return`${e}::${t}`}function s_(e,t){tt.delete(e),tt.set(e,t)}function i_(e,t){let n=Au(e,t),r=tt.get(n);return r&&s_(n,r),r}function To(e,t,n){let r=Au(e,t);if(!tt.has(r)&&tt.size>=512){let o=tt.keys().next().value;o!==void 0&&tt.delete(o)}s_(r,n)}function a_(e,t){tt.delete(Au(e,t))}function hR(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Xn(){return hR(C().backendUrl||"http://localhost:8008/v1")}function c_(){let e=C().sandboxId;return e?`${Xn()}/p/${e}/8000`:""}function _R(e,t=8e3){return`${Xn()}/p/${e}/${t}`}function Ie(e,t=8e3){return _R(e,t)}function Ru(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Io=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function bR(e){return e instanceof Error&&e.name==="SessionStartError"}function PR(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,o=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Io(o,{status:n,code:r,terminal:!0}):null}function l_(e,t,n){let r=typeof n=="number"?n:n?.waitMs,o=typeof n=="number"?void 0:n?.repositoryMode,s=new URLSearchParams;r&&r>0&&s.set("wait_ms",String(Math.floor(r))),o&&s.set("repository_mode",o),typeof n=="object"&&n?.keepStopped&&s.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&s.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=s.size>0?`?${s.toString()}`:"";return c.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function nt(e,t,n){let r=await l_(e,t,n);if(!r.success||!r.data){let o=PR(r.error);if(o&&!(o.status===404&&Il(t)))throw o;return null}return u_(e,t,r.data)}async function Cu(e,t,n){let r=await l_(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return u_(e,t,r.data)}function u_(e,t,n){let r=n.sandbox?.external_id,o=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&o&&To(e,t,{runtimeSessionId:o,opencodeSessionId:o,runtimeUrl:Ie(r),sandboxId:r}),n}function SR(e,t){return["session-start",e,t]}async function Tu(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function Iu(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function Eu(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await c.delete(`/projects/${e}/model-defaults?${n}`))}async function xR(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function p_(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function wR(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Eo(e){let t=e.connectors_required?p_(e.connectors_required):void 0,n=e.connectors_personal?p_(e.connectors_personal):void 0;if(t&&n&&!wR(t,n))throw new Error("connectors_personal must match connectors_required when both fields are present");let r={...e};return delete r.connectors_personal,(t!==void 0||n!==void 0)&&(r.connectors_required=t??n),r}async function Mu(e,t,n){let r=Eo(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function kR(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Ou(n.block):null}}async function vR(e,t,n){let r=Ou(n,!0),o=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?Ou(o.block):null}}function Ou(e,t=!1){let n=Eo(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function AR(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Du(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var Mo="Use setBillingPlan().",d_="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Lu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",monthly_usd:null,status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function RR(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function CR(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,monthlyUsd:t.monthly_usd??null};let n=e??Lu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:RR(r),label:o,sublabel:null,monthlyUsd:null}}function g_(e){return!!e&&e.can_manage_billing!==!1}function TR(e){return e?.subscription?.can_purchase_credits===!0&&g_(e)}async function m_(e){let t=await c.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?Lu():t.data}function f_(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString();return n?`?${n}`:""}async function ju(e){return m_(`/billing/account-state${f_(e)}`)}async function $u(e){return m_(`/billing/account-state/minimal${f_(e)}`)}async function Uu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await c.get(`/billing/transactions${n?`?${n}`:""}`))}async function Fu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await c.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Nu(){return u(await c.get("/billing/credit-breakdown"))}async function Bu(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function Ku(){return u(await c.get("/billing/tier-configurations"))}async function IR(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return $t(e,`/v1/billing/account-state${t}`)}async function qu(e){throw F("createCheckoutSession",Mo)}async function Gu(e,t){throw F("confirmCheckoutSession",Mo)}async function Wu(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Hu(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Vu(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function zu(e,t,n){throw F("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Yu(e){throw F("cancelScheduledChange",d_)}async function Ju(e,t){throw F("getProrationPreview",d_)}async function Qu(e){return u(await c.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Xu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function ER(e){return u(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Zu(e){return u(await c.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function MR(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function ep(e){return u(await c.post("/billing/plan/preview",{monthly_usd:e.monthlyUsd,account_id:e.accountId}),"Failed to preview the plan change")}async function tp(e){return u(await c.post("/billing/plan",{monthly_usd:e.monthlyUsd,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale,account_id:e.accountId}),"Failed to set billing plan")}async function np(e){return u(await c.post("/billing/enterprise-offer/checkout",{success_url:e.successUrl,cancel_url:e.cancelUrl,account_id:e.accountId}),"Failed to start the Enterprise checkout")}async function rp(e={}){return u(await c.post("/billing/enterprise/contact",{account_id:e.accountId,...e.note?{note:e.note}:{}}),"Failed to reach Kortix sales")}async function OR(e){throw F("createPerSeatCheckout",Mo)}async function DR(e){throw F("claimPerSeatBilling",Mo)}async function LR(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function op(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await c.get(`/usage${n?`?${n}`:""}`))}function ip(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Oo(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Do(e){return e.size>0?`?${e}`:""}async function ap(e={}){let t=new URLSearchParams;return ip(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Oo(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/session-costs${Do(t)}`))}async function Zn(e,t={}){let n=new URLSearchParams;return ip(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Do(n)}`))}async function jR(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Oo(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/cost-by-project${Do(t)}`))}async function $R(e={}){let t=new URLSearchParams;return ip(t,e),e.sessionId&&t.set("session_id",e.sessionId),Oo(t,e),u(await c.get(`/usage/cost-summary${Do(t)}`))}function sp(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let o=t;o.ownerId&&n.set("owner_id",o.ownerId)}Oo(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${C().backendUrl||""}${r}?${n}`}async function UR(e,t={}){let n=sp(e==="projects"?"projects":"sessions",t),r=await je(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),o=r.headers.get("x-kortix-row-cap"),s=o!=null?Number(o):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(s)?s:null}}async function y_(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function FR(e){return y_("slack",e)}function NR(e){return y_("teams",e)}async function h_(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function BR(e){return h_("slack",e)}function KR(e){return h_("teams",e)}async function cp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function lp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var qR={oauth_available:!1,install_url:null};async function up(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?qR:t.data}async function __(e,t,n){return u(await c.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function pp(e,t){return __("slack",e,t)}function dp(e,t){return __("teams",e,t)}async function gp(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function mp(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function GR(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function WR(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function HR(e,t){return u(await c.put(`/projects/${encodeURIComponent(e)}/channels/telegram/allowed-users`,{user_ids:t},{showErrors:!1}),"Failed to update allowed Telegram users")}async function VR(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/telegram`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect Telegram")}async function fp(e,t){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function yp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function hp(e){let t=e.connectionId??e.connection_id??null,n=e.connectorSlug??e.connector_slug??e.connectionSlug??e.connection_slug??"kortix_email";return{...e,connectionId:t,connectorSlug:n}}var zR={provider:"agentmail",managed_available:!1};async function _p(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?hp(r.data):null}async function bp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?zR:t.data}async function Pp(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return hp(n)}async function Sp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function xp(e,t,n){let r=u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return hp(r)}async function YR(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function JR(e,t,n){return u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function wp(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function kp(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function vp(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Ap(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Rp(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await c.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function Cp(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Tp(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ip(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ep(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Mp(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Op(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Dp(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Lp(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function jp(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function $p(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Up(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Fp(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Np(e,t,n,r,o){return u(await c.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...o&&Object.keys(o).length?{generationConfig:o}:{}}),"Gateway request failed")}async function QR(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function XR(){throw F("getReferralCode")}async function ZR(){throw F("refreshReferralCode")}async function eC(e){throw F("validateReferralCode")}async function tC(){throw F("getReferralStats")}async function nC(e={}){throw F("listReferrals")}async function rC(e){throw F("sendReferralEmails")}var Bp="call:";function qp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Bp)&&e.length>Bp.length?{type:"connector_call",executionId:e.slice(Bp.length)}:{type:"review_item",reviewItemId:e}}function P_(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function oC(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[P_(n.status)]+=1;return t}function sC(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function Kp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Gp(e){let t=e.indexOf(".");return t<=0?Kp(e):`(${Kp(e.slice(0,t))}) ${Kp(e.slice(t+1))}`}function iC(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Wt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>typeof e=="string"&&e?e:void 0,Ee=e=>Array.isArray(e)?e:void 0,b_=e=>typeof e=="number"?e:0,aC=e=>e.split(`
14
+ `).map(t=>t.trim()).filter(Boolean);function cC(e,t){let n=Wt(e.advanced),r=$(e.description),o=Ee(e.whatChanged)??(r?aC(r):t.summary?[t.summary]:[]);return{crId:$(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:o,impact:$(e.impact)??"",verification:Ee(e.verification)??[],previewUrl:$(e.previewUrl)??$(e.preview_url),conflicts:Ee(e.conflicts),requestedChanges:Ee(e.requested_changes)??[],advanced:{headRef:$(n.headRef)??$(e.head_ref)??"",baseRef:$(n.baseRef)??$(e.base_ref)??"",headSha:$(n.headSha)??$(e.head_sha)??$(e.head_commit_sha)??"",baseSha:$(n.baseSha)??$(e.base_sha)??"",additions:b_(n.additions),deletions:b_(n.deletions),files:Ee(n.files)??[],mergeMode:$(n.mergeMode)??"merge"}}}function lC(e,t){let n=Ee(e.actions);if(n)return{actions:n.map((l,p)=>({id:$(l.id)??`${t.review_item_id}-${p}`,title:$(l.title)??"Action",connector:$(l.connector)??"",action:$(l.action)??"",consequence:$(l.consequence)??"",risk:$(l.risk)??t.risk,icon:$(l.icon)??"generic",argsPreview:Ee(l.argsPreview)??[],policySource:$(l.policySource)??"Requires approval",decided:l.decided==="approved"||l.decided==="denied"?l.decided:void 0}))};let r=$(e.action_path)??"",{connector:o,action:s}=iC(r),i=Wt(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:$(e.execution_id)??t.review_item_id,title:r?Gp(r):t.title||"Run action",connector:o,connectorName:$(e.connector_name),action:s,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([l,p])=>({key:l,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:$(e.approval_context),...Object.keys(Wt(e.resolved_preview)).length>0?{resolvedPreview:Wt(e.resolved_preview)}:{},...$(e.resolved_error)?{resolvedError:$(e.resolved_error)}:{},connectorRisk:$(e.risk)??null,policySource:"Requires approval",expiresAt:$(t.expires_at)}]}}function uC(e,t){return{artifactKind:$(e.artifactKind)??"document",artifactLabel:$(e.artifactLabel)??"Output",previewUrl:$(e.previewUrl)??$(e.preview_url),preview:$(e.preview),files:Ee(e.files),note:$(e.note)??t.summary??""}}function pC(e,t){return{question:$(e.question)??t.title??"",context:$(e.context),options:Ee(e.options)??[]}}function dC(e,t){return{note:$(e.note)??t.summary??"",children:Ee(e.children)??[]}}function gC(e){let t=Wt(e.detail);switch(e.kind){case"change":return cC(t,e);case"approval":return lC(t,e);case"output":return uC(t,e);case"decision":return pC(t,e);case"batch":return dC(t,e)}}function mC(e,t){let n=typeof e.number=="number"?e.number:void 0,r=$(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function fC(e,t={}){let n=Wt(e.detail),r=e.origin_session_id??void 0,o=r?t.sessionLabels?.[r]:void 0,s=e.kind==="approval"?$(n.action_path):void 0,i=e.kind==="change"?mC(n,e.summary):e.kind==="approval"?o??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:s?Gp(s):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,expiresAt:$(e.expires_at),detail:gC(e)}}var J={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_ROOM_READ:"project.room.read",PROJECT_ROOM_WRITE:"project.room.write",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},yC=[J.PROJECT_WRITE,J.PROJECT_TRIGGER_CREATE,J.PROJECT_TRIGGER_FIRE,J.PROJECT_TRIGGER_UPDATE,J.PROJECT_TRIGGER_DELETE];function hC(e){let t=r=>e[r]?.allowed===!0,n=t(J.PROJECT_WRITE);return{canCreate:n&&t(J.PROJECT_TRIGGER_CREATE),canFire:t(J.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(J.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(J.PROJECT_TRIGGER_DELETE)}}var _C=[J.PROJECT_WRITE,J.PROJECT_GITOPS_PUSH,J.PROJECT_GITOPS_MERGE,J.PROJECT_REVIEW_ACT];function S_(e){let t=r=>e[r]?.allowed===!0,n=t(J.PROJECT_WRITE);return{canOpen:n&&t(J.PROJECT_GITOPS_PUSH),canMerge:n&&t(J.PROJECT_GITOPS_MERGE),canClose:n}}function bC(e,t,n){let r=qp(e.id);if(r.type==="connector_call"){let o=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&o?.canResolve!==!1&&o?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return S_(n).canMerge}return n[J.PROJECT_WRITE]?.allowed===!0&&n[J.PROJECT_REVIEW_ACT]?.allowed===!0}function U(e){return c.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function Wp(e){return A(await U(`/accounts/${e}/iam/groups`)).groups}async function Hp(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}`))}async function Vp(e,t){return A(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function zp(e,t,n){return A(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Yp(e,t){return A(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function Jp(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Qp(e,t,n){return A(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function PC(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Xp(e,t,n){return A(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function SC(e,t){return A(await U(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function xC(e,t){let n=A(await U(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function rt(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function wC(e,t={}){let n=rt({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await U(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function kC(e,t={}){let n=rt({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await U(`/accounts/${e}/iam/policies${n}`)).policies}async function vC(e,t){return A(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function AC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function RC(e,t){return A(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function CC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function TC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Zp(e){return A(await U(`/accounts/${e}/iam/roles`)).roles}async function ed(e){return A(await U(`/accounts/${e}/iam/agent-identities`)).agents}async function td(e){return A(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function nd(e,t){return A(await U(`/accounts/${e}/iam/roles/${t}/permissions`))}async function IC(e){return A(await U(`/accounts/${e}/iam/actions`)).actions}async function rd(e,t){return A(await U(`/accounts/${e}/iam/roles/${t}/usage`))}async function od(e,t){return A(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function sd(e,t,n){return A(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function id(e,t,n){return A(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function ad(e,t){return A(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function EC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function MC(e){return A(await U(`/accounts/${e}/iam/scim/tokens`)).tokens}async function OC(e,t){return A(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function DC(e,t){return A(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function LC(e){return A(await U(`/accounts/${e}/iam/mfa-required`))}async function jC(e){return A(await U(`/accounts/${e}/iam/mfa-required/preview`))}async function $C(e,t){return A(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function UC(e){return A(await U(`/accounts/${e}/iam/session-oversight`))}async function FC(e,t){return A(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function NC(e){return A(await U(`/accounts/${e}/iam/sso/provider`)).provider}async function BC(e,t){return A(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function KC(e,t){return A(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function qC(e){return A(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function GC(e){return A(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function WC(e){return A(await U(`/accounts/${e}/iam/sso/mappings`)).mappings}async function HC(e,t){return A(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function VC(e,t){return A(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function zC(e){return A(await U(`/accounts/${e}/iam/session-policy`))}async function YC(e,t){return A(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function JC(e){return A(await U(`/accounts/${e}/iam/sessions`)).sessions}async function QC(e,t){return A(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function XC(e){return A(await U(`/accounts/${e}/iam/pat-policy`))}async function ZC(e,t){return A(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function eT(e){return A(await U(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function tT(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function nT(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function rT(e,t){return A(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function oT(e){return A(await U(`/accounts/${e}/audit/webhooks`)).webhooks}async function sT(e,t){return A(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function iT(e,t,n){return A(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function aT(e,t){return A(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function cT(e,t={}){let n=rt({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return A(await U(`/accounts/${e}/audit${n}`))}async function cd(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),A(await U(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function ld(e,t,n){return n.length===0?[]:A(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function lT(e){return A(await U(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function uT(e,t){return A(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function ud(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function pd(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function dd(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function gd(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function md(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function fd(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function pT(e){return rt({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function yd(e,t){return u(await U(`/accounts/${e}/iam/assignments${pT(t)}`)).assignments}async function hd(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await c.post(`/accounts/${e}/iam/assignments`,n))}async function _d(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function bd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await U(`/accounts/${e}/iam/permissions${n}`)).permissions}async function dT(){let e=await c.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function gT(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function mT(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function fT(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function yT(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function hT(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function _T(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function bT(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function PT(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function ST(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function xT(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function wT(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var x_="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function kT(e){throw F("getGoogleAuthUrl",x_)}async function vT(e,t){throw F("convertPresentationToGoogleSlides",x_)}async function Pd(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind),t?.sessionId&&n.set("session_id",t.sessionId),t?.limit!=null&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);let r=n.toString();return u(await c.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Sd(e){return u(await c.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function xd(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function wd(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function kd(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function vd(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}async function Ad(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Rd(e){return u(await c.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Cd(e,t){let n=await c.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var Lo=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function w_(e,t=""){return`${Xn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function k_(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let o=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new Lo(o,t.status)}return r}async function AT(e){return k_(w_(e))}async function RT(e){return k_(w_(e,"/messages"))}async function Td(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function Id(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function jo(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function $o(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var CT=4;async function v_(e,t){let n=new Array(e.length),r=0,o=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(CT,e.length)},o));let s={done:[],failed:[]};return e.forEach((i,a)=>{let l=n[a];l.ok?s.done.push(i):s.failed.push({reminder:i,error:l.error})}),s}function Ed(e,t,n){return v_(t,r=>jo(e,r.sessionId,r.reminderId,n))}function Md(e,t){return v_(t,n=>$o(e,n.sessionId,n.reminderId))}async function Od(e){return u(await c.get(`/projects/${e}/reminders`))}var xe=e=>`/projects/${e}/rooms`;function Dd(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o!==void 0&&o!==!1&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function Ld(e,t={}){return u(await c.get(`${xe(e)}${Dd({name:t.name,archived:t.archived,mine:t.mine})}`))}async function jd(e,t){return u(await c.post(xe(e),t))}async function $d(e,t){return u(await c.get(`${xe(e)}/${t}`))}async function Ud(e,t,n){return u(await c.patch(`${xe(e)}/${t}`,n))}async function Fd(e,t,n={}){return u(await c.get(`${xe(e)}/${t}/messages${Dd({after:n.after,before:n.before,limit:n.limit,top:n.top,thread:n.thread})}`))}async function Nd(e,t,n){return u(await c.post(`${xe(e)}/${t}/messages`,n))}async function Bd(e,t,n){return u(await c.post(`${xe(e)}/${t}/read`,n===void 0?{}:{seq:n}))}async function Kd(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/sessions/${n}`,r))}async function qd(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/sessions/${n}`))}async function Gd(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/people/${n}`,r))}async function Wd(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/people/${n}`))}async function Hd(e,t){return u(await c.get(`${xe(e)}/people${Dd({q:t})}`))}async function Vd(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await c.get(`/accounts/tokens${r}`))}async function zd(e){let{accountId:t,expiresAt:n,projectId:r,name:o}=e;return u(await c.post("/accounts/tokens",{name:o,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Yd(e,t,n){let r=new URLSearchParams;t&&r.set("account_id",t),n?.deleteRevoked&&r.set("delete_revoked","true");let o=r.size>0?`?${r.toString()}`:"";return u(await c.delete(`/accounts/tokens/${encodeURIComponent(e)}${o}`))}async function Jd(){return u(await c.get("/oauth/grants")).grants}async function Qd(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function TT(){return u(await c.get("/accounts/me/devices")).devices}async function IT(e){return u(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Xd(e){return u(await c.get(`/projects/${e}/cli-token`))}async function Zd(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function eg(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}function Ht(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,o]of Object.entries(e))n.includes(` ${r} `)&&o!=null&&o!==""&&t.set(r,String(o));return t}function tg(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function ng(e,t){let n=Ht(tg(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function rg(e,t){let n=Ht(tg({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function og(e,t){let n=Ht(tg(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function sg(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function ig(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function ag(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function cg(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function lg(e,t){return u(await c.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function ug(e,t){return u(await c.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function ET(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function pg(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await c.get(`/marketplace/items${n}`))}async function dg(){return u(await c.get("/marketplace/marketplaces"))}async function gg(){return u(await c.get("/marketplace/marketplaces/featured"))}async function mg(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function fg(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function yg(){return u(await c.get("/marketplace/sources"))}async function hg(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function _g(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function MT(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function OT(e){throw F("getTemplate")}async function DT(e,t){throw F("installTemplate")}async function bg(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Pg(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Uo(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Sg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function xg(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function wg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function kg(e,t){let n=await Uo(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await c.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),o=new TextEncoder().encode(JSON.stringify(r)),s="";for(let i of o)s+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(s)}`}}async function vg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Ag(e,t){return u(await c.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function Rg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Cg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Fo(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function No(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function LT(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function jT(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest("SHA-256",t.buffer);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}async function Tg(e,t,n={}){let r=await LT(t),o=n.mediaType??"application/gzip",s=await Fo(e,{kind:"archive",media_type:o});if(!s.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>s.upload.max_bytes)throw new Error(`App artifact exceeds ${s.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(s.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:o}),signal:n.signal,headers:{"content-type":o,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),No(e,s.artifact.artifact_id,{sha256:await jT(r),size_bytes:r.byteLength})}async function Ig(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Eg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Mg(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Og(e,t,n,r={}){let o=new URLSearchParams;r.after!==void 0&&o.set("after",String(r.after)),r.limit!==void 0&&o.set("limit",String(r.limit));let s=o.size?`?${o.toString()}`:"";return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${s}`),"Failed to load App logs")}async function Dg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Lg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function jg(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function $g(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var _e=(e,t)=>`/projects/${e}/apps/${t}`;async function Ug(e,t){return u(await c.get(`${_e(e,t)}/machines`),"Failed to list machines").machines}async function Fg(e,t,n,r){return u(await c.post(`${_e(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Ng=(e,t,n)=>Fg(e,t,n,"start"),Bg=(e,t,n)=>Fg(e,t,n,"stop"),Kg=(e,t,n)=>Fg(e,t,n,"restart");async function qg(e,t,n){return u(await c.delete(`${_e(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Gg(e,t,n,r={}){return u(await c.put(`${_e(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function Wg(e,t,n){return u(await c.post(`${_e(e,t)}/exec`,n),"Failed to run the command")}async function Hg(e,t){return u(await c.get(`${_e(e,t)}/volumes`),"Failed to list volumes").volumes}async function Vg(e,t,n){return u(await c.post(`${_e(e,t)}/volumes`,n),"Failed to create the volume")}async function zg(e,t,n,r){return u(await c.patch(`${_e(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function Yg(e,t,n,r){u(await c.delete(`${_e(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Jg(e,t,n){return u(await c.get(`${_e(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Qg(e,t,n){return u(await c.post(`${_e(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Xg(e,t,n,r){return u(await c.post(`${_e(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function Zg(e,t,n,r){return u(await c.post(`${_e(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function le(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var de=e=>`/drives/${encodeURIComponent(e)}`;async function $T(e){let t=u(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new S("Files not found",{status:404});return t[0]}async function UT(e,t){return u(await c.get(`${de(e)}/access?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load sharing")}async function FT(e,t){return u(await c.put(`${de(e)}/access`,t),"Failed to share folder")}async function NT(e,t){let n=u(await c.delete(`${de(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function BT(e){return u(await c.get(`${de(e)}/principals`),"Failed to load people")}async function KT(e){return u(await c.get(`${de(e)}/conflicts`),"Failed to load conflicts").conflicts}async function qT(e,t){u(await c.post(`${de(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function GT(e,t="/"){return(await A_(e,t)).entries}async function A_(e,t="/"){return u(await c.get(`${de(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function em(e,t,n){let r=le(C().backendUrl),o={path:t};return n?.download&&(o.download="1"),`${r}${de(e)}/files/content?${new URLSearchParams(o)}`}async function WT(e,t,n){let r=await j(em(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new S(o?.message||"Could not download file",{status:r.status})}return r.blob()}async function HT(e,t,n){let r=await j(em(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new S(o?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function VT(e,t,n,r){let o=`${de(e)}/files/content?${new URLSearchParams({path:t})}`,s=r?.ifMatch?{"If-Match":r.ifMatch}:{},i=r?.onProgress,a=globalThis.XMLHttpRequest;if(i&&a){let d=n instanceof Blob?n:new Blob([n]);return zT(a,o,d,s,i,r?.signal)}let l=u(await c.putRaw(o,n,{signal:r?.signal,headers:s}),"Failed to upload file"),p=n instanceof Blob?n.size:n.byteLength;return i?.(p,p),l}async function zT(e,t,n,r,o,s){let i=`${le(C().backendUrl)}${t}`,{headers:a,rejected:l}=await jt(i,{"Content-Type":"application/octet-stream",...r});return new Promise((p,d)=>{let g=new e,m=()=>new S("Request aborted",{name:"AbortError",code:"ABORTED"});if(s?.aborted)return d(m());let f=()=>g.abort();s?.addEventListener("abort",f,{once:!0});let _=()=>s?.removeEventListener("abort",f);g.open("PUT",i),a.forEach((y,k)=>g.setRequestHeader(k,y)),g.upload.onprogress=y=>o(y.loaded,n.size),g.onload=()=>{_();let y=null;try{y=g.responseText?JSON.parse(g.responseText):null}catch{y=null}if(g.status>=200&&g.status<300)return p(y);g.status===401&&l(),d(new S(y?.message||"Failed to upload file",{status:g.status,code:y?.code,url:i}))},g.onerror=()=>{_(),d(new S("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{_(),d(m())},g.send(n)})}async function YT(e,t){return u(await c.post(`${de(e)}/files/mkdir`,{path:t},{showErrors:!1}),"Failed to create folder")}async function JT(e,t,n){return u(await c.post(`${de(e)}/files/move`,{from:t,to:n},{showErrors:!1}),"Failed to move")}async function QT(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await c.delete(`${de(e)}/files?${new URLSearchParams(r)}`,{showErrors:!1}),"Failed to delete")}async function XT(e){return u(await c.get(`${de(e)}/versions`),"Failed to load versions").versions}async function ZT(e,t){u(await c.post(`${de(e)}/restore`,{versionId:t}),"Failed to restore version")}var eI=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function tI(e,t){return(await R_(e,t)).drives}async function R_(e,t){return u(await c.get(eI(e,t)),"Failed to load session files")}function ot(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}var Ke={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function st(){let e=ot("BACKEND_URL")||C().backendUrl;return e||"http://localhost:8008/v1"}function qe(e){let t=le(e);return t.endsWith("/v1")?t:`${t}/v1`}function er(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=er(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return er(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function nI(e){return e==="running"||e==="active"?"active":e==="queued"||e==="branching"||e==="provisioning"?"provisioning":e==="failed"||e==="error"?"error":e==="stopped"||e==="completed"||e==="archived"?"stopped":e||"unknown"}function Bo(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"platinum",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${st()}/p/${n.external_id}/${Ke.KORTIX_MASTER}`:""),status:nI(n?.status||t.status),metadata:{...t.metadata??{},project_id:e.project_id,session_id:t.session_id,project_name:e.name,runtime_status:n?.status,error:t.error},created_at:n?.created_at||t.created_at,updated_at:n?.updated_at||t.updated_at}}async function tm(){let e=await xt(),t=[];for(let n of e){let r=await At(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:Bo(n,o,null)})}return t.sort((n,r)=>{let o={active:0,provisioning:1,stopped:2,error:3},s=(o[n.sandbox.status]??99)-(o[r.sandbox.status]??99);return s!==0?s:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function nm(e){let t=await c.get(`/sessions/${encodeURIComponent(e)}`,{showErrors:!1});if(t.success&&t.data)return t.data;if(t.error?.status===400||t.error?.status===404)return null;throw t.error??new Error("Session request failed")}async function Ko(e){let t=await nm(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await tr(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function tr(e){let t=await tm();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}async function rm(e){return u(await c.post("/notifications/device-token",e))}async function om(e,t){return u(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function sm(e,t){let n=C().fetch??((s,i)=>fetch(s,i)),r=qe(t?.backendUrl??C().backendUrl),o=await n(`${r}/notifications/device-token/release`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({device_token:e}),credentials:"omit",...t?.signal?{signal:t.signal}:{}});if(!o.ok)throw new S(`Device token release failed (HTTP ${o.status})`,{status:o.status,response:o});return{ok:!0}}var rI=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered","message"];async function im(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await c.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function am(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await c.post("/notifications/read",t))}var oI={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1},capture_device_down:{push:!0,email:!0},capture_device_recovered:{push:!0,email:!1},message:{push:!0,email:!0}};async function cm(){return u(await c.get("/notifications/preferences",{showErrors:!1}))}async function lm(e){return u(await c.put("/notifications/preferences",e))}async function um(){return u(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function pm(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await c.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function dm(e,t){return u(await c.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function nr(e){return u(await c.get(`/projects/${e}/model-access`))}async function rr(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}async function or(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/custom-providers`)).providers}async function sr(e,t,n){return u(await c.put(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,n))}var C_=e=>e?.status===404;async function ir(e,t){let n=await c.delete(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,{showErrors:!1});if(!n.success&&!C_(n.error))throw n.error??new Error("Failed to delete the custom provider");let r=`CUSTOM_${t.toUpperCase().replace(/-/g,"_")}_API_KEY`;await Ln(e,r).catch(o=>{if(!C_(o))throw o})}function sI(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:o,previewHasError:s,previewIsLinkOnly:i}=e;return t||n?!1:o?s&&!i:r==="error"}function gm(e){return typeof e=="string"&&e.trim().length>0}function T_(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return gm(t)||gm(n)||gm(r)}function iI(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function ar(e){if(!e)return!0;let t=iI(e.items);return t?!t.some(T_):!T_(e)}var ke="kortix.transcript.v1",I_=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function mm(e){return typeof e=="string"&&I_.includes(e)}var aI=["once","always","reject"],cI=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var O_="kortix-v1-import",lI={harness:O_,harness_version:ke,adapter_version:"1"},fm={schema:ce,v:1},uI={opencode:"[Tool execution was interrupted]",pi:"No result provided"},pI="[Old tool result content cleared]",dI="The following tool was executed by the user",gI=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),mI=e=>gI.get(e)??(e.includes("_")?"mcp":"other"),fI=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),yI=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q=e=>typeof e=="string"?e:void 0,Ge=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ho=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,D_=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Vt=e=>Ge(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,zt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function ym(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,o)=>ym(r,t[o]));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>ym(e[r],Ho(t,r)))}function Go(e,t){if(ym(e,t))return;if(e===void 0)return{del:!0};if(!B(e)||!B(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let o=Go(Ho(e,r),Ho(t,r));o&&D_(n,r,o)}return{sub:n}}function Wo(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=B(e)?{...e}:{};for(let[r,o]of Object.entries(t.sub)){let s=Wo(Ho(n,r),o);s===void 0?delete n[r]:D_(n,r,s)}return n}var cr=e=>Object.values(e??{}).find(t=>t.version===ke),Vo=(e,t)=>({[e]:{version:ke,...t}}),L_=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},E_=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),hI=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),_I=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==ke&&B(n.data?.details));return t?t.data.details:{}};function bI(e,t,n){let r=e.result,o=e.input===null||e.input===void 0?{}:{input:e.input},s=zt(e.started_at)??t.created,i=zt(e.ended_at)??s,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:s}};if(e.status==="error")return{status:"error",...o,error:E_(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:s,end:i}};let l=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...L_(d,t)}]:[]),p=zt(r?.cleared_at);return{status:"completed",...o,output:E_(r?.content),title:e.title??"",metadata:{..._I(e),...a},time:{start:s,end:i,...p!==void 0&&{compacted:p}},...l.length&&{attachments:l}}}function j_(e,t){let n=hI(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...L_(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:bI(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function PI(e){return mm(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function $_(e,t,n={}){let r=e.usage,o=e.finish===null?void 0:yI.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:zt(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...o&&{finish:o},...e.error&&{error:PI(e.error)},...n}}function U_(e,t){return e.role==="assistant"?$_(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function F_(e,t,n){let r=`${e.message_id}-summary`;return{info:$_({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function SI(e,t,n){let r=n||e.producer.harness===O_;if(!r&&(e.role==="system"||e.kind==="context"))return[];let o=cr(e.ext)?.data,s=o&&"runtime_session_id"in o?o.runtime_session_id??null:t,i={sessionID:s,messageID:e.message_id,created:zt(e.created_at),fromV1:r},a=o&&"parts"in o?o.parts:e.blocks.flatMap(d=>{let g=j_(d,i);return g===void 0?[]:[Wo(g,cr(d.ext)?.data)]}),l=[{runtime_session_id:s,info:Wo(U_(e,i),o?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=Wo(F_(e,p,i),o?.summary);l.push({runtime_session_id:s,info:d.info,parts:d.parts})}return l}var hm=e=>Ge(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,qo=e=>String(B(e.info)?e.info.id:""),N_=(e,t)=>hm(e)-hm(t)||(qo(e)<qo(t)?-1:qo(e)>qo(t)?1:0),M_=e=>{let t=cr(e.ext);return t?t.native_id??null:e.thread_id};function zo(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>SI(a,M_(i),cr(i.ext)!==void 0))),o=cr(t.ext)?.data,s=o&&"root_id"in o?o.root_id??null:n?M_(n):null;return{session_id:t.session_id,root_id:s,rows:r.sort(N_)}}function xI(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:B(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=Q(t.p),r=Q(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...Q(t.v)!==void 0&&{variant:t.v}}}function wI(e){if(!B(e.tokens))return null;let t=e.tokens,n=B(t.cache)?t.cache:{};return{input:Ge(t.input)??0,output:Ge(t.output)??0,cache_read:Ge(n.read)??0,cache_write:Ge(n.write)??0,...Ge(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Ge(e.cost)!==void 0&&{cost:e.cost}}}var kI=e=>({code:Q(e.code)||Q(e.name)||"UnknownError",message:Q(B(e.data)?e.data.message:void 0)??""});function B_(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:Q(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...Q(e.url)!==void 0&&{url:e.url}}}function vI(e,t,n,r){let o=e.state,s=B(o.time)?o.time:{};B(o.input)||r.tool_input++;let i=B(o.metadata)&&Ge(o.metadata.exit)!==void 0?{exit_code:o.metadata.exit}:{},a,l,p=o.input??null;if(o.status==="completed"){let m=(Array.isArray(o.attachments)?o.attachments:[]).filter(B).map(_=>{let{bytes:y,...k}=B_(_,n,r);return{type:"attachment",...k}}),f=Vt(s.compacted);a="complete",l={content:[...Q(o.output)!==void 0?[{type:"text",text:o.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:pI}],cleared_at:f}}}else if(o.status==="error"){let m=Q(o.error);a="error",l={content:m!==void 0?[{type:"text",text:m}]:[],is_error:!0,...m!==void 0&&{error:{message:m}},...i}}else if(n.live)a=o.status==="pending"?"pending":"running",a==="pending"&&Q(o.raw)&&!(B(o.input)&&Object.keys(o.input).length)&&(p=o.raw);else{let m=uI[n.h];a="error",l={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Vt(s.start),g=Vt(s.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:mI(e.tool),input:p,status:a,...l&&{result:l},...Q(o.title)&&{title:o.title},...d&&{started_at:d},...g&&{ended_at:g}}}function AI(e,t,n,r,o,s){let i=(a,l=!1)=>({type:"harness",id:t,harness:o.h,kind:a,data:e,model_visible:l,...l&&{fallback_text:dI}});if(!B(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...B_(e,o,s),...Q(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?vI(e,t,o,s):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:Q(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(Q(e.type)||"unknown")}}function RI(e){let t=e.map((o,s)=>B(o)&&typeof o.id=="string"&&o.id?o.id:`#${s}`),n=new Set(t),r=new Set;return t.map(o=>{if(!r.has(o))return r.add(o),o;let s=2;for(;n.has(`${o}#${s}`);)s++;return n.add(`${o}#${s}`),`${o}#${s}`})}function CI(e,t,n,r,o,s){let i=B(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],l=i.role==="user"?a.find(w=>B(w)&&w.type==="compaction"):void 0,p=t&&B(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=l?p:d==="assistant"?i:void 0,m=g&&B(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",_=g&&B(g.time)?Vt(g.time.completed):null,y=s.live?"streaming":"interrupted",k=g?m?f?"aborted":"error":_?"complete":y:l?y:"complete",R=Vt(B(i.time)?i.time.created:void 0)??"",I=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(w=>B(w)&&w.type==="text"&&typeof w.text=="string"?[w.text]:[]).join(""):null,b={tool_input:0,cut_point:0,attachment:0},M=RI(a),h=a.map((w,D)=>AI(w,M[D],l,I,s,b)),x=h.some(w=>w.type==="text"||w.type==="attachment"||w.type==="tool_call"||w.type==="harness"&&w.model_visible),P=!o&&d!=="system"&&(l?k==="complete":!m||f&&x),v=s.live&&P&&k!=="streaming"&&h.some(w=>w.type==="tool_call"&&(w.status==="pending"||w.status==="running"))?"streaming":k,T=o?"superseded":P||!m?void 0:f?"aborted":"failed_attempt";return l&&B(l)&&Q(l.tail_start_id)===void 0&&b.cut_point++,{m:{...fm,message_id:Q(i.id)??"",thread_id:n,seq:r,role:d,kind:l?"compaction":"turn",status:v,in_context:P,...T&&{hidden_reason:T},agent:Q(i.agent)??null,...d==="assistant"&&{reply_to:Q(i.parentID)??null},model:xI(i),usage:g?wI(g):null,finish:!g||l?null:f?"aborted":m?"error":fI.get(i.finish)??null,error:m?kI(m):null,created_at:R,completed_at:g||l?_:R||null,producer:lI,blocks:h},lost:b}}function TI(e,t,n,r,o){let s={};t.runtime_session_id!==r&&(s.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:zt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=Go(t.parts[d],j_(p,i));g&&(p.ext=Vo(o,{data:g}))}):s.parts=t.parts;let a=Go(t.info,U_(e,i));a&&(s.info=a);let l=e.blocks.find(p=>p.type==="compaction");if(n&&l){let p=Go({info:n.info,parts:n.parts},F_(e,l,i));p&&(s.summary=p)}Object.keys(s).length&&(e.ext=Vo(o,{data:s}))}function II(e,t,n){if(t){for(let r of[!0,!1])for(let o of e)if(!(o.runtime_session_id===t||!Array.isArray(o.parts))){for(let s of o.parts)if(!(!B(s)||s.type!=="tool"||!B(s.state))&&(r?B(s.state.metadata)&&s.state.metadata.sessionId===t:n(s.state).includes(t)))return{row:o,part:s}}}}function Yo(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(N_),o=new Map;for(let b of r){let M=o.get(b.runtime_session_id);M?M.push(b):o.set(b.runtime_session_id,[b])}let s=e.root_id,i=o.has(s),a=new Map,l=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of o.keys()){let M=i&&b===s?void 0:II(r,b,l);M&&p.set(b,M)}let d=[...r].reverse().find(b=>b.runtime_session_id===null||!p.has(b.runtime_session_id)),g=i||!d?s:d.runtime_session_id;o.has(g)||o.set(g,[]);let m=g||e.session_id,f=b=>b!==null&&p.has(b)?b:m,_=Vt(r.map(hm).find(Number.isFinite))??"",y=[];for(let[b,M]of o){if(b!==g&&(b===null||!p.has(b)))continue;let h=b===g,x=h?r.filter(N=>N.runtime_session_id!==g&&f(N.runtime_session_id)===m):[],P=[...x,...M],v=new Set(x),T=new Map,L=new Set;for(let N of P){let z=B(N.info)?N.info:{};if(z.role!=="user"||!Array.isArray(N.parts)||!N.parts.some(K=>B(K)&&K.type==="compaction"))continue;let G=P.find(K=>!L.has(K)&&K.runtime_session_id===N.runtime_session_id&&B(K.info)&&K.info.role==="assistant"&&K.info.summary===!0&&K.info.parentID===z.id);G&&(T.set(N,G),L.add(G))}let w=[];for(let N of P){if(L.has(N))continue;let z=T.get(N),{m:G,lost:K}=CI(N,z,h?m:b,w.length+1,v.has(N),n);if(TI(G,N,z,b,n.h),G.in_context)for(let Le of["tool_input","cut_point","attachment"])n.counts[Le]+=K[Le];w.push(G)}let D=b===null?void 0:p.get(b),Se=w.find(N=>N.role==="user"&&N.kind==="turn");y.push({...fm,thread_id:h?m:b,parent_thread_id:D?f(D.row.runtime_session_id):null,spawned_by:D&&typeof D.part.callID=="string"?{message_id:Q(D.row.info?.id)??"",call_id:D.part.callID}:null,agent:Se?.agent??null,title:null,created_at:w[0]?.created_at||_,messages:w,ext:Vo(n.h,b===null?{}:{native_id:b})})}y.sort((b,M)=>b.parent_thread_id===null?-1:M.parent_thread_id===null?1:I(b)-I(M));let k=y[0]?.messages.filter(b=>b.role==="user"&&b.kind==="turn").at(-1),R=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...fm,session_id:e.session_id,title:null,created_at:_,restore_grade:R?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:k?.agent??null,model:k?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:y,...g!==s&&{ext:Vo(n.h,{data:{root_id:s}})}};function I(b){return r.findIndex(M=>M.runtime_session_id===b.thread_id)}}var _m={schema:ce,v:1},EI=Object.freeze({}),K_=new WeakMap;function lr(e){let t=K_.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},s=Yo({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return K_.set(e,{state:e.state,block:s}),s}var bm=new WeakMap;function Pm(e){if(bm.has(e))return bm.get(e);let t={..._m,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:ke}},messages:[{..._m,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=zo({..._m,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return bm.set(e,r),r}function se(e){return Pm(e)}var ge=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",We=e=>ge(e)?se(e):e;function G_(e){let t=se(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:EI}var W_=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function H_(e){return e.status==="complete"?"completed":e.status}var q_=new WeakMap;function V_(e){if(e.status!=="complete")return"";let t=q_.get(e);return t===void 0&&q_.set(e,t=W_(e)),t}function z_(e){return e.status==="error"?e.result?.error?.message||W_(e):void 0}function me(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function MI(e){return me(e)==="bash"}function Sm(e){let t=me(e);return t==="question"||t==="ask"}function OI(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Y_=new Set(["show","show_user"]);function xm(e){return Y_.has(me(e))}function DI(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function wm(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Jo(e))}function Jo(e){let t=ge(e)?se(e):e,n=me(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:ar(t.state?.input)}var J_=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function km(e){return J_.has(me(e))}var LI=50*1024*1024,vm="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",jI=new RegExp(`^kortix-attachment://(${vm})/(${vm})/(${vm})$`);function Rm(e){if(typeof e!="string")return null;let t=jI.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function $I(e){return Rm(e)!==null}var Am=new WeakMap;async function Cm(e,t,n,r={}){if(n.size>LI)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:Am.get(n)?.get(o);if(s?.promise)return s.promise;let i=s??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let l=Am.get(n)??new Map;l.set(o,i),Am.set(n,l)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=c.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(l=>{throw i.promise=void 0,l}),i.promise}async function Tm(e,t){let n=Rm(e);if(!n)throw new Error("Invalid attachment reference");let r=C().backendUrl.replace(/\/$/,""),o=await j(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!o.ok)throw new S("Could not load attachment",{status:o.status});return o.blob()}var UI=new Set(["show","show_user"]);function FI(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let o=r+5;if(o>=e.length||!/\s/.test(e[o])){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return t;let i=e.indexOf("</file>",s+1);if(i===-1)return t;t.push(e.slice(o,s).trimStart()),n=i+7}}var He=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ur=e=>typeof e=="string"&&e.length>0?e:null,Q_=e=>typeof e=="string"?ur(e.split("/").pop()):null;function Qo(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function NI(e){if(Array.isArray(e))return e;if(typeof e!="string"||!e.trim())return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function BI(e){let t=e.blocks.filter(He).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&He(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function KI(e,t){for(let n of FI(e))t(Qo(n,"attachment"),Qo(n,"filename")??Q_(Qo(n,"path")),Qo(n,"mime"))}function qI(e,t){for(let n of[e,...NI(e.items)])He(n)&&t(n.attachment,Q_(n.path),null)}function GI(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=He(r)&&Array.isArray(r.blocks)?BI(r):r;if(!He(o)||!He(o.info)||!Array.isArray(o.parts))continue;let s=ur(o.info.id);if(!s)continue;let i=ur(o.info.role)??"unknown",a=(l,p,d)=>{let g=Rm(l);!g||n.has(l)||(n.add(l),t.push({url:l,attachment_id:g.attachmentId,filename:p,mime:d,message_id:s,role:i}))};for(let l of o.parts)He(l)&&(l.type==="file"?a(l.url,ur(l.filename),ur(l.mime)):l.type==="text"&&typeof l.text=="string"?KI(l.text,a):l.type==="tool"&&typeof l.tool=="string"&&UI.has(me(l.tool))&&He(l.state)&&He(l.state.input)&&qI(l.state.input,a))}return t}function WI(e,t){if(e==null)return t;let n=e.trim().toLowerCase();return["1","true","yes","y","on"].includes(n)?!0:["0","false","no","n","off"].includes(n)?!1:t}function HI(e){if(e==null)return;let t=e.trim().toLowerCase();if(["1","true","yes","y","on"].includes(t))return!0;if(["0","false","no","n","off"].includes(t))return!1}function Im(e,t,n){return e!==void 0?e:WI(ot(t),n)}var Em={get disableMobileAdvertising(){return Im(C().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Im(C().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Im(C().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var VI=new Set(["project-manager"]);function Xo(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Em.enableProjects||!VI.has(e.name)}function zI(e){let t=e.agents.filter(Xo),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function X_(){return{projects:{list:xt,listForAccount:Xi,get:wt,detail:In,create:na,createRepo:ra,provision:oa,update:On,archive:Dn,llmCatalog:En,modelPicker:Mn,modelAccess:nr,setModelAccess:rr,customLlmProviders:or,setCustomLlmProvider:sr,deleteCustomLlmProvider:ir,sandboxHealth:$n,sandboxTemplates:Jc,sessions:At,createSession:Rt},github:{linkRepository:pa,replaceProjectRepository:da,getInstallation:ga,listInstallations:ma,listLinkableInstallations:fa,listRepositories:ya,listRepositoryBranches:ha,linkInstallation:ba,saveInstallation:_a,deleteInstallation:Sa,storeUserToken:Pa},gitBackend:{get:xa,repositories:wa},connectStatus:qc,marketplace:{items:s=>pg(s),item:s=>mg(s),itemFile:(s,i)=>fg(s,i),marketplaces:()=>dg(),featured:()=>gg(),sources:{list:()=>yg(),add:s=>hg(s),remove:s=>_g(s)}}}}function Z_(){return{billing:{accountState:ju,accountStateMinimal:$u,transactions:Uu,transactionsSummary:Fu,creditBreakdown:Nu,usageHistory:Bu,usageRollup:op,sessionCosts:{list:ap,get:Zn},tierConfigurations:Ku,setPlan:tp,previewPlan:ep,acceptEnterpriseOffer:np,contactSales:rp,checkout:{createSession:n=>qu(n),confirmSession:(n,r)=>Gu(n,r)},subscription:{createPortalSession:(n,r)=>Wu(n,r),cancel:(n,r)=>Hu(n,r),reactivate:n=>Vu(n),scheduleDowngrade:(n,r,o)=>zu(n,r,o),cancelScheduledChange:n=>Yu(n),prorationPreview:(n,r)=>Ju(n,r)},credits:{purchase:n=>Qu(n),autoTopupSettings:n=>Xu(n),configureAutoTopup:n=>Zu(n)}},sandboxShares:{list:Ad,create:Rd,revoke:Cd}}}var Yt=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function ie(e,t,n){let r=n?.fetch??C().fetch??((p,d)=>fetch(p,d)),o=le(n?.backendUrl??C().backendUrl??"");if(!o)throw new Yt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${qe(o)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:s,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),l=null;try{l=a?JSON.parse(a):null}catch{l=a}if(!i.ok){let p=l&&typeof l=="object"?l:{};throw new Yt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return l}function Zo(e,t){return ie("/auth/signup",{body:e},t)}function es(e,t){return ie("/auth/sign-in/password",{body:e},t)}function ts(e,t){return ie("/auth/sign-in/magic-link",{body:e},t)}function ns(e,t){return ie("/auth/verify-otp",{body:e},t)}function rs(e,t){return ie("/auth/sign-in/oauth",{body:e},t)}function os(e,t){return ie("/auth/oauth/exchange",{body:e},t)}function Jt(e,t){return ie("/auth/refresh",{body:e},t)}function ss(e,t){return ie("/auth/password/reset",{body:e},t)}function is(e,t,n){return ie("/auth/password/update",{body:e,bearer:t},n)}function as(e,t){return ie("/auth/user",{bearer:e},t)}function cs(e,t,n){return ie("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function ls(e,t){return ie("/auth/sign-in/sso",{body:e},t)}var us={enroll:(e,t,n)=>ie("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function ps(e,t={},n){return ie("/auth/sign-out",{body:t,bearer:e},n)}function ds(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,o=null,s=!e.storage,i=null,a=null,l=0,p=new Set,d=y=>(y.expires_at??0)*1e3,g=y=>d(y)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:o})):await e.storage.remove());for(let y of[...p])try{y(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let y=l,k=(async()=>{let R=await e.storage.get();if(y===l&&R)try{let I=JSON.parse(R);I.session?.access_token&&I.session?.refresh_token&&(r=I.session,o=I.user??null)}catch{r=null}return s=!0,r})();i=k,k.then(()=>{i===k&&(i=null)},()=>{i===k&&(i=null)})}return i}async function _(){if(await f(),!r)return null;if(!a){let y=r.refresh_token,k=l,R=Jt({refresh_token:y},e.request).then(async I=>(k!==l||(r=I.session,I.user&&(o=I.user),await m()),r)).catch(async I=>{if(k!==l)return r;let b=I&&typeof I=="object"&&"status"in I?I.status:0;if(b>=400&&b<500)return r=null,o=null,await m(),null;throw I}).finally(()=>{a===R&&(a=null)});a=R}return a}return{subscribe(y){return p.add(y),()=>{p.delete(y)}},current:()=>r,user:()=>o,load:f,async set(y,k){await f(),l+=1,a=null,r=y,k!==void 0&&(o=k),y||(o=null),await m()},async getToken(){return await f(),r?g(r)?(await _().catch(()=>r))?.access_token??null:r.access_token:null},refresh:_,async clear(){l+=1,a=null,r=null,o=null,s=!0,await m()}}}function eb(){return{list:Ii,get:Mi,create:Ei,secretResources:{list:ec,create:tc,rotate:nc,retry:rc,remove:oc,grant:sc,revoke:ic,setAccess:ac},updateName:Oi,branding:{get:Di,update:Li,uploadAsset:ji,removeAsset:$i,reset:Ui},leave:Ji,members:Fi,invite:Ni,removeMember:zi,updateMemberRole:Yi,invites:Bi,cancelInvite:Ki,resendInvite:qi,tokens:{list:Vd,create:zd,revoke:Yd},connectedApps:{list:Jd,revoke:Qd},audit:{log:ng,export:og,webhooks:{list:sg,create:ig,update:ag,remove:cg}}}}function tb(){return{assignments:{list:yd,create:hd,revoke:_d},permissions:{list:bd,forRole:nd},roles:{list:Zp,create:od,update:sd,setPermissions:id,remove:ad,usage:rd},groups:{list:Wp,get:Hp,create:Vp,update:zp,remove:Yp,members:{list:Jp,add:Qp,remove:Xp}},agentIdentities:ed,oauthClients:{list:ud,get:pd,create:dd,update:gd,rotateSecret:md,remove:fd},can:cd,canBatch:ld}}function nb(){let e={signUp:Zo,signInWithPassword:es,sendMagicLink:ts,verifyOtp:ns,signInWithProvider:rs,exchangeCode:os,refresh:Jt,resetPassword:ss,updatePassword:is,updateUserMetadata:cs,signInWithSso:ls,mfa:us,user:as,signOut:ps,session:ds},t=eb(),n=tb();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Gi,describe:Wi,accept:lo,acceptAndLand:Hi,decline:Vi}}}var pr=new Map,Mm=new Map;function Om(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function rb(e){return pr.get(Om(e))??null}function ob(){return[...pr.values()].filter(e=>typeof e=="string")}function sb(e){return pr.has(Om(e))}async function it(e){let t=Om(e),n=pr.get(t);if(n!==void 0)return n;let r=Mm.get(t);if(r)return r;let o=(async()=>{try{let s=await c.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!s.success)return null;let i=typeof s.data?.preview_url_template=="string"?s.data.preview_url_template:null;return pr.set(t,i),i}catch{return null}finally{Mm.delete(t)}})();return Mm.set(t,o),o}function ib(e){let{apiBaseUrl:t}=e;return sb(t)||it(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:rb(t)}}function ab(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new S(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let o=C().backendUrl??e.backendUrl,s=80,i=t(o);return i&&(s=i.port?Number(i.port):i.protocol==="https:"?443:80),ib({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function cb(e,t){let n=null;async function r(){n||(n=Wn(e,t,{showErrors:!1}).then(o=>{let s=Qn(o)??"",i=s.indexOf("/"),a=i>0&&i<s.length-1?{providerID:s.slice(0,i),modelID:s.slice(i+1)}:void 0,l=o.agent_name?.trim()||void 0;return{model:a,agent:l}}));try{return await n}catch(o){throw n=null,o}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Qt={url:null,sandboxId:null,dbSandboxId:null,version:0},JI=new Set;function gs(e,t=null,n=null){if(!(Qt.url===e&&Qt.sandboxId===t&&Qt.dbSandboxId===n)){Qt={url:e,sandboxId:t,dbSandboxId:n,version:Qt.version+1};for(let r of JI)r()}}function lb(){return Qt.url}var dr=new Map;function ub(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let o=n?.evidence?.error;return o&&o!==n?.message&&r.push(o),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Ct=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function pb(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await nt(e,t,Math.min(3e4,s()));for(;Date.now()<o&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,s()))),i=await nt(e,t,Math.min(3e4,s()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new S(ub(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new S("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ie(l);return gs(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function db(e,t,n){let r=null;function o(){if(r)return r;let p=i_(e,t);return p&&(r=p),r}let s=pb(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=it(C().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Ru(p.session):null,_=f?.sandbox?.external_id,y=f?.runtime_session_id;if(_&&y){let b=Ie(_);return gs(b,_),r={runtimeSessionId:y,opencodeSessionId:y,runtimeUrl:b,sandboxId:_},To(e,t,r),await m,r}let k=`${e}
15
+ ${t}`,R=dr.get(k);if(R)return r=await R,await m,r;let I=s(g);dr.set(k,I);try{return r=await I,await m,r}finally{dr.get(k)===I&&dr.delete(k)}}function a(p){let d=o();if(!d)throw new Ct(p);return d}function l(){r=null,a_(e,t)}return{ensureReady:i,tryResolveReady:o,requireReady:a,forgetReady:l}}var q=["directory","workspace"],gb=["messageID","model","agent","noReply","tools","format","system","variant","parts"],E=(e,t,n=q,r=[],o)=>({method:e,path:t,query:n,body:r,bodyParam:o}),QI={"session.list":E("GET","/session",[...q,"scope","path","roots","start","search","limit"]),"session.get":E("GET","/session/{sessionID}"),"session.create":E("POST","/session",q,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":E("DELETE","/session/{sessionID}"),"session.update":E("PATCH","/session/{sessionID}",q,["title","metadata","permission","time"]),"session.status":E("GET","/session/status"),"session.messages":E("GET","/session/{sessionID}/message",[...q,"limit","before"]),"session.prompt":E("POST","/session/{sessionID}/message",q,gb),"session.promptAsync":E("POST","/session/{sessionID}/prompt_async",q,gb),"session.abort":E("POST","/session/{sessionID}/abort"),"session.revert":E("POST","/session/{sessionID}/revert",q,["messageID","partID"]),"session.unrevert":E("POST","/session/{sessionID}/unrevert"),"session.summarize":E("POST","/session/{sessionID}/summarize",q,["providerID","modelID","auto"]),"session.command":E("POST","/session/{sessionID}/command",q,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":E("POST","/session/{sessionID}/share"),"session.unshare":E("DELETE","/session/{sessionID}/share"),"session.fork":E("POST","/session/{sessionID}/fork",q,["messageID"]),"session.diff":E("GET","/session/{sessionID}/diff",[...q,"messageID"]),"session.todo":E("GET","/session/{sessionID}/todo"),"permission.list":E("GET","/permission"),"permission.reply":E("POST","/permission/{requestID}/reply",q,["reply","message"]),"question.list":E("GET","/question"),"question.reply":E("POST","/question/{requestID}/reply",q,["answers"]),"question.reject":E("POST","/question/{requestID}/reject"),"part.update":E("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",q,[],"part"),"part.delete":E("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":E("GET","/file",[...q,"path"]),"file.read":E("GET","/file/content",[...q,"path"]),"find.files":E("GET","/find/file",[...q,"query","dirs","type","limit"]),"vcs.diff":E("GET","/vcs/diff",[...q,"mode","context"]),"global.health":E("GET","/global/health",[]),"global.dispose":E("POST","/global/dispose",[]),"global.config.get":E("GET","/global/config",[]),"global.config.update":E("PATCH","/global/config",[],[],"config"),"provider.list":E("GET","/provider"),"provider.auth":E("GET","/provider/auth"),"provider.oauth.authorize":E("POST","/provider/{providerID}/oauth/authorize",q,["method","inputs"]),"provider.oauth.callback":E("POST","/provider/{providerID}/oauth/callback",q,["method","code"]),"auth.set":E("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":E("GET","/agent"),"app.skills":E("GET","/skill"),"app.log":E("POST","/log",q,["service","level","message","extra"]),"command.list":E("GET","/command"),"tool.ids":E("GET","/experimental/tool/ids"),"tool.list":E("GET","/experimental/tool",[...q,"provider","model"]),"mcp.status":E("GET","/mcp"),"mcp.add":E("POST","/mcp",q,["name","config"]),"mcp.connect":E("POST","/mcp/{name}/connect"),"mcp.disconnect":E("POST","/mcp/{name}/disconnect"),"mcp.auth.start":E("POST","/mcp/{name}/auth"),"mcp.auth.callback":E("POST","/mcp/{name}/auth/callback",q,["code"]),"mcp.auth.remove":E("DELETE","/mcp/{name}/auth"),"project.list":E("GET","/project"),"project.current":E("GET","/project/current"),"path.get":E("GET","/path")};function XI(e,t){let n=[];for(let r of e.query){let o=t[r];o!=null&&n.push(`${r}=${encodeURIComponent(String(o))}`)}return n.length?`?${n.join("&")}`:""}function ZI(e,t,n={},r={}){let o=QI[t],s=o.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(o.bodyParam)i=n[o.bodyParam],a=i!==void 0;else for(let p of o.body)p in n&&(i={...i,[p]:n[p]},a=!0);let l=new Headers(r.headers);return a&&l.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${s}${XI(o,n)}`,{method:o.method,headers:l,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function eE(e){if(!e)return"stream";let t=e.split(";")[0]?.trim()??"";return t.startsWith("application/json")||t.endsWith("+json")?"json":t==="multipart/form-data"?"formData":["application/","audio/","image/","video/"].some(n=>t.startsWith(n))?"blob":t.startsWith("text/")?"text":"json"}async function tE(e,t){let n=e.fetch??globalThis.fetch,r;try{r=await n(t)}catch(i){return{error:i||{},request:t,response:void 0}}if(r.headers.get("content-type")==="text/html")throw new Error("The session runtime does not serve this request (it answered text/html)");if(r.ok){let i=eE(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let o=await r.text(),s=o;try{s=JSON.parse(o)}catch{}return{error:s||{},request:t,response:r}}function Dm(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let o=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!o.ok)throw Object.assign(new Error(`SSE failed: ${o.status} ${o.statusText}`),{status:o.status});if(!o.body)throw new Error("No body in SSE response");let s=o.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{s.cancel().catch(()=>{})}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:l,value:p}=await s.read();if(l)break;a=(a+p).replace(/\r\n/g,`
16
16
  `).replace(/\r/g,`
17
17
  `);let d=a.split(`
18
18
 
19
19
  `);a=d.pop()??"";for(let g of d){let m={},f=[];for(let _ of g.split(`
20
20
  `))if(_.startsWith("data:"))f.push(_.replace(/^data:\s*/,""));else if(_.startsWith("id:"))m.id=_.replace(/^id:\s*/,"");else if(_.startsWith("retry:")){let y=Number.parseInt(_.replace(/^retry:\s*/,""),10);Number.isNaN(y)||(m.retry=y)}f.length&&(m.data=f.join(`
21
- `)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*PI(e,t,n){let r=e.eventTransport??gm(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal:s}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(o=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(c){if(n.onSseError?.(c),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(o*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function rr(e){let t=s=>(o,i)=>bI(e,hI(e.baseUrl,s,o,i)),n=s=>o=>t(s)(void 0,o);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(s={})=>({stream:PI(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,s)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var H_=200;async function SI(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function Ct(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new x(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function z_(e){let t=e.runtimeUrl.replace(/\/$/,""),n=rr({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${s}${d.size?`?${d}`:""}`,m=y=>e.fetch(new Request(`${t}${y}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new x(`Reading the session transcript failed: ${await SI(f)}`,{status:f.status,response:f});let _=await f.json();return{messages:_.messages??[],hasMore:_.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,H_),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await o(Math.min(r.limit-a.length,H_),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,s,o]=await Promise.all([n.session.status().then(i=>Ct(i,"Reading the session status failed")),n.permission.list().then(i=>Ct(i,"Reading permission requests failed")),n.question.list().then(i=>Ct(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{Ct(await n.permission.reply({requestID:r,reply:s,...o!==void 0?{message:o}:{}}),"Answering the permission request failed")},answerQuestion:async(r,s)=>{if(s===null){Ct(await n.question.reject({requestID:r}),"Dismissing the question failed");return}Ct(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let o=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof o?.model=="string"?o.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(s={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!s)throw new x("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return Ct(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function Y_(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return z_({runtimeUrl:r,rootId:n,fetch:L})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,s)=>(await t()).answerPermission(n,r,s),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function J_(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await ou(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var zt=BigInt(4096),Ve=BigInt(0xffffffffffff),Q_=Ve+BigInt(1),xI=Q_/BigInt(2),it=BigInt(3600*1e3)*zt,co=120*1e3,X_=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,wI=/^msg_([0-9a-f]{12})/,Z_="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Tt(e){let t=wI.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Yt(e){return BigInt(Math.trunc(e))*zt&Ve}function It(e,t){let n=e-t&Ve;return n>=xI&&(n-=Q_),n}function mm(e){let t=null;for(let n of e)n!=null&&(t===null||It(n,t)>BigInt(0))&&(t=n);return t}function eb(e,t){let n=Tt(e);return n===null?!1:It(n,Yt(t))>it}function tb(e,t){let n=t===void 0?null:Yt(t);return nb(e,r=>n===null||It(r,n)<=it)}function nb(e,t){let n=[];for(let r of e){let s=Tt(r);s!==null&&t(s)&&n.push(s)}return mm(n)}function kI(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Z_[n%62])}return e}function fm(e){let t=e.random,n=Yt(e.nowMs-(e.backdateMs??co)),r=e.newestKnownTime??null;if(r!==null){let o=It(r,n);o>=BigInt(0)&&o<=it&&(n=r+BigInt(1)&Ve)}let s="";if(t)for(let o=0;o<14;o++)s+=Z_[Math.min(61,Math.floor(t()*62))];else s=kI();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function lo(e={}){let t=e.nowMs??Date.now(),n=Yt(t-co),r=nb(e.after??[],s=>{let o=It(s,n);return o>=BigInt(0)&&o<=it});return fm({nowMs:t,newestKnownTime:r}).id}function rb(e){return{scope:()=>ru(e.projectId,e.sessionId),providerSecretPool:{list:()=>ic(e.projectId,e.sessionId),get:t=>oc(e.projectId,e.sessionId,t),set:(t,n)=>ac(e.projectId,e.sessionId,t,n)},rescope:t=>su(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,s=n?.agent??e.agent,o=r&&s?{}:await e.persistedPromptDefaults(),i=r??o.model,a=s??o.agent,c=lo(),p=await Kn(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new x("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var sb=async function*(e){let t=I().eventStreamTransport;if(!t){yield*gm(((s,o)=>L(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await Zr(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function He(){let e=B_();return e||(I().billingEnabled??!1?"":Bh())}async function ym(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function hm(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function _m(e){let t=hm(e),n=await L(`${t}/env`);if(!n.ok)throw new Error(await ym(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function bm(e,t,n){let r=hm(e),s=await L(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await ym(s,"Failed to save secret"))}async function Pm(e,t){let n=hm(e),r=await L(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await ym(r,"Failed to delete secret"))}var ob={list:_m,set:bm,delete:Pm};async function ib(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await L(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}async function uo(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function sr(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return ue(e)}async function xm(e){let t=sr(e),n=await L(`${t}/kortix/pty`);if(!n.ok)throw new Error(await uo(n,"Failed to list terminals"));return n.json()}async function wm(e,t){let n=sr(e),r=await L(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await uo(r,"Failed to create terminal"));return r.json()}async function km(e,t,n){let r=sr(e),s=await L(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await uo(s,"Failed to update terminal"));return s.json()}async function vm(e,t){let n=sr(e),r=await L(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await uo(r,"Failed to remove terminal"))}async function Am(e,t,n){let r=sr(t),o=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),ue(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await $t();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${o}${o.includes("?")?"&":"?"}${c}`:o}function ab(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var at="\x1B",cb="\x07",vI="\0",Sm=`(?:${cb}|${at}\\\\)`,AI=[new RegExp(`${at}\\]697;[^${cb}${at}]*${Sm}`,"g"),new RegExp(`${vI}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${at}\\][0-9]+;rgb:[0-9a-fA-F/]+${Sm}`,"g"),new RegExp(`${at}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Sm}`,"g"),new RegExp(`${at}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${at}\\[\\d+;\\d+R`,"g"),new RegExp(`${at}\\[\\?[0-9;]*c`,"g")];function lb(e){let t=e;for(let n of AI)t=t.replace(n,"");return t}var ub={list:xm,create:wm,update:km,remove:vm,webSocketUrl:Am};async function O(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await L(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await o.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!o.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${o.status}`);return a}async function RI(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return O(e,`/kortix/tasks${r}`)}async function CI(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function TI(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function II(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function EI(e,t){return O(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function MI(e,t,n){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function OI(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function DI(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function jI(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function LI(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return O(e,`/kortix/tickets${n}`)}async function $I(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function UI(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function FI(e,t){return O(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function NI(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function KI(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function BI(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function qI(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function GI(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function WI(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function VI(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function HI(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function zI(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function YI(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function JI(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function QI(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function XI(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function ZI(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function eE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function tE(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function nE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function rE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function sE(e,t,n=200){return O(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function oE(e){return O(e,"/kortix/projects")}async function iE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function aE(e,t){return O(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function cE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function lE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function uE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function pE(e,t,n="all"){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function dE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function gE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function mE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function fE(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function yE(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function hE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function _E(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function bE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function PE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function SE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function xE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function wE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var kE=1e4,vE={retryOnAuthError:!1};function Jt(e,t,n){return O(e,t,{signal:AbortSignal.timeout(kE),...n},vE)}async function AE(e,t=!1){return(await Jt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function RE(e){return(await Jt(e,"/kortix/services/templates")).templates??[]}async function CE(e,t){return(await Jt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function TE(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Jt(e,s,{method:r?"DELETE":"POST"})}async function IE(e,t){return Jt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function EE(e,t){return Jt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var ze=new Map,ME=256,Qt=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ct(){let e=He();if(!e)throw new Qt;return Me(e)}function Me(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=ze.get(e);if(t)return ze.delete(e),ze.set(e,t),t;if(!Gr())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=rr({baseUrl:e,fetch:L,eventTransport:sb});return ze.set(e,n),ze.size>ME&&ze.delete(ze.keys().next().value),n}function OE(e){ze.delete(e)}function DE(){ze.clear()}var po=new Map;function jE(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=po.get(e);if(t)return t;let n=rr({baseUrl:e,fetch});return po.set(e,n),n}function LE(e){po.delete(e)}function $E(){po.clear()}async function UE(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n?.error||n?.message||t||e.statusText||`HTTP ${e.status}`}catch{return t||e.statusText||`HTTP ${e.status}`}}async function FE(e){let t=He();if(!t)throw new x("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await L(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new x(`System reload failed (${r.status}): ${await UE(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new x(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new x(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var pb="frontend";function go(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${pb}] ${t}`,...n?[n]:[]);try{ct().app.log({service:pb,level:e,message:t,extra:n})}catch{}}var Ye={debug:(e,t)=>go("debug",e,t),info:(e,t)=>go("info",e,t),warn:(e,t)=>go("warn",e,t),error:(e,t)=>go("error",e,t)};var NE=16,KE=8,db=6e4,BE=250,qE=1e3,GE=3e4,WE=5,VE=.5,HE=3e3,zE=3e4,gb=2e4,YE=2e3,mb=8;function JE(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function QE(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function fb(e,t){let n=[],r,s=0,o=new Map,i=()=>{if(r&&e.clearTimeout(r),r=void 0,n.length===0)return;let c=n;n=[],o.clear(),s=e.now();for(let p of c)p&&t(p.event)},a=()=>{if(r)return;let c=e.now()-s;r=e.setTimeout(i,Math.max(0,NE-c))};return{push(c){let p=QE(n[n.length-1]?.event,c);if(p)n[n.length-1]={type:p.type,event:p};else{let d=JE(c);if(d){let g=o.get(d);g!==void 0&&(n[g]=void 0),o.set(d,n.length)}n.push({type:c.type,event:c})}a()},flush:i,clearTimer:()=>{r&&e.clearTimeout(r)}}}function yb(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}function Rm(e,t,...n){for(let r of e){let s=t(r);if(s)try{s(...n)}catch(o){console.warn("[opencode-events] subscriber handler threw, skipping",o)}}}async function XE(e,t,n,r){return new Promise((s,o)=>{let i=!1,a=t.setTimeout(()=>{i||(i=!0,Ye.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:n}),r.abort(),o(new Error(`SSE connect timed out after ${n}ms`)))},n);e.global.event({signal:r.signal,sseDefaultRetryDelay:HE,sseMaxRetryDelay:zE,sseMaxRetryAttempts:1}).then(c=>{i||(i=!0,t.clearTimeout(a),s(c))},c=>{i||(i=!0,t.clearTimeout(a),o(c))})})}async function ZE(e,t,n,r,s){let o=!1,i=t.now(),a=e[Symbol.asyncIterator]();for(;!n.aborted;){let c=a.next().then(f=>({kind:"next",result:f}),f=>({kind:"error",error:f})),p=yb(n),d=await Promise.race([c,p.promise.then(()=>({kind:"aborted"}))]);if(p.cleanup(),d.kind==="aborted")break;if(d.kind==="error")throw d.error;if(d.result.done)break;s();let g=d.result.value,m=g&&typeof g=="object"&&"payload"in g?g.payload:g;m?.type&&(m.type!=="server.connected"&&(o=!0),r.push(m),!(t.now()-i<KE)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function hb(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<YE)}function _b(e,t,n){Ye.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),Rm(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function bb(e,t,n){let r=t?BE:Math.min(qE*2**Math.min(e-1,WE),GE);return Math.round(r*(1+VE*(n.random?.()??0)))}function Pb(e,t,n){return new Promise(r=>{let s=e.setTimeout(r,n),o=()=>{e.clearTimeout(s),r()};t.addEventListener("abort",o,{once:!0})})}async function Sb(e){let{client:t,t:n,connectTimeoutMs:r,heartbeatTimeoutMs:s,outerSignal:o,retryCount:i,setConnectionState:a,onConnected:c,coalescer:p}=e,d=!1,g=!1,m,f=null,_=new AbortController;a("connecting");let y=yb(o);y.promise.then(()=>_.abort());try{let{stream:v}=await XE(t,n,r,_);c();let R=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{Ye.warn("SSE heartbeat timeout, forcing reconnect"),_.abort()},s)};R(),d=await ZE(v,n,_.signal,p,()=>{a("open"),R()}),g=d}catch(v){if(f=v,o.aborted)return{streamHadWork:d,stableConnection:g,error:f};let R=String(v),T=Dt(v)||Dt(v?.cause);if(Ye.error("SSE event stream error",{error:R,retryCount:i,isAuthError:T}),T)try{is(),await os(),Ye.info("SSE: refreshed auth token after auth error")}catch(b){Ye.error("SSE: failed to refresh auth token",{error:String(b)})}}finally{n.clearTimeout(m),_.abort(),y.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function xb(e){return{type:"heartbeat-gap",gapMs:e}}function wb(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var eM={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},tM=5e3,nM=1e4,rM=4,or=new WeakMap;function sM(e,t,n){let r=t.timers??eM,s=t.connectTimeoutMs??gb,o=t.heartbeatTimeoutMs??db,i=t.maxConsecutiveHardFailures??mb,a=new AbortController,c=(v,...R)=>Rm(n,v,...R),p=null,d=!1,g=v=>{p!==v&&(p=v,v&&c(R=>R.onConnectionChange,v))},m=r.now(),f=null,_=fb(r,v=>{m=r.now(),c(R=>R.onEvent,v)}),y={client:e,t:r,connectTimeoutMs:s,heartbeatTimeoutMs:o,outerSignal:a.signal,setConnectionState:g,onConnected:()=>{if(f){let v=r.now()-f.lastActivityAt,R=f.eventful;f=null,(R||v>tM)&&c(T=>T.onGapRehydrate,v)}m=r.now()},coalescer:_};return(async()=>{let v=0,R=0,T=0;for(;!a.signal.aborted;){let b=r.now(),M=await Sb({...y,retryCount:v});if(a.signal.aborted)break;let h=M.error,{streamHadWork:S,stableConnection:P}=M,k=r.now()-b;if(R=hb(S,h,k)?R+1:0,R>=i){_b(n,R,h),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||S},T=P&&k<nM?T+1:0;let w=P&&T<=rM;w?v=0:(v++,v>1&&Ye.warn("SSE event stream reconnecting",{retryCount:v})),await Pb(r,a.signal,bb(v,w,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),_.clearTimer()}}}function mo(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?Me(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s},c=or.get(i);if(c?.isParked()&&(or.delete(i),c=void 0),!c)c=sM(i,e,new Set([a])),or.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&s?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),or.get(i)===p&&or.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function kb(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Me(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return mo({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Ab(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new x(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Im(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function le(e){let t=(e??He()).trim();if(!t)throw new Qt;return t}async function cr(e,t){let n=await L(`${le(t)}${e}`);if(!n.ok)throw new x(await Im(n),{status:n.status,response:n});return n.json()}async function Em(e,t,n,r,s){let o=await L(`${le(s)}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new x(`${r} failed (${o.status}): ${await Im(o)}`,{status:o.status,response:o});return o.json()}var yo=["/workspace","/tmp","/home","/opt"],oM=yo.filter(e=>e!=="/workspace");function Mm(e){return yo.some(t=>e===t||e.startsWith(`${t}/`))}function en(e){return Mm(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function lt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(oM.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Om=lt;async function tn(e,t){let n=le(t),r=lt(e)||".";return(await cr(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function nn(e,t){let n=lt(e);return cr(`/file/content?path=${encodeURIComponent(n)}`,t)}async function iM(e,t,n){let r=le(n),s=lt(e),o=await L(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new x(await Im(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new x("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var aM=8,fo=0,Rb=[];async function cM(){if(fo<aM){fo++;return}await new Promise(e=>Rb.push(e)),fo++}function lM(){fo--,Rb.shift()?.()}function Cb(e,t){let n=le(t);return Mn(`${n}/file/raw?path=${encodeURIComponent(lt(e))}`)}async function rn(e,t){await cM();try{let n=le(t);try{return await iM(e,void 0,n)}catch{}let r=await nn(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{lM()}}async function lr(e){return cr("/file/status",le(e))}async function ur(e,t,n){let r=le(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),cr(`/find/file?${s.toString()}`,r)}async function pr(e,t){let n=le(t);return(await cr(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var ir=[400,1200],uM=e=>e===408||e===429||e===502||e===503||e===504,vb=e=>new Promise(t=>setTimeout(t,e));function pM(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Cm=3e4,Tb=15*6e4,dM=256;function Xt(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Cm;let t=Cm+e/dM;return Math.min(Tb,Math.max(Cm,Math.round(t)))}async function gM(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function ar(e,t){let n;for(let s=0;s<=ir.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,pM(a)||s===ir.length)break;await vb(ir[s]);continue}if(o.ok)return o.json();let i=await gM(o);if(n=new x(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!uM(o.status)||s===ir.length)throw n;await vb(ir[s])}if(n instanceof x)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new x(`Upload failed: ${r}`)}var Tm=8*1024*1024;function mM(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new x(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Ib(e,t){try{e?.onProgress?.(t)}catch{}}function Eb(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function fM(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function sn(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=le(o),c=Xt(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Tm){let d=await ar(()=>Eb(e,t,p),g=>L(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:c}));return mM(d[0],e.size),Ib(i,{loadedBytes:e.size,totalBytes:e.size}),d}return yM(e,t,p,a,i)}async function yM(e,t,n,r,s){let i=(await ar(()=>Eb(new Blob([],{type:e.type}),t,n),c=>L(`${r}/file/upload`,{method:"POST",body:c},{timeoutMs:Xt(0)})))[0]?.path;if(!i)throw new x("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=fM(i);if(!a.name)throw new x(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let c=0;c<e.size;c+=Tm){let p=Math.min(e.size,c+Tm),d=e.slice(c,p,e.type),g=await ar(()=>{let m=new FormData;return a.parent&&m.append("path",a.parent),m.append("filename",a.name),m.append("first",c===0?"true":"false"),m.append("offset",String(c)),m.append("file",d,a.name),m},m=>L(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:Xt(d.size)}));if(g.path!==i||g.size!==p)throw new x(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Ib(s,{loadedBytes:p,totalBytes:e.size})}}catch(c){throw await Et(i,r).catch(()=>{}),c}return[{path:i,size:e.size}]}function Mb(e,t,n){let r=le(n);return ar(()=>{let s=new FormData;return t&&s.append("path",t),s.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),s},s=>L(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:hM}))}var hM=Tb;function _M(e,t,n){let r=le(n),s=Xt(t.size);return ar(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>L(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var Zt=class extends x{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function dr(e,t){let n=le(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",c=en(`${a}/${i}`),p=[];try{p=await tn(Ob(c),n)}catch(g){if(!(g instanceof x&&g.status===404))throw g}if(p.some(g=>g.name===Db(c)))throw new Zt(c);let d=await jb(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function gr(e,t,n){let r=le(n);return _M(t,await rn(e,r),r)}function bM(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Ob(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Db(e){return e.slice(e.lastIndexOf("/")+1)}function PM(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function mr(e,t,n){let r=le(n),s=en(bM(e.trim()));return jb(s,t,r,{overwrite:!0})}async function jb(e,t,n,r){let s=Db(e);if(!s)throw new x(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=Ob(e);await on(o,n).catch(()=>{});let i=PM(),a=await sn(t,o,`.${s}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new x(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=en(c);try{await Lb(p,e,n,r.overwrite)}catch(g){throw await Et(p,n).catch(()=>{}),!r.overwrite&&g instanceof x&&g.status===409?new Zt(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Et(e,t){return Em("/file","DELETE",{path:e},"Delete",t)}async function on(e,t){return Em("/file/mkdir","POST",{path:e},"Mkdir",t)}async function fr(e,t,n){return Lb(e,t,le(n),!0)}async function Lb(e,t,n,r){return Em("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function Dm(){return Ab(await ct().project.current())}async function ho(){return Ab(await ct().global.health())}async function jm(){try{return(await ho()).healthy===!0}catch{return!1}}var $b={list:tn,read:nn,readBlob:rn,status:lr,findFiles:ur,findText:pr,upload:sn,write:mr,create:dr,copy:gr,remove:Et,mkdir:on,rename:fr,currentProject:Dm,health:ho,isReachable:jm,toDaemonPath:lt,toSandboxAbsolutePath:en,toWorkspaceRelative:Om};function Ub(e){return{list:async t=>tn(t,(await e()).runtimeUrl),read:async t=>nn(t,(await e()).runtimeUrl),readBlob:async t=>rn(t,(await e()).runtimeUrl),status:async()=>lr((await e()).runtimeUrl),findFiles:async(t,n)=>ur(t,n,(await e()).runtimeUrl),findText:async t=>pr(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>sn(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>mr(t,n,(await e()).runtimeUrl),create:async t=>dr(t,(await e()).runtimeUrl),copy:async(t,n)=>gr(t,n,(await e()).runtimeUrl),remove:async t=>Et(t,(await e()).runtimeUrl),mkdir:async t=>on(t,(await e()).runtimeUrl),rename:async(t,n)=>fr(t,n,(await e()).runtimeUrl)}}function Fb(e){return{get:t=>Un(e.projectId,e.sessionId,t),presence:(t,n)=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>Vn(e.sessionId,{projectId:e.projectId}),update:t=>Jl(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),Ql(e.projectId,e.sessionId)),restore:()=>Zl(e.projectId,e.sessionId),recover:()=>Xl(e.projectId,e.sessionId),start:(...t)=>tt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Su(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Bn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),qn(e.projectId,e.sessionId)),configState:()=>eu(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),tu(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),nu(e.projectId,e.sessionId,...t)),setSharing:t=>Tl(e.projectId,e.sessionId,t),previews:()=>jl(e.projectId,e.sessionId),participants:()=>Il(e.projectId,e.sessionId),watch:()=>El(e.projectId,e.sessionId),setWatch:t=>Ml(e.projectId,e.sessionId,t),setPinned:t=>Ol(e.projectId,e.sessionId,t),setArchived:t=>Dl(e.projectId,e.sessionId,t),commit:t=>wl(e.projectId,e.sessionId,t),publicShares:{list:()=>Ll(e.projectId,e.sessionId),create:(...t)=>$l(e.projectId,e.sessionId,...t),revoke:(...t)=>Ul(e.projectId,e.sessionId,...t)}}}function Nb(e){return{reminders:{list:()=>xd(e.projectId,e.sessionId),create:t=>wd(e.projectId,e.sessionId,t),update:(t,n)=>Is(e.projectId,e.sessionId,t,n),remove:t=>Es(e.projectId,e.sessionId,t)},audit:(t,n)=>Kl(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>om(e.projectId,e.sessionId,t,n),read:(t,n)=>im(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Bl(e.projectId,e.sessionId,t),messageAuthors:()=>iu(e.projectId,e.sessionId),modelUsage:()=>au(e.projectId,e.sessionId),transcriptSync:t=>Fn(e.projectId,e.sessionId,t),log:t=>ql(e.projectId,e.sessionId,t),turn:()=>Nn(e.projectId,e.sessionId),prompts:{create:t=>Kn(e.projectId,e.sessionId,t),list:()=>Gl(e.projectId,e.sessionId),remove:t=>Wl(e.projectId,e.sessionId,t),retry:t=>zl(e.projectId,e.sessionId,t),edit:(t,n)=>Vl(e.projectId,e.sessionId,t,n),interrupt:t=>Hl(e.projectId,e.sessionId,t),hold:t=>Yl(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function Kb(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var xM=["control_plane","provider_ingress","daemon","upstream_port"];function Lm(e){return typeof e=="string"&&xM.includes(e)?e:null}function $m(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.harness?e.harness.ready===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function Um(e,t){let n=(e===void 0?He():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await L(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let i=o,a=Lm(r.headers.get("X-Kortix-Proxy-Hop"))??Lm(o?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var Bb=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,qb=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,Gb=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,Wb=new Set([22,4096,parseInt(We.KORTIX_MASTER,10)]);function wM(e){return qb.test(e)}function _o(e){if(!e)return"/";let t=e,n=t.indexOf("](");n!==-1&&(t=t.slice(0,n));let r=t.toLowerCase().indexOf("%5d(");return r!==-1&&(t=t.slice(0,r)),t?t.startsWith("/")?t:`/${t}`:"/"}function kM(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var vM=new Set(["'",'"',"`","<","(","["]),AM=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function RM(e){let t=0,n=e.length;for(;t<n&&(e[t]===" "||e[t]===" ");)t++;for(;n>t&&(e[n-1]===" "||e[n-1]===" ");)n--;for(;t<n&&vM.has(e[t]);)t++;for(;n>t&&AM.has(e[n-1]);)n--;return e.slice(t,n)}function CM(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var TM=/^\/proxy\/(\d{1,5})(\/.*)?$/,IM=/^\/(connectors|settings|dashboard|projects|agents|skills|tools|commands|support|changelog|files|p|browser|desktop|terminal|sessions|services|workspace|channels|scheduled-tasks|marketplace|templates|tunnel|admin|auth)(\/|$|\?)/;function Vb(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:IM.test(t.pathname)}catch{return!1}}function hr(e){if(!e)return null;let t=RM(kM(e.trim())),n=Nm(t);if(n){let r=_o(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(We.KORTIX_MASTER,10);if(s===i){let c=r.pathname.match(TM);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return s=p,o=_o(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=_o(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=CM(e);return r&&r!==e?hr(r):null}}function EM(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,i=o+r[0].length;t.some(([c,p])=>o>=c&&i<=p)||t.push([o,i])}return t}function MM(e,t){return t.some(([n,r])=>e>=n&&e<r)}function Hb(e){let t=[],n=new Set,r=EM(e);Bb.lastIndex=0;let s;for(;(s=Bb.exec(e))!==null;){let o=hr(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:c}=o;a<1||a>65535||Wb.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:MM(s.index,r)}))}return t}function OM(e){return Hb(e).length>0}function DM(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function zb(e){return e.trim().toLowerCase().split("_").join("-")}function Yb(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function jM(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(zb(n.sandboxId));return`${Yb(s)}${t}`}function Jb(e){return e.sandboxId.trim().length>0}function ut(e,t,n){let r=_o(t);if(!Jb(n))return eP(e,r);let s=jM(e,r,n);return s||(DM(n.apiBaseUrl)?`http://p${e}-${zb(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${Yb(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function LM(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return ut(3211,`/open?path=/workspace/${r}`,t)}function Qb(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function $M(e){return`http://localhost:3211${Qb(e)}`}function Xb(){return"/health"}function UM(e){return ut(3211,Xb(),e)}function FM(e,t){return ut(e,"/",t)}function Zb(e){let t=hr(e);return!(!t||Wb.has(t.port)||Vb(e))}function Fm(e,t){if(!e)return e;let n=hr(e);return n?Zb(n.originalUrl)?ut(n.port,n.path,t):n.originalUrl:e}function eP(e,t="/"){return`http://localhost:${e}${t}`}var tP=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function Nm(e){let t=e.match(qb);if(t)return{port:parseInt(t[1],10),sandboxId:t[2],backendPort:t[3]?parseInt(t[3],10):80,path:t[4]||"/"};let n=e.match(Gb);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(tP);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function NM(e){try{let t=Nm(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function KM(e){return wM(e)||Gb.test(e)||tP.test(e)}function BM(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var yr="/web-proxy/";function qM(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${yr}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(We.KORTIX_MASTER,10);return`${ut(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function GM(e){try{let t=new URL(e),n=t.pathname.indexOf(yr);if(n===-1)return null;let s=t.pathname.slice(n+yr.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],i=s[2],a=s[3]||"/";return`${o}://${i}${a}${t.search}${t.hash}`}catch{return null}}function WM(e){try{return new URL(e).pathname.includes(yr)}catch{return e.includes(yr)}}function VM(e){if(!e)return!1;let t=e.trim();return!!(/^https?:\/\/(?!localhost|127\.0\.0\.1)/i.test(t)||/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t))}function HM(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function nP(e){return{health:t=>Um(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>ut(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>Fm(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ie(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Km(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=K_(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=W_(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return s},set model(f){s=f},get agent(){return o},set agent(f){o=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...Fb(m),...Nb(m),...nP(m),...J_(m),...rb(m),...kb(m),files:Ub(c),...Y_(m),get runtime(){return Me(d("runtime").runtimeUrl)}}}function rP(e){return{apps:{list:()=>Zd(e),create:t=>eg(e,t),get:t=>Ms(e,t),update:(...t)=>tg(e,...t),access:{get:(...t)=>og(e,...t),update:(...t)=>ag(e,...t),session:(...t)=>cg(e,...t),agents:t=>ig(e,t)},remove:t=>ng(e,t),token:t=>rg(e,t),authEnv:t=>sg(e,t),artifacts:{register:t=>Os(e,t),uploadArchive:(...t)=>lg(e,...t),finalize:(...t)=>Ds(e,...t)},deployments:{create:(...t)=>ug(e,...t),list:t=>pg(e,t),get:(...t)=>dg(e,...t),logs:(...t)=>gg(e,...t),remove:(...t)=>yg(e,...t)},start:t=>mg(e,t),stop:t=>fg(e,t),rollback:(...t)=>hg(e,...t),machines:{list:t=>_g(e,t),start:(t,n)=>Pg(e,t,n),stop:(t,n)=>Sg(e,t,n),restart:(t,n)=>xg(e,t,n),destroy:(t,n)=>wg(e,t,n)},scale:(...t)=>kg(e,...t),exec:(...t)=>vg(e,...t),volumes:{list:t=>Ag(e,t),create:(...t)=>Rg(e,...t),update:(...t)=>Cg(e,...t),destroy:(...t)=>Tg(e,...t),snapshots:(...t)=>Ig(e,...t),snapshot:(...t)=>Eg(e,...t),restore:(...t)=>Mg(e,...t),fork:(...t)=>Og(e,...t)}}}}function sP(e){return{list:()=>wa(e),invite:(...t)=>Aa(e,...t),update:(...t)=>ka(e,...t),revoke:t=>va(e,t),pendingInvites:()=>Ra(e),resendInvite:(...t)=>Ta(e,...t),revokeInvite:(...t)=>Ca(e,...t),requests:()=>Pa(e),approveRequest:(...t)=>Sa(e,...t),rejectRequest:(...t)=>xa(e,...t),groupGrants:()=>Ia(e),attachGroupGrant:(...t)=>Ea(e,...t),updateGroupGrant:(...t)=>Ma(e,...t),detachGroupGrant:t=>Oa(e,t),resourceGrants:{list:()=>Da(e),create:t=>ja(e,t),remove:t=>La(e,t)}}}function oP(e){return{tokens:{list:()=>Md(e),create:t=>Od(e,t),revoke:t=>Dd(e,t)},setupLinks:{requestSecret:t=>qd(e,t),requestConnector:t=>Gd(e,t)},validateManifest:t=>Qi(e,t),gitToken:()=>Xi(e),agentIdentities:()=>zp(e),secrets:{list:()=>Na(e),upsert:t=>Ka(e,t),setStrategy:(...t)=>Ba(e,...t),broker:(...t)=>qa(e,...t),remove:t=>Ha(e,t),setPersonal:(...t)=>za(e,...t),removePersonal:t=>Ya(e,t),setGitCredential:t=>Va(e,t),listProviderOAuth:()=>Ga(e),startProviderOAuth:(...t)=>rs(e,...t),pollProviderOAuth:(...t)=>ss(e,...t),removeProviderOAuth:t=>Wa(e,t)},access:sP(e)}}function iP(e){return{list:()=>lc(e),listAll:()=>uc(e),reconcile:(...t)=>pc(e,...t),reconcileMember:(...t)=>dc(e,...t),updateCredential:(...t)=>gc(e,...t),revoke:(...t)=>mc(e,...t),activate:(...t)=>fc(e,...t),setDefault:(...t)=>yc(e,...t),rename:(...t)=>hc(e,...t),share:(...t)=>bc(e,...t),addComputer:(...t)=>_c(e,...t),pipedreamConnect:(...t)=>Pc(e,...t),pipedreamFinalize:(...t)=>Sc(e,...t)}}function bo(e){return{catalog:t=>Ut(e,t),tools:()=>cs(e),search:(...t)=>cc(e,...t),describe:(...t)=>ls(e,...t),call:(...t)=>xt(e,...t),callAction:(t,n,r,s)=>xt(e,`${t}.${n}`,r,s),accounts:(...t)=>us(e,...t),uploadAttachment:(...t)=>ps(e,...t)}}function Bm(e,t){return{slug:t,run:(r,s,o)=>ys(e,t,r,s,o),call:(r,s,o)=>xt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?ls(e,`${t}.${r}`):(await Ut(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>us(e,t),paginate:(r,s,o)=>Bc(e,t,r,s,o),uploadAttachment:(r,s)=>ps(e,r,{...s,connector:t})}}var zM=100,aP=0,YM=new Set(["attachment_size_mismatch","attachment_failed"]),cP=()=>new x("Attachment expired. Attach the file again.",{code:"attachment_expired"});function qm(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function JM(e,t,n){let r,s=0,o,i=()=>{o=void 0,!(!t()||e.item.status!=="uploading"||r===void 0)&&(e.item={...e.item,receivedBytes:r},r=void 0,s=Date.now(),n())},a=p=>Math.floor(p*100/e.item.size),c=()=>{o&&clearTimeout(o),o=void 0};return{onProgress:p=>{if(!t()||a(p)===a(e.item.receivedBytes)||(r=p,o))return;let d=s+zM-Date.now();if(d<=0)return i();o=setTimeout(i,d),typeof o=="object"&&"unref"in o&&o.unref()},onProcessing:()=>{c(),r=void 0,t()&&(e.item={...e.item,status:"processing",receivedBytes:e.item.size},n())},clear:c}}function Gm(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(h=>!h.handedOff);function g(h,S){h.removalDeleted||(h.removalDeleted=!0,Ft(e,S).catch(()=>{}))}function m(){c&&clearTimeout(c);let h=d().map(({item:P})=>P);(h.length!==p.attachments.length||h.some((P,k)=>P!==p.attachments[k]))&&(p={attachments:h});let S=Math.min(...h.filter(P=>P.status==="ready").map(P=>Date.parse(P.attachment.expires_at)));Number.isFinite(S)&&!a&&(c=setTimeout(()=>{for(let P of d())P.item.status==="ready"&&Date.parse(P.item.attachment.expires_at)<=Date.now()&&(P.item={...P.item,status:"error",error:cP()});m()},Math.min(2147483647,Math.max(0,S-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let P of s)P();for(let P of[...o])P()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function _(h){f();let S=d();if(S.length+h.length>20)throw new Error("A message can contain up to 20 attachments");if(h.some(k=>!Number.isSafeInteger(k)||k<=0||k>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(S.reduce((k,C)=>k+C.item.size,0)+h.reduce((k,C)=>k+C,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function y(h,S,P){let k=++h.generation,C=new AbortController;h.abort=C,h.item={...h.item,status:"uploading",error:void 0};let j=()=>(!a||h.handedOff===!0)&&r.get(h.item.id)===h&&h.generation===k,w=JM(h,j,m);jn(e,S,{resume:h.upload,signal:C.signal,onUpload:D=>{h.upload=D,h.removed&&(C.abort(),g(h,D.attachment_id))},...w}).then(D=>{j()&&(h.item={...h.item,status:"ready",attachment:qm(D),receivedBytes:D.size})}).catch(D=>{D instanceof x&&YM.has(D.code??"")&&(h.upload=void 0),j()&&(h.item={...h.item,status:D instanceof x&&D.code==="ABORTED"?"aborted":"error",error:D instanceof Error?D:new Error(String(D))})}).finally(()=>{w.clear(),h.abort===C&&(h.abort=void 0),P()})}function v(){for(let h of r.values()){if(i>=n)break;if(h.item.status!=="pending"||!h.item.file||a&&!h.handedOff)continue;let S=h.item.file;i++,y(h,S,()=>{i--,m(),v()})}m()}function R(h){_(h.map(P=>P.size));let S=h.map(P=>{let k=`attachment-${++aP}`;return r.set(k,{generation:0,item:{id:k,file:P,filename:P.name,mime:P.type||"application/octet-stream",size:P.size,status:"pending",receivedBytes:0}}),k});return m(),v(),S}function T(h){let S=h.map(({attachment:k,file:C})=>{try{return{attachment:qm(k),file:C}}catch{return}});_(S.flatMap(k=>k?[k.attachment.size]:[]));let P=S.map(k=>{if(!k)return;let C=`attachment-${++aP}`,{attachment:j,file:w}=k;return r.set(C,{generation:0,item:{id:C,...w?{file:w}:{},filename:j.filename,mime:j.mime,size:j.size,status:"ready",receivedBytes:j.size,attachment:j}}),C});return m(),P}function b(h){let S=r.get(h);!S||S.item.status==="ready"||(S.generation++,S.abort?.abort(),S.item={...S.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function M(h,{signal:S}={}){let P=[...h];return new Promise((k,C)=>{let j=()=>{o.delete(xe),S?.removeEventListener("abort",D)},w=N=>{j(),C(N)},D=()=>w(Ae()),xe=()=>{let N=!1;for(let G of P){let B=r.get(G);if(!B)return w(new Error("Attachment was removed before it was sent"));if(a&&!B.handedOff)return w(new Error("Attachment controller is disposed"));if(B.item.status==="error"||B.item.status==="aborted")return w(B.item.error??new Error("Attachment upload failed"));B.item.status!=="ready"&&(N=!0)}if(N)return;let z;try{z=P.map(G=>{let B=qm(r.get(G).item.attachment);return{type:"file",attachment_id:B.attachment_id,filename:B.filename,mime:B.mime}})}catch(G){return w(G instanceof Error?G:new Error(String(G)))}j(),k(z)};if(S?.aborted)return D();o.add(xe),S?.addEventListener("abort",D,{once:!0}),xe()})}return{add:h=>R([h])[0],addMany:R,restore:T,retry(h){let S=r.get(h);if(S?.handedOff||f(),!(!S||S.item.status==="ready"||S.item.status==="uploading"||S.item.status==="processing"||S.item.status==="pending")){if(!S.item.file||S.upload&&Date.parse(S.upload.expires_at)<=Date.now())throw cP();S.item={...S.item,status:"pending",error:void 0},v()}},async remove(h){let S=r.get(h);if(!S)return;S.removed=!0,S.generation++,r.delete(h);let P=S.upload?.attachment_id??S.item.attachment?.attachment_id;P&&S.abort?.abort(),m(),v(),P&&g(S,P)},abort:b,submit(h){if(!a){for(let S of h){let P=r.get(S);P&&(P.handedOff=!0)}m()}},reclaim(h){if(!a){for(let S of h){let P=r.get(S);P&&(P.handedOff=!1)}m()}},whenReady:M,forget(h=d().map(S=>S.item.id)){for(let S of h){let P=r.get(S);P&&(P.generation++,P.abort?.abort(),r.delete(S))}m(),v()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let h of r.values()){if(h.handedOff)continue;h.generation++,h.abort?.abort();let S=h.upload?.attachment_id??h.item.attachment?.attachment_id;S&&e&&Ft(e,S).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(h){return s.add(h),()=>{s.delete(h)}}}}function lP(e){return{attachments:{upload:(...t)=>jn(e,...t),delete:(...t)=>Ft(e,...t),createController:t=>Gm(e,t)},get:t=>St(e,t),detail:()=>vn(e),skills:{create:(...t)=>ia(e,...t)},audit:t=>$d(e,t),update:t=>Cn(e,t),archive:()=>Tn(e),llmCatalog:()=>An(e),modelPicker:()=>Rn(e),modelAccess:()=>Hn(e),setModelAccess:t=>zn(e,t),sandboxHealth:()=>En(e),onboardingComplete:(...t)=>oa(e,...t)}}function uP(e){return{sessions:{list:t=>kt(e,t),listPage:t=>Cl(e,t),create:t=>vt(e,t),ensureWarm:()=>Fl(e),claimWarm:t=>Nl(e,t)},review:{list:t=>gd(e,t),summary:()=>md(e),get:t=>fd(e,t),submit:t=>yd(e,t),act:(...t)=>hd(e,...t),bulkAct:t=>_d(e,t)},approvals:{list:t=>$a(e,t),resolve:(...t)=>Fa(e,...t),sessionsNeedingInput:t=>Ua(e,t)}}}function pP(e){return{files:{list:t=>el(e,t),listDirectory:t=>tl(e,t),read:(t,n)=>rl(e,t,n),search:(...t)=>nl(e,...t),archive:(...t)=>sl(e,...t),archiveRequest:(...t)=>ol(e,...t),history:(...t)=>dl(e,...t)},git:{commits:()=>ll(e),commit:t=>ul(e,t),commitDiff:t=>pl(e,t),branches:()=>cl(e),versionDiff:(...t)=>gl(e,...t),inviteCollaborator:(...t)=>Ji(e,...t)},changeRequests:{list:(...t)=>ml(e,...t),get:t=>fl(e,t),update:(...t)=>kl(e,...t),diff:t=>yl(e,t),mergePreview:t=>hl(e,t),open:(...t)=>_l(e,...t),merge:(...t)=>bl(e,...t),close:(...t)=>Pl(e,...t),reopen:(...t)=>Sl(e,...t),requestChanges:(...t)=>xl(e,...t)},...uP(e)}}function dP(e){return{policies:{list:()=>qc(e),set:(...t)=>Gc(e,...t)},reminders:{list:()=>Ad(e),updateMany:(...t)=>kd(e,...t),removeMany:(...t)=>vd(e,...t)},triggers:{list:()=>cu(e),eventApps:()=>_u(e),eventTypes:(...t)=>hu(e,...t),create:(...t)=>lu(e,...t),update:(...t)=>uu(e,...t),remove:(...t)=>pu(e,...t),fire:((t,n)=>gu(e,t,n)),runs:(...t)=>mu(e,...t),projectRuns:(...t)=>fu(e,...t),replay:(...t)=>yu(e,...t),setActivation:(...t)=>du(e,...t)},...pP(e)}}function gP(e,t){return{connectors:{...bo(e),list:()=>xc(e),config:(...n)=>Tc(e,...n),create:(...n)=>Mc(e,...n),remove:(...n)=>Dc(e,...n),sync:()=>wc(e),auth:{discover:(...n)=>Oc(e,...n)},setName:(...n)=>Ic(e,...n),setCredentialMode:(...n)=>kc(e,...n),setAuthorizationStrategy:(...n)=>vc(e,...n),setCredential:(...n)=>Fc(e,...n),deleteCredential:(...n)=>Nc(e,...n),setSensitive:(...n)=>Ac(e,...n),connections:t,policies:{get:(...n)=>Rc(e,...n),set:(...n)=>Cc(e,...n)},pipedream:{listApps:(...n)=>jc(e,...n),listSections:(...n)=>Lc(e,...n),connect:(...n)=>Ec(e,...n),finalize:(...n)=>Kc(e,...n)},discover:{list:(...n)=>ds(e,...n),sections:(...n)=>$c(e,...n),detail:(...n)=>gs(e,...n)}},...dP(e)}}function mP(e){return{gateway:{logs:t=>Pp(e,t),log:t=>Sp(e,t),overview:t=>xp(e,t),series:t=>wp(e,t),breakdown:t=>kp(e,t),sessions:t=>vp(e,t),errors:t=>Ap(e,t),budgets:()=>Rp(e),setBudget:t=>Cp(e,t),deleteBudget:t=>Tp(e,t),keys:()=>Ip(e),createKey:t=>Ep(e,t),revokeKey:t=>Mp(e,t),routing:{get:()=>yp(e),set:t=>hp(e,t),reset:()=>_p(e),preview:t=>bp(e,t)},playground:(t,n,r)=>Op(e,t,n,r)}}}function fP(e){return{modelDefaults:{get:()=>xu(e),set:t=>wu(e,t),clear:t=>ku(e,t)},setDefaultAgent:t=>Ru(e,t),sandbox:{list:()=>Zc(e),snapshots:()=>Vc(e),rebuildSnapshot:t=>Hc(e,t),fixWithAgent:()=>zc(e),createTemplate:t=>Yc(e,t),updateTemplate:(...t)=>Jc(e,...t),removeTemplate:t=>Qc(e,t),buildTemplate:t=>Xc(e,t),setProvider:t=>sa(e,t)},setAgentScope:(...t)=>vu(e,...t)}}function yP(e){return{channels:{slack:{installation:()=>tp(e),connect:t=>np(e,t),mode:()=>rp(e),completeInstall:t=>sp(e,t),manifest:()=>ip(e),disconnect:()=>ap(e),getFile:t=>cp(e,t),uploadFile:t=>lp(e,t)},teams:{completeInstall:t=>op(e,t)},email:{installation:t=>pp(e,t),mode:()=>dp(e),connect:t=>gp(e,t),disconnect:t=>mp(e,t),updatePolicy:(...t)=>fp(e,...t)}},updateFeatureFlag:(...t)=>na(e,...t),updateExperimentalFeature:(...t)=>ra(e,...t),...fP(e)}}var QM=["screen","actions","audio"],XM=["password_managers","messaging","banking"],ZM={localHours:8760,remoteDays:3650},eO=[500,1e3,2e3,5e3,1e4],tO=[720,1080,1440,2160],nO={intervalMs:2e3,maxHeight:1440},rO=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function sO(e){let t=e.trim().toLowerCase();if(!t)return null;let n;try{n=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{return null}return n=n.replace(/^www\./,"").replace(/\.$/,""),rO.test(n)?n:null}function oO(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||/\s/.test(t)&&!t.toLowerCase().endsWith(".exe")?null:t}function iO(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var X=e=>`/accounts/${e}/capture`;function Je(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}var hP=e=>Je({q:e.q,kinds:e.kinds?.join(","),app:e.app,limit:e.limit,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,scope:e.scope}),Wm=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function Vm(e,t={}){return u(await l.get(`${X(e)}/devices${Je({user_id:t.userId,scope:t.scope})}`))}async function Hm(e,t){return u(await l.delete(`${X(e)}/devices/${t}`))}async function zm(e,t,n){return u(await l.put(`${X(e)}/devices/${t}/link`,{user_id:n}))}async function Ym(e){return u(await l.get(`${X(e)}/enrollment-tokens`))}async function Jm(e,t){return u(await l.post(`${X(e)}/enrollment-tokens`,t))}async function Qm(e,t){return u(await l.delete(`${X(e)}/enrollment-tokens/${t}`))}async function Xm(e,t={}){return u(await l.get(`${X(e)}/enrollments${Je({status:t.status})}`))}async function Zm(e,t,n){return u(await l.post(`${X(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function ef(e,t){return u(await l.post(`${X(e)}/enrollments/${t}/deny`,{}))}async function tf(e){return u(await l.get(`${X(e)}/policy`))}async function nf(e,t){return u(await l.put(`${X(e)}/policy`,{policy:t}))}async function rf(e,t={}){return u(await l.get(`${X(e)}/timeline${Je(Wm(t))}`))}async function sf(e,t={}){return u(await l.get(`${X(e)}/timeline/items${Je(Wm(t))}`))}async function of(e,t={}){return u(await l.get(`${X(e)}/days${Je({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function af(e,t){return u(await l.get(`${X(e)}/search${hP(t)}`))}async function cf(e,t,n={}){return u(await l.get(`${X(e)}/frames/${t}${Je({user_id:n.userId})}`))}async function lf(e,t,n={}){return u(await l.get(`${X(e)}/chunks/${t}/media${Je({user_id:n.userId})}`))}async function uf(e,t,n){return u(await l.get(`${X(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function pf(e){return u(await l.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function df(e,t){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function gf(e){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function mf(e){return u(await l.get(X(e)))}async function ff(e,t){return u(await l.patch(X(e),{enabled:t}))}async function yf(e){return u(await l.get(`/capture/me/search${hP(e)}`))}async function hf(e={}){return u(await l.get(`/capture/me/timeline${Je(Wm(e))}`))}async function _f(e){return u(await l.get(`/capture/me/frames/${e}`))}function cO(e){return{workspace:{get:()=>mf(e),setEnabled:t=>ff(e,t)},devices:{list:t=>Vm(e,t),revoke:t=>Hm(e,t),link:(t,n)=>zm(e,t,n),assetUrl:(t,n)=>uf(e,t,n)},enrollment:{tokens:{list:()=>Ym(e),create:t=>Jm(e,t),revoke:t=>Qm(e,t)},list:t=>Xm(e,t),approve:(t,n)=>Zm(e,t,n),deny:t=>ef(e,t)},policy:{get:()=>tf(e),set:t=>nf(e,t)},timeline:{get:t=>rf(e,t),items:t=>sf(e,t),days:t=>of(e,t)},search:t=>af(e,t),frame:(t,n)=>cf(e,t,n),media:(t,n)=>lf(e,t,n)}}var _P={account:e=>cO(e),deviceGrant:pf,approveDevice:df,denyDevice:gf,me:{search:yf,timeline:hf,frame:_f}};async function bf(e){let t=e?.fetch??I().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??I().backendUrl,r=await t(`${At(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new x(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var lO=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function uO(e,t){let n=o=>{let i=lO.exec(o.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),s=n(t);if(!r||!s)return null;for(let o=0;o<3;o++)if(r[o]!==s[o])return r[o]<s[o]?-1:1;return 0}function pO(){return ct()}var bP=null,PP=!1;function dO(e){let t=bP;bP=e,!(PP||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(PP=!0,console.warn("[kortix] createKortix() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedKortix() from @kortix/sdk/server.")))}function SP(e,t){t?.global!==!1&&dO(e),qr(e,t);let n=N_(e),{auth:r,accounts:s,iam:o,accountInvites:i}=j_(),{billing:a,sandboxShares:c}=M_(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=E_();function _(y){let v=iP(y);return{...lP(y),...rP(y),...oP(y),...gP(y,v),...mP(y),...yP(y),connector:R=>Bm(y,R),session:R=>Km(y,R,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:bo(),connector:y=>Bm(void 0,y),project:_,session:(y,v)=>Km(y,v,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,capture:_P,notifications:{registerDeviceToken:jg,unregisterDeviceToken:Lg,list:$g,markRead:Ug,preferences:Fg,updatePreferences:Ng,webPushPublicKey:Kg,registerWebPushSubscription:Bg,unregisterWebPushSubscription:qg},mobileClientPolicy:bf,validateToken:zi,runtime:pO}}function xP(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<16;r++)t[r]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(r=>r.toString(16).padStart(2,"0"));return`${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n.slice(10).join("")}`}function wP(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function an(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function kP(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function vP(e){if(an(e).length>0)return{state:e};let t=e.pending[0];if(!t)return{state:e};let n={...t,attempts:t.attempts+1};return{state:{...e,pending:[n,...e.pending.slice(1)],inFlightId:n.id,inFlightIds:[n.id]},claimed:n}}function AP(e){let t=an(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function RP(e,t){let n=an(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function CP(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function TP(e,t){return an(e).includes(t)?e:e.pending.some(n=>n.id===t)?{...e,pending:e.pending.filter(n=>n.id!==t)}:e.failed.some(n=>n.id===t)?{...e,failed:e.failed.filter(n=>n.id!==t)}:e}function IP(e,t,n){return an(e).includes(t)||!e.pending.some(r=>r.id===t)?e:{...e,pending:e.pending.map(r=>r.id===t?{...r,text:n}:r)}}function EP(e,t,n){let r=an(e);if(r.includes(t))return e;let s=e.pending.findIndex(p=>p.id===t);if(s===-1)return e;let o=r.length,i=Math.min(Math.max(n,o),e.pending.length-1);if(i===s)return e;let a=[...e.pending],[c]=a.splice(s,1);return a.splice(i,0,c),{...e,pending:a}}var Pf={thinking:!1,toolDetails:!0,assistantMetadata:!0};function gO(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function mO(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=t%60;return`${n}m ${r.toFixed(0)}s`}function fO(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
21
+ `)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*nE(e,t,n){let r=e.eventTransport??Dm(e.fetch??globalThis.fetch),o=n.signal??new AbortController().signal,s=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!o.aborted;a++)try{let l=new Headers(n.headers);i!==void 0&&l.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:l,signal:o}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(s=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(l){if(n.onSseError?.(l),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(s*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function gr(e){let t=o=>(s,i)=>tE(e,ZI(e.baseUrl,o,s,i)),n=o=>s=>t(o)(void 0,s);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(o={})=>({stream:nE(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,o)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var mb=200;async function rE(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function at(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new S(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function fb(e){let t=e.runtimeUrl.replace(/\/$/,""),n=gr({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let o=encodeURIComponent(r.conversationId??e.rootId),s=async(l,p)=>{let d=new URLSearchParams;l!==void 0&&d.set("limit",String(l)),p&&d.set("before",p);let g=`/messages/${o}${d.size?`?${d}`:""}`,m=y=>e.fetch(new Request(`${t}${y}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new S(`Reading the session transcript failed: ${await rE(f)}`,{status:f.status,response:f});let _=await f.json();return{messages:_.messages??[],hasMore:_.has_more===!0}},i=await s(r.limit===void 0?void 0:Math.min(r.limit,mb),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await s(Math.min(r.limit-a.length,mb),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,o,s]=await Promise.all([n.session.status().then(i=>at(i,"Reading the session status failed")),n.permission.list().then(i=>at(i,"Reading permission requests failed")),n.question.list().then(i=>at(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{at(await n.permission.reply({requestID:r,reply:o,...s!==void 0?{message:s}:{}}),"Answering the permission request failed")},answerQuestion:async(r,o)=>{if(o===null){at(await n.question.reject({requestID:r}),"Dismissing the question failed");return}at(await n.question.reply({requestID:r,answers:o}),"Answering the question failed")},compact:async r=>{let o=r;if(!o){let a=await n.global.config.get().then(d=>d.error===void 0?d.data:null),l=typeof a?.model=="string"?a.model:"",p=l.indexOf("/");p>0&&p<l.length-1&&(o={providerID:l.slice(0,p),modelID:l.slice(p+1)})}if(!o)throw new S("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});let i=at(await n.session.status(),"Reading the session status failed")?.[e.rootId];if(i&&i.type!=="idle")throw new S("This session is busy. Wait for the current turn to finish, then run compact again.",{code:"SESSION_BUSY",status:409});return at(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function yb(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return fb({runtimeUrl:r,rootId:n,fetch:j})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,o)=>(await t()).answerPermission(n,r,o),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function hb(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await du(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Xt=BigInt(4096),Ve=BigInt(0xffffffffffff),_b=Ve+BigInt(1),oE=_b/BigInt(2),ct=BigInt(3600*1e3)*Xt,ms=120*1e3,bb=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,sE=/^msg_([0-9a-f]{12})/,Pb="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Tt(e){let t=sE.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Zt(e){return BigInt(Math.trunc(e))*Xt&Ve}function It(e,t){let n=e-t&Ve;return n>=oE&&(n-=_b),n}function Lm(e){let t=null;for(let n of e)n!=null&&(t===null||It(n,t)>BigInt(0))&&(t=n);return t}function Sb(e,t){let n=Tt(e);return n===null?!1:It(n,Zt(t))>ct}function xb(e,t){let n=t===void 0?null:Zt(t);return wb(e,r=>n===null||It(r,n)<=ct)}function wb(e,t){let n=[];for(let r of e){let o=Tt(r);o!==null&&t(o)&&n.push(o)}return Lm(n)}function iE(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Pb[n%62])}return e}function jm(e){let t=e.random,n=Zt(e.nowMs-(e.backdateMs??ms)),r=e.newestKnownTime??null;if(r!==null){let s=It(r,n);s>=BigInt(0)&&s<=ct&&(n=r+BigInt(1)&Ve)}let o="";if(t)for(let s=0;s<14;s++)o+=Pb[Math.min(61,Math.floor(t()*62))];else o=iE();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function fs(e={}){let t=e.nowMs??Date.now(),n=Zt(t-ms),r=wb(e.after??[],o=>{let s=It(o,n);return s>=BigInt(0)&&s<=ct});return jm({nowMs:t,newestKnownTime:r}).id}function kb(e){return{scope:()=>uu(e.projectId,e.sessionId),providerSecretPool:{list:()=>lc(e.projectId,e.sessionId),get:t=>cc(e.projectId,e.sessionId,t),set:(t,n)=>uc(e.projectId,e.sessionId,t,n)},rescope:t=>pu(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,o=n?.agent??e.agent,s=r&&o?{}:await e.persistedPromptDefaults(),i=r??s.model,a=o??s.agent,l=fs(),p=await zn(e.projectId,e.sessionId,{clientMessageId:l,messageId:l,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new S("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var vb=async function*(e){let t=C().eventStreamTransport;if(!t){yield*Dm(((o,s)=>j(o,s,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await jt(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function ze(){let e=lb();return e||(C().billingEnabled??!1?"":c_())}async function $m(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Um(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function Fm(e){let t=Um(e),n=await j(`${t}/env`);if(!n.ok)throw new Error(await $m(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Nm(e,t,n){let r=Um(e),o=await j(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await $m(o,"Failed to save secret"))}async function Bm(e,t){let n=Um(e),r=await j(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await $m(r,"Failed to delete secret"))}var Ab={list:Fm,set:Nm,delete:Bm};async function Rb(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await j(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),s=await o.json();if(!o.ok)throw new Error(s?.error||s?.message||`Request failed with ${o.status}`);return s}async function ys(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function mr(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return le(e)}async function qm(e){let t=mr(e),n=await j(`${t}/kortix/pty`);if(!n.ok)throw new Error(await ys(n,"Failed to list terminals"));return n.json()}async function Gm(e,t){let n=mr(e),r=await j(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await ys(r,"Failed to create terminal"));return r.json()}async function Wm(e,t,n){let r=mr(e),o=await j(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await ys(o,"Failed to update terminal"));return o.json()}async function Hm(e,t){let n=mr(e),r=await j(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await ys(r,"Failed to remove terminal"))}async function Vm(e,t,n){let r=mr(t),s=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),le(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await Ft();a&&i.set("token",a),n?.wake&&i.set("wake","1");let l=i.toString();return l?`${s}${s.includes("?")?"&":"?"}${l}`:s}function Cb(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var lt="\x1B",Tb="\x07",aE="\0",Km=`(?:${Tb}|${lt}\\\\)`,cE=[new RegExp(`${lt}\\]697;[^${Tb}${lt}]*${Km}`,"g"),new RegExp(`${aE}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${lt}\\][0-9]+;rgb:[0-9a-fA-F/]+${Km}`,"g"),new RegExp(`${lt}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Km}`,"g"),new RegExp(`${lt}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${lt}\\[\\d+;\\d+R`,"g"),new RegExp(`${lt}\\[\\?[0-9;]*c`,"g")];function Ib(e){let t=e;for(let n of cE)t=t.replace(n,"");return t}var Eb={list:qm,create:Gm,update:Wm,remove:Hm,webSocketUrl:Vm};async function O(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await j(`${o}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await s.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!s.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${s.status}`);return a}async function lE(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return O(e,`/kortix/tasks${r}`)}async function uE(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function pE(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function dE(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function gE(e,t){return O(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function mE(e,t,n){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function fE(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function yE(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function hE(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function _E(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return O(e,`/kortix/tickets${n}`)}async function bE(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function PE(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function SE(e,t){return O(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function xE(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function wE(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function kE(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function vE(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function AE(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function RE(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function CE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function TE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function IE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function EE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function ME(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function OE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function DE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function LE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function jE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function $E(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function UE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function FE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function NE(e,t,n=200){return O(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function BE(e){return O(e,"/kortix/projects")}async function KE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function qE(e,t){return O(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function GE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function WE(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function HE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function VE(e,t,n="all"){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function zE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function YE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function JE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function QE(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function XE(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function ZE(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function eM(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function tM(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function nM(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function rM(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function oM(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function sM(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var iM=1e4,aM={retryOnAuthError:!1};function en(e,t,n){return O(e,t,{signal:AbortSignal.timeout(iM),...n},aM)}async function cM(e,t=!1){return(await en(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function lM(e){return(await en(e,"/kortix/services/templates")).templates??[]}async function uM(e,t){return(await en(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function pM(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return en(e,o,{method:r?"DELETE":"POST"})}async function dM(e,t){return en(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function gM(e,t){return en(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Ye=new Map,mM=256,tn=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ut(){let e=ze();if(!e)throw new tn;return Me(e)}function Me(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=Ye.get(e);if(t)return Ye.delete(e),Ye.set(e,t),t;if(!Zr())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=gr({baseUrl:e,fetch:j,eventTransport:vb});return Ye.set(e,n),Ye.size>mM&&Ye.delete(Ye.keys().next().value),n}function fM(e){Ye.delete(e)}function yM(){Ye.clear()}var hs=new Map;function hM(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=hs.get(e);if(t)return t;let n=gr({baseUrl:e,fetch});return hs.set(e,n),n}function _M(e){hs.delete(e)}function bM(){hs.clear()}async function PM(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n?.error||n?.message||t||e.statusText||`HTTP ${e.status}`}catch{return t||e.statusText||`HTTP ${e.status}`}}async function SM(e){let t=ze();if(!t)throw new S("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await j(`${t}${n}`,{method:"POST"}),o=r.headers.get("content-type")??"",s=/^application\/([\w.+-]+\+)?json\b/i.test(o.trim());if(!r.ok)throw new S(`System reload failed (${r.status}): ${await PM(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!s)throw new S(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(l){throw new S(`System reload returned malformed JSON from ${n}: ${l instanceof Error?l.message:String(l)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var Mb="frontend";function _s(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Mb}] ${t}`,...n?[n]:[]);try{ut().app.log({service:Mb,level:e,message:t,extra:n})}catch{}}var Je={debug:(e,t)=>_s("debug",e,t),info:(e,t)=>_s("info",e,t),warn:(e,t)=>_s("warn",e,t),error:(e,t)=>_s("error",e,t)};var xM=16,wM=8,Ob=6e4,kM=250,vM=1e3,AM=3e4,RM=5,CM=.5,TM=3e3,IM=3e4,Db=2e4,EM=2e3,Lb=8;function MM(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function OM(e,t){if(!e||e.type!==t.type)return;if(t.type==="message.part.delta"){let s=e.properties,i=t.properties;if(s.partID!==i.partID||s.field!==i.field||s.messageID!==i.messageID||s.sessionID!==i.sessionID)return}else if(t.type==="log.block.delta"){let s=e.properties,i=t.properties;if(typeof s.delta!="string"||typeof i.delta!="string"||s.thread_id!==i.thread_id||s.message_id!==i.message_id||s.block_id!==i.block_id)return}else return;let n=e.properties,r=t.properties,o=e.coalesced??[e];return o.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:o}}function jb(e,t){let n=[],r,o=0,s=new Map,i=()=>{if(r&&e.clearTimeout(r),r=void 0,n.length===0)return;let l=n;n=[],s.clear(),o=e.now();for(let p of l)p&&t(p.event)},a=()=>{if(r)return;let l=e.now()-o;r=e.setTimeout(i,Math.max(0,xM-l))};return{push(l){let p=OM(n[n.length-1]?.event,l);if(p)n[n.length-1]={type:p.type,event:p};else{let d=MM(l);if(d){let g=s.get(d);g!==void 0&&(n[g]=void 0),s.set(d,n.length)}n.push({type:l.type,event:l})}a()},flush:i,clearTimer:()=>{r&&e.clearTimeout(r)}}}function $b(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}function zm(e,t,...n){for(let r of e){let o=t(r);if(o)try{o(...n)}catch(s){console.warn("[opencode-events] subscriber handler threw, skipping",s)}}}async function DM(e,t,n,r){return new Promise((o,s)=>{let i=!1,a=t.setTimeout(()=>{i||(i=!0,Je.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:n}),r.abort(),s(new Error(`SSE connect timed out after ${n}ms`)))},n);e.global.event({signal:r.signal,sseDefaultRetryDelay:TM,sseMaxRetryDelay:IM,sseMaxRetryAttempts:1}).then(l=>{i||(i=!0,t.clearTimeout(a),o(l))},l=>{i||(i=!0,t.clearTimeout(a),s(l))})})}async function LM(e,t,n,r,o){let s=!1,i=t.now(),a=e[Symbol.asyncIterator]();for(;!n.aborted;){let l=a.next().then(f=>({kind:"next",result:f}),f=>({kind:"error",error:f})),p=$b(n),d=await Promise.race([l,p.promise.then(()=>({kind:"aborted"}))]);if(p.cleanup(),d.kind==="aborted")break;if(d.kind==="error")throw d.error;if(d.result.done)break;o();let g=d.result.value,m=g&&typeof g=="object"&&"payload"in g?g.payload:g;m?.type&&(m.type!=="server.connected"&&(s=!0),r.push(m),!(t.now()-i<wM)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return s}function Ub(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<EM)}function Fb(e,t,n){Je.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),zm(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function Nb(e,t,n){let r=t?kM:Math.min(vM*2**Math.min(e-1,RM),AM);return Math.round(r*(1+CM*(n.random?.()??0)))}function Bb(e,t,n){return new Promise(r=>{let o=e.setTimeout(r,n),s=()=>{e.clearTimeout(o),r()};t.addEventListener("abort",s,{once:!0})})}async function Kb(e){let{client:t,t:n,connectTimeoutMs:r,heartbeatTimeoutMs:o,outerSignal:s,retryCount:i,setConnectionState:a,onConnected:l,coalescer:p}=e,d=!1,g=!1,m,f=null,_=new AbortController;a("connecting");let y=$b(s);y.promise.then(()=>_.abort());try{let{stream:k}=await DM(t,n,r,_);l();let R=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{Je.warn("SSE heartbeat timeout, forcing reconnect"),_.abort()},o)};R(),d=await LM(k,n,_.signal,p,()=>{a("open"),R()}),g=d}catch(k){if(f=k,s.aborted)return{streamHadWork:d,stableConnection:g,error:f};let R=String(k),I=Lt(k)||Lt(k?.cause);if(Je.error("SSE event stream error",{error:R,retryCount:i,isAuthError:I}),I)try{mo(),await go(),Je.info("SSE: refreshed auth token after auth error")}catch(b){Je.error("SSE: failed to refresh auth token",{error:String(b)})}}finally{n.clearTimeout(m),_.abort(),y.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function qb(e){return{type:"heartbeat-gap",gapMs:e}}function Gb(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var jM={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},$M=5e3,UM=1e4,FM=4,fr=new WeakMap;function NM(e,t,n){let r=t.timers??jM,o=t.connectTimeoutMs??Db,s=t.heartbeatTimeoutMs??Ob,i=t.maxConsecutiveHardFailures??Lb,a=new AbortController,l=(k,...R)=>zm(n,k,...R),p=null,d=!1,g=k=>{p!==k&&(p=k,k&&l(R=>R.onConnectionChange,k))},m=r.now(),f=null,_=jb(r,k=>{m=r.now(),l(R=>R.onEvent,k)}),y={client:e,t:r,connectTimeoutMs:o,heartbeatTimeoutMs:s,outerSignal:a.signal,setConnectionState:g,onConnected:()=>{if(f){let k=r.now()-f.lastActivityAt,R=f.eventful;f=null,(R||k>$M)&&l(I=>I.onGapRehydrate,k)}m=r.now()},coalescer:_};return(async()=>{let k=0,R=0,I=0;for(;!a.signal.aborted;){let b=r.now(),M=await Kb({...y,retryCount:k});if(a.signal.aborted)break;let h=M.error,{streamHadWork:x,stableConnection:P}=M,v=r.now()-b;if(R=Ub(x,h,v)?R+1:0,R>=i){Fb(n,R,h),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||x},I=P&&v<UM?I+1:0;let w=P&&I<=FM;w?k=0:(k++,k>1&&Je.warn("SSE event stream reconnecting",{retryCount:k})),await Bb(r,a.signal,Nb(k,w,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),_.clearTimer()}}}function bs(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?Me(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o},l=fr.get(i);if(l?.isParked()&&(fr.delete(i),l=void 0),!l)l=NM(i,e,new Set([a])),fr.set(i,l);else{l.subscribers.add(a);let f=l.connectionState();f&&o?.(f)}let p=l,d=!1,g=()=>{d||(d=!0,s&&s.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),fr.get(i)===p&&fr.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function Wb(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Me(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return bs({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Vb(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new S(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Qm(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function ue(e){let t=(e??ze()).trim();if(!t)throw new tn;return t}async function _r(e,t){let n=await j(`${ue(t)}${e}`);if(!n.ok)throw new S(await Qm(n),{status:n.status,response:n});return n.json()}async function Xm(e,t,n,r,o){let s=await j(`${ue(o)}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new S(`${r} failed (${s.status}): ${await Qm(s)}`,{status:s.status,response:s});return s.json()}var Ss=["/workspace","/tmp","/home","/opt"],BM=Ss.filter(e=>e!=="/workspace");function Zm(e){return Ss.some(t=>e===t||e.startsWith(`${t}/`))}function on(e){return Zm(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function pt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(BM.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var ef=pt;async function sn(e,t){let n=ue(t),r=pt(e)||".";return(await _r(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function an(e,t){let n=pt(e);return _r(`/file/content?path=${encodeURIComponent(n)}`,t)}async function KM(e,t,n){let r=ue(n),o=pt(e),s=await j(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new S(await Qm(s),{status:s.status,response:s});if((s.headers.get("content-type")||"").includes("text/html"))throw new S("File could not be loaded (raw byte route unavailable)",{status:s.status,response:s,code:"INVALID_CONTENT_TYPE"});let i=await s.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var qM=8,Ps=0,zb=[];async function GM(){if(Ps<qM){Ps++;return}await new Promise(e=>zb.push(e)),Ps++}function WM(){Ps--,zb.shift()?.()}function Yb(e,t){let n=ue(t);return Un(`${n}/file/raw?path=${encodeURIComponent(pt(e))}`)}async function cn(e,t){await GM();try{let n=ue(t);try{return await KM(e,void 0,n)}catch{}let r=await an(e,n);if(r.encoding==="base64"&&r.content){let o=Uint8Array.from(atob(r.content),s=>s.charCodeAt(0));return new Blob([o],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{WM()}}async function br(e){return _r("/file/status",ue(e))}async function Pr(e,t,n){let r=ue(n),o=new URLSearchParams({query:e});return t?.type&&o.set("type",t.type),t?.limit&&o.set("limit",String(t.limit)),_r(`/find/file?${o.toString()}`,r)}async function Sr(e,t){let n=ue(t);return(await _r(`/find?pattern=${encodeURIComponent(e)}`,n)).map(o=>({path:typeof o.path=="string"?o.path:o.path?.text??"",lines:typeof o.lines=="string"?o.lines:o.lines?.text??"",line_number:o.line_number,absolute_offset:o.absolute_offset,submatches:(o.submatches??[]).map(s=>({start:s.start,end:s.end}))}))}var yr=[400,1200],HM=e=>e===408||e===429||e===502||e===503||e===504,Hb=e=>new Promise(t=>setTimeout(t,e));function VM(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Ym=3e4,Jb=15*6e4,zM=256;function nn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Ym;let t=Ym+e/zM;return Math.min(Jb,Math.max(Ym,Math.round(t)))}async function YM(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function hr(e,t){let n;for(let o=0;o<=yr.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,VM(a)||o===yr.length)break;await Hb(yr[o]);continue}if(s.ok)return s.json();let i=await YM(s);if(n=new S(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!HM(s.status)||o===yr.length)throw n;await Hb(yr[o])}if(n instanceof S)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new S(`Upload failed: ${r}`)}var Jm=8*1024*1024;function JM(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new S(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Qb(e,t){try{e?.onProgress?.(t)}catch{}}function Xb(e,t,n){let r=new FormData,o=(t??"").trim();return o&&r.append("path",o.startsWith("/")?o:`/${o}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function QM(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function ln(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=ue(s),l=nn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Jm){let d=await hr(()=>Xb(e,t,p),g=>j(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:l}));return JM(d[0],e.size),Qb(i,{loadedBytes:e.size,totalBytes:e.size}),d}return XM(e,t,p,a,i)}async function XM(e,t,n,r,o){let i=(await hr(()=>Xb(new Blob([],{type:e.type}),t,n),l=>j(`${r}/file/upload`,{method:"POST",body:l},{timeoutMs:nn(0)})))[0]?.path;if(!i)throw new S("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=QM(i);if(!a.name)throw new S(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let l=0;l<e.size;l+=Jm){let p=Math.min(e.size,l+Jm),d=e.slice(l,p,e.type),g=await hr(()=>{let m=new FormData;return a.parent&&m.append("path",a.parent),m.append("filename",a.name),m.append("first",l===0?"true":"false"),m.append("offset",String(l)),m.append("file",d,a.name),m},m=>j(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:nn(d.size)}));if(g.path!==i||g.size!==p)throw new S(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Qb(o,{loadedBytes:p,totalBytes:e.size})}}catch(l){throw await Et(i,r).catch(()=>{}),l}return[{path:i,size:e.size}]}function Zb(e,t,n){let r=ue(n);return hr(()=>{let o=new FormData;return t&&o.append("path",t),o.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),o},o=>j(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:ZM}))}var ZM=Jb;function eO(e,t,n){let r=ue(n),o=nn(t.size);return hr(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>j(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var rn=class extends S{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function xr(e,t){let n=ue(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",l=on(`${a}/${i}`),p=[];try{p=await sn(eP(l),n)}catch(g){if(!(g instanceof S&&g.status===404))throw g}if(p.some(g=>g.name===tP(l)))throw new rn(l);let d=await nP(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function wr(e,t,n){let r=ue(n);return eO(t,await cn(e,r),r)}function tO(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function eP(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function tP(e){return e.slice(e.lastIndexOf("/")+1)}function nO(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function kr(e,t,n){let r=ue(n),o=on(tO(e.trim()));return nP(o,t,r,{overwrite:!0})}async function nP(e,t,n,r){let o=tP(e);if(!o)throw new S(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=eP(e);await un(s,n).catch(()=>{});let i=nO(),a=await ln(t,s,`.${o}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new S(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=on(l);try{await rP(p,e,n,r.overwrite)}catch(g){throw await Et(p,n).catch(()=>{}),!r.overwrite&&g instanceof S&&g.status===409?new rn(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Et(e,t){return Xm("/file","DELETE",{path:e},"Delete",t)}async function un(e,t){return Xm("/file/mkdir","POST",{path:e},"Mkdir",t)}async function vr(e,t,n){return rP(e,t,ue(n),!0)}async function rP(e,t,n,r){return Xm("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function tf(){return Vb(await ut().project.current())}async function xs(){return Vb(await ut().global.health())}async function nf(){try{return(await xs()).healthy===!0}catch{return!1}}var oP={list:sn,read:an,readBlob:cn,status:br,findFiles:Pr,findText:Sr,upload:ln,write:kr,create:xr,copy:wr,remove:Et,mkdir:un,rename:vr,currentProject:tf,health:xs,isReachable:nf,toDaemonPath:pt,toSandboxAbsolutePath:on,toWorkspaceRelative:ef};function sP(e){return{list:async t=>sn(t,(await e()).runtimeUrl),read:async t=>an(t,(await e()).runtimeUrl),readBlob:async t=>cn(t,(await e()).runtimeUrl),status:async()=>br((await e()).runtimeUrl),findFiles:async(t,n)=>Pr(t,n,(await e()).runtimeUrl),findText:async t=>Sr(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>ln(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>kr(t,n,(await e()).runtimeUrl),create:async t=>xr(t,(await e()).runtimeUrl),copy:async(t,n)=>wr(t,n,(await e()).runtimeUrl),remove:async t=>Et(t,(await e()).runtimeUrl),mkdir:async t=>un(t,(await e()).runtimeUrl),rename:async(t,n)=>vr(t,n,(await e()).runtimeUrl)}}function iP(e){return{get:t=>Wn(e.projectId,e.sessionId,t),presence:(t,n)=>c.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>Zn(e.sessionId,{projectId:e.projectId}),update:t=>ru(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),ou(e.projectId,e.sessionId)),restore:()=>iu(e.projectId,e.sessionId),recover:()=>su(e.projectId,e.sessionId),start:(...t)=>nt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Cu(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Yn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Jn(e.projectId,e.sessionId)),configState:()=>au(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),cu(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),lu(e.projectId,e.sessionId,...t)),setSharing:t=>jl(e.projectId,e.sessionId,t),previews:()=>Kl(e.projectId,e.sessionId),participants:()=>$l(e.projectId,e.sessionId),watch:()=>Ul(e.projectId,e.sessionId),setWatch:t=>Fl(e.projectId,e.sessionId,t),setPinned:t=>Nl(e.projectId,e.sessionId,t),setArchived:t=>Bl(e.projectId,e.sessionId,t),commit:t=>Cl(e.projectId,e.sessionId,t),publicShares:{list:()=>ql(e.projectId,e.sessionId),create:(...t)=>Gl(e.projectId,e.sessionId,...t),revoke:(...t)=>Wl(e.projectId,e.sessionId,...t)}}}function aP(e){return{reminders:{list:()=>Td(e.projectId,e.sessionId),create:t=>Id(e.projectId,e.sessionId,t),update:(t,n)=>jo(e.projectId,e.sessionId,t,n),remove:t=>$o(e.projectId,e.sessionId,t)},audit:(t,n)=>zl(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Cm(e.projectId,e.sessionId,t,n),read:(t,n)=>Tm(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Yl(e.projectId,e.sessionId,t),messageAuthors:()=>gu(e.projectId,e.sessionId),modelUsage:()=>mu(e.projectId,e.sessionId),transcriptSync:t=>Hn(e.projectId,e.sessionId,t),log:t=>Jl(e.projectId,e.sessionId,t),turn:()=>Vn(e.projectId,e.sessionId),prompts:{create:t=>zn(e.projectId,e.sessionId,t),list:()=>Ql(e.projectId,e.sessionId),remove:t=>Xl(e.projectId,e.sessionId,t),retry:t=>tu(e.projectId,e.sessionId,t),edit:(t,n)=>Zl(e.projectId,e.sessionId,t,n),interrupt:t=>eu(e.projectId,e.sessionId,t),hold:t=>nu(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function cP(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var oO=["control_plane","provider_ingress","daemon","upstream_port"];function rf(e){return typeof e=="string"&&oO.includes(e)?e:null}function of(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.harness?e.harness.ready===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function sf(e,t){let n=(e===void 0?ze():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await j(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),o=await r.text().catch(()=>""),s=null;try{s=o?JSON.parse(o):null}catch{s=null}let i=s,a=rf(r.headers.get("X-Kortix-Proxy-Hop"))??rf(s?.hop),l=Number(r.headers.get("X-Kortix-Upstream-Status")),p=s?.upstream_status,d=Number.isFinite(l)&&l>0?l:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:o,hop:a,upstreamStatus:d}}var lP=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,uP=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,pP=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,dP=new Set([22,4096,parseInt(Ke.KORTIX_MASTER,10)]);function sO(e){return uP.test(e)}function ws(e){if(!e)return"/";let t=e,n=t.indexOf("](");n!==-1&&(t=t.slice(0,n));let r=t.toLowerCase().indexOf("%5d(");return r!==-1&&(t=t.slice(0,r)),t?t.startsWith("/")?t:`/${t}`:"/"}function iO(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var aO=new Set(["'",'"',"`","<","(","["]),cO=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function lO(e){let t=0,n=e.length;for(;t<n&&(e[t]===" "||e[t]===" ");)t++;for(;n>t&&(e[n-1]===" "||e[n-1]===" ");)n--;for(;t<n&&aO.has(e[t]);)t++;for(;n>t&&cO.has(e[n-1]);)n--;return e.slice(t,n)}function uO(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var pO=/^\/proxy\/(\d{1,5})(\/.*)?$/,dO=/^\/(connectors|settings|dashboard|projects|agents|skills|tools|commands|support|changelog|files|p|browser|desktop|terminal|sessions|services|workspace|channels|scheduled-tasks|marketplace|templates|tunnel|admin|auth)(\/|$|\?)/;function gP(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:dO.test(t.pathname)}catch{return!1}}function Rr(e){if(!e)return null;let t=lO(iO(e.trim())),n=cf(t);if(n){let r=ws(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let o=parseInt(r.port,10);if(!Number.isInteger(o)||o<1||o>65535)return null;let s=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Ke.KORTIX_MASTER,10);if(o===i){let l=r.pathname.match(pO);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return o=p,s=ws(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=ws(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=uO(e);return r&&r!==e?Rr(r):null}}function gO(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let o=/`[^`\n]+`/g;for(;(r=o.exec(e))!==null;){let s=r.index,i=s+r[0].length;t.some(([l,p])=>s>=l&&i<=p)||t.push([s,i])}return t}function mO(e,t){return t.some(([n,r])=>e>=n&&e<r)}function mP(e){let t=[],n=new Set,r=gO(e);lP.lastIndex=0;let o;for(;(o=lP.exec(e))!==null;){let s=Rr(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:l}=s;a<1||a>65535||dP.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:l,startIndex:o.index,endIndex:o.index+i.length,inCodeBlock:mO(o.index,r)}))}return t}function fO(e){return mP(e).length>0}function yO(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function fP(e){return e.trim().toLowerCase().split("_").join("-")}function yP(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function hO(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let o=r.split("{port}").join(String(e)).split("{sandbox}").join(fP(n.sandboxId));return`${yP(o)}${t}`}function hP(e){return e.sandboxId.trim().length>0}function dt(e,t,n){let r=ws(t);if(!hP(n))return SP(e,r);let o=hO(e,r,n);return o||(yO(n.apiBaseUrl)?`http://p${e}-${fP(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${yP(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function _O(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return dt(3211,`/open?path=/workspace/${r}`,t)}function _P(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function bO(e){return`http://localhost:3211${_P(e)}`}function bP(){return"/health"}function PO(e){return dt(3211,bP(),e)}function SO(e,t){return dt(e,"/",t)}function PP(e){let t=Rr(e);return!(!t||dP.has(t.port)||gP(e))}function af(e,t){if(!e)return e;let n=Rr(e);return n?PP(n.originalUrl)?dt(n.port,n.path,t):n.originalUrl:e}function SP(e,t="/"){return`http://localhost:${e}${t}`}var xP=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function cf(e){let t=e.match(uP);if(t)return{port:parseInt(t[1],10),sandboxId:t[2],backendPort:t[3]?parseInt(t[3],10):80,path:t[4]||"/"};let n=e.match(pP);if(n){let o=443;try{let s=new URL(e);o=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:o,path:n[4]||"/"}}let r=e.match(xP);if(r)try{let o=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(o.port,10)||(o.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function xO(e){try{let t=cf(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function wO(e){return sO(e)||pP.test(e)||xP.test(e)}function kO(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Ar="/web-proxy/";function vO(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${Ar}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt(Ke.KORTIX_MASTER,10);return`${dt(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function AO(e){try{let t=new URL(e),n=t.pathname.indexOf(Ar);if(n===-1)return null;let o=t.pathname.slice(n+Ar.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!o)return null;let s=o[1],i=o[2],a=o[3]||"/";return`${s}://${i}${a}${t.search}${t.hash}`}catch{return null}}function RO(e){try{return new URL(e).pathname.includes(Ar)}catch{return e.includes(Ar)}}function CO(e){if(!e)return!1;let t=e.trim();return!!(/^https?:\/\/(?!localhost|127\.0\.0\.1)/i.test(t)||/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t))}function TO(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function wP(e){return{health:t=>sf(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>dt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>af(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ie(e.requireReady("sandboxPortUrl").sandboxId,t)}}function lf(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=cb(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=db(e,t,n),m={projectId:e,sessionId:t,ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return o},set model(f){o=f},get agent(){return s},set agent(f){s=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...iP(m),...aP(m),...wP(m),...hb(m),...kb(m),...Wb(m),files:sP(l),...yb(m),get runtime(){return Me(d("runtime").runtimeUrl)}}}function kP(e){return{apps:{list:()=>bg(e),create:t=>Pg(e,t),get:t=>Uo(e,t),update:(...t)=>Sg(e,...t),access:{get:(...t)=>vg(e,...t),update:(...t)=>Rg(e,...t),session:(...t)=>Cg(e,...t),agents:t=>Ag(e,t)},remove:t=>xg(e,t),token:t=>wg(e,t),authEnv:t=>kg(e,t),artifacts:{register:t=>Fo(e,t),uploadArchive:(...t)=>Tg(e,...t),finalize:(...t)=>No(e,...t)},deployments:{create:(...t)=>Ig(e,...t),list:t=>Eg(e,t),get:(...t)=>Mg(e,...t),logs:(...t)=>Og(e,...t),remove:(...t)=>jg(e,...t)},start:t=>Dg(e,t),stop:t=>Lg(e,t),rollback:(...t)=>$g(e,...t),machines:{list:t=>Ug(e,t),start:(t,n)=>Ng(e,t,n),stop:(t,n)=>Bg(e,t,n),restart:(t,n)=>Kg(e,t,n),destroy:(t,n)=>qg(e,t,n)},scale:(...t)=>Gg(e,...t),exec:(...t)=>Wg(e,...t),volumes:{list:t=>Hg(e,t),create:(...t)=>Vg(e,...t),update:(...t)=>zg(e,...t),destroy:(...t)=>Yg(e,...t),snapshots:(...t)=>Jg(e,...t),snapshot:(...t)=>Qg(e,...t),restore:(...t)=>Xg(e,...t),fork:(...t)=>Zg(e,...t)}}}}function vP(e){return{list:()=>Ra(e),invite:(...t)=>Ia(e,...t),update:(...t)=>Ca(e,...t),revoke:t=>Ta(e,t),pendingInvites:()=>Ea(e),resendInvite:(...t)=>Oa(e,...t),revokeInvite:(...t)=>Ma(e,...t),requests:()=>ka(e),approveRequest:(...t)=>va(e,...t),rejectRequest:(...t)=>Aa(e,...t),groupGrants:()=>Da(e),attachGroupGrant:(...t)=>La(e,...t),updateGroupGrant:(...t)=>ja(e,...t),detachGroupGrant:t=>$a(e,t),resourceGrants:{list:()=>Ua(e),create:t=>Fa(e,t),remove:t=>Na(e,t)}}}function AP(e){return{tokens:{list:()=>Xd(e),create:t=>Zd(e,t),revoke:t=>eg(e,t)},setupLinks:{requestSecret:t=>lg(e,t),requestConnector:t=>ug(e,t)},validateManifest:t=>ea(e,t),gitToken:()=>ta(e),agentIdentities:()=>td(e),secrets:{list:()=>Ga(e),upsert:t=>Wa(e,t),setStrategy:(...t)=>Ha(e,...t),broker:(...t)=>Va(e,...t),remove:t=>Ln(e,t),setPersonal:(...t)=>Qa(e,...t),removePersonal:t=>Xa(e,t),setGitCredential:t=>Ja(e,t),listProviderOAuth:()=>za(e),startProviderOAuth:(...t)=>uo(e,...t),pollProviderOAuth:(...t)=>po(e,...t),removeProviderOAuth:t=>Ya(e,t)},access:vP(e)}}function RP(e){return{list:()=>dc(e),listAll:()=>gc(e),reconcile:(...t)=>mc(e,...t),reconcileMember:(...t)=>fc(e,...t),updateCredential:(...t)=>yc(e,...t),revoke:(...t)=>hc(e,...t),activate:(...t)=>_c(e,...t),setDefault:(...t)=>bc(e,...t),rename:(...t)=>Pc(e,...t),share:(...t)=>xc(e,...t),addComputer:(...t)=>Sc(e,...t),pipedreamConnect:(...t)=>wc(e,...t),pipedreamFinalize:(...t)=>kc(e,...t)}}function ks(e){return{catalog:t=>Nt(e,t),tools:()=>yo(e),search:(...t)=>pc(e,...t),describe:(...t)=>ho(e,...t),call:(...t)=>kt(e,...t),callAction:(t,n,r,o)=>kt(e,`${t}.${n}`,r,o),accounts:(...t)=>_o(e,...t),uploadAttachment:(...t)=>bo(e,...t)}}function uf(e,t){return{slug:t,run:(r,o,s)=>ko(e,t,r,o,s),call:(r,o,s)=>kt(e,`${t}.${r}`,o,s),describe:async r=>r!==void 0?ho(e,`${t}.${r}`):(await Nt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===t)??null,accounts:()=>_o(e,t),paginate:(r,o,s)=>Vc(e,t,r,o,s),uploadAttachment:(r,o)=>bo(e,r,{...o,connector:t})}}var IO=100,CP=0,EO=new Set(["attachment_size_mismatch","attachment_failed"]),TP=()=>new S("Attachment expired. Attach the file again.",{code:"attachment_expired"});function pf(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function MO(e,t,n){let r,o=0,s,i=()=>{s=void 0,!(!t()||e.item.status!=="uploading"||r===void 0)&&(e.item={...e.item,receivedBytes:r},r=void 0,o=Date.now(),n())},a=p=>Math.floor(p*100/e.item.size),l=()=>{s&&clearTimeout(s),s=void 0};return{onProgress:p=>{if(!t()||a(p)===a(e.item.receivedBytes)||(r=p,s))return;let d=o+IO-Date.now();if(d<=0)return i();s=setTimeout(i,d),typeof s=="object"&&"unref"in s&&s.unref()},onProcessing:()=>{l(),r=void 0,t()&&(e.item={...e.item,status:"processing",receivedBytes:e.item.size},n())},clear:l}}function df(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,o=new Set,s=new Set,i=0,a=!1,l,p={attachments:[]},d=()=>[...r.values()].filter(h=>!h.handedOff);function g(h,x){h.removalDeleted||(h.removalDeleted=!0,Bt(e,x).catch(()=>{}))}function m(){l&&clearTimeout(l);let h=d().map(({item:P})=>P);(h.length!==p.attachments.length||h.some((P,v)=>P!==p.attachments[v]))&&(p={attachments:h});let x=Math.min(...h.filter(P=>P.status==="ready").map(P=>Date.parse(P.attachment.expires_at)));Number.isFinite(x)&&!a&&(l=setTimeout(()=>{for(let P of d())P.item.status==="ready"&&Date.parse(P.item.attachment.expires_at)<=Date.now()&&(P.item={...P.item,status:"error",error:TP()});m()},Math.min(2147483647,Math.max(0,x-Date.now()))),typeof l=="object"&&"unref"in l&&l.unref());for(let P of o)P();for(let P of[...s])P()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function _(h){f();let x=d();if(x.length+h.length>20)throw new Error("A message can contain up to 20 attachments");if(h.some(v=>!Number.isSafeInteger(v)||v<=0||v>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(x.reduce((v,T)=>v+T.item.size,0)+h.reduce((v,T)=>v+T,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function y(h,x,P){let v=++h.generation,T=new AbortController;h.abort=T,h.item={...h.item,status:"uploading",error:void 0};let L=()=>(!a||h.handedOff===!0)&&r.get(h.item.id)===h&&h.generation===v,w=MO(h,L,m);Bn(e,x,{resume:h.upload,signal:T.signal,onUpload:D=>{h.upload=D,h.removed&&(T.abort(),g(h,D.attachment_id))},...w}).then(D=>{L()&&(h.item={...h.item,status:"ready",attachment:pf(D),receivedBytes:D.size})}).catch(D=>{D instanceof S&&EO.has(D.code??"")&&(h.upload=void 0),L()&&(h.item={...h.item,status:D instanceof S&&D.code==="ABORTED"?"aborted":"error",error:D instanceof Error?D:new Error(String(D))})}).finally(()=>{w.clear(),h.abort===T&&(h.abort=void 0),P()})}function k(){for(let h of r.values()){if(i>=n)break;if(h.item.status!=="pending"||!h.item.file||a&&!h.handedOff)continue;let x=h.item.file;i++,y(h,x,()=>{i--,m(),k()})}m()}function R(h){_(h.map(P=>P.size));let x=h.map(P=>{let v=`attachment-${++CP}`;return r.set(v,{generation:0,item:{id:v,file:P,filename:P.name,mime:P.type||"application/octet-stream",size:P.size,status:"pending",receivedBytes:0}}),v});return m(),k(),x}function I(h){let x=h.map(({attachment:v,file:T})=>{try{return{attachment:pf(v),file:T}}catch{return}});_(x.flatMap(v=>v?[v.attachment.size]:[]));let P=x.map(v=>{if(!v)return;let T=`attachment-${++CP}`,{attachment:L,file:w}=v;return r.set(T,{generation:0,item:{id:T,...w?{file:w}:{},filename:L.filename,mime:L.mime,size:L.size,status:"ready",receivedBytes:L.size,attachment:L}}),T});return m(),P}function b(h){let x=r.get(h);!x||x.item.status==="ready"||(x.generation++,x.abort?.abort(),x.item={...x.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function M(h,{signal:x}={}){let P=[...h];return new Promise((v,T)=>{let L=()=>{s.delete(Se),x?.removeEventListener("abort",D)},w=N=>{L(),T(N)},D=()=>w(Ae()),Se=()=>{let N=!1;for(let G of P){let K=r.get(G);if(!K)return w(new Error("Attachment was removed before it was sent"));if(a&&!K.handedOff)return w(new Error("Attachment controller is disposed"));if(K.item.status==="error"||K.item.status==="aborted")return w(K.item.error??new Error("Attachment upload failed"));K.item.status!=="ready"&&(N=!0)}if(N)return;let z;try{z=P.map(G=>{let K=pf(r.get(G).item.attachment);return{type:"file",attachment_id:K.attachment_id,filename:K.filename,mime:K.mime}})}catch(G){return w(G instanceof Error?G:new Error(String(G)))}L(),v(z)};if(x?.aborted)return D();s.add(Se),x?.addEventListener("abort",D,{once:!0}),Se()})}return{add:h=>R([h])[0],addMany:R,restore:I,retry(h){let x=r.get(h);if(x?.handedOff||f(),!(!x||x.item.status==="ready"||x.item.status==="uploading"||x.item.status==="processing"||x.item.status==="pending")){if(!x.item.file||x.upload&&Date.parse(x.upload.expires_at)<=Date.now())throw TP();x.item={...x.item,status:"pending",error:void 0},k()}},async remove(h){let x=r.get(h);if(!x)return;x.removed=!0,x.generation++,r.delete(h);let P=x.upload?.attachment_id??x.item.attachment?.attachment_id;P&&x.abort?.abort(),m(),k(),P&&g(x,P)},abort:b,submit(h){if(!a){for(let x of h){let P=r.get(x);P&&(P.handedOff=!0)}m()}},reclaim(h){if(!a){for(let x of h){let P=r.get(x);P&&(P.handedOff=!1)}m()}},whenReady:M,forget(h=d().map(x=>x.item.id)){for(let x of h){let P=r.get(x);P&&(P.generation++,P.abort?.abort(),r.delete(x))}m(),k()},dispose(){if(!a){a=!0,l&&clearTimeout(l);for(let h of r.values()){if(h.handedOff)continue;h.generation++,h.abort?.abort();let x=h.upload?.attachment_id??h.item.attachment?.attachment_id;x&&e&&Bt(e,x).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(h){return o.add(h),()=>{o.delete(h)}}}}function IP(e){return{attachments:{upload:(...t)=>Bn(e,...t),delete:(...t)=>Bt(e,...t),createController:t=>df(e,t)},get:t=>wt(e,t),detail:()=>In(e),skills:{remove:(...t)=>ua(e,...t),create:(...t)=>la(e,...t)},audit:t=>rg(e,t),update:t=>On(e,t),archive:()=>Dn(e),llmCatalog:()=>En(e),modelPicker:()=>Mn(e),modelAccess:()=>nr(e),setModelAccess:t=>rr(e,t),customLlmProviders:()=>or(e),setCustomLlmProvider:(t,n)=>sr(e,t,n),deleteCustomLlmProvider:t=>ir(e,t),sandboxHealth:()=>$n(e),onboardingComplete:(...t)=>ca(e,...t)}}function EP(e){return{sessions:{list:t=>At(e,t),listPage:t=>Ll(e,t),create:t=>Rt(e,t),ensureWarm:()=>Hl(e),claimWarm:t=>Vl(e,t)},review:{list:t=>Pd(e,t),summary:()=>Sd(e),get:t=>xd(e,t),submit:t=>wd(e,t),act:(...t)=>kd(e,...t),bulkAct:t=>vd(e,t)},approvals:{list:t=>Ba(e,t),resolve:(...t)=>qa(e,...t),sessionsNeedingInput:t=>Ka(e,t)}}}function MP(e){return{files:{list:t=>sl(e,t),listDirectory:t=>il(e,t),read:(t,n)=>cl(e,t,n),search:(...t)=>al(e,...t),archive:(...t)=>ll(e,...t),archiveRequest:(...t)=>ul(e,...t),history:(...t)=>hl(e,...t)},git:{commits:()=>ml(e),commit:t=>fl(e,t),commitDiff:t=>yl(e,t),branches:()=>gl(e),versionDiff:(...t)=>_l(e,...t),inviteCollaborator:(...t)=>Zi(e,...t)},changeRequests:{list:(...t)=>bl(e,...t),get:t=>Pl(e,t),update:(...t)=>Tl(e,...t),diff:t=>Sl(e,t),mergePreview:t=>xl(e,t),open:(...t)=>wl(e,...t),merge:(...t)=>kl(e,...t),close:(...t)=>vl(e,...t),reopen:(...t)=>Al(e,...t),requestChanges:(...t)=>Rl(e,...t)},...EP(e)}}function OP(e){return{policies:{list:()=>zc(e),set:(...t)=>Yc(e,...t)},reminders:{list:()=>Od(e),updateMany:(...t)=>Ed(e,...t),removeMany:(...t)=>Md(e,...t)},rooms:{list:(...t)=>Ld(e,...t),create:(...t)=>jd(e,...t),get:(...t)=>$d(e,...t),update:(...t)=>Ud(e,...t),messages:(...t)=>Fd(e,...t),post:(...t)=>Nd(e,...t),markRead:(...t)=>Bd(e,...t),addSession:(...t)=>Kd(e,...t),removeSession:(...t)=>qd(e,...t),addPerson:(...t)=>Gd(e,...t),removePerson:(...t)=>Wd(e,...t),people:(...t)=>Hd(e,...t)},triggers:{list:()=>fu(e),eventApps:()=>vu(e),eventTypes:(...t)=>ku(e,...t),create:(...t)=>yu(e,...t),update:(...t)=>hu(e,...t),remove:(...t)=>_u(e,...t),fire:((t,n)=>Pu(e,t,n)),runs:(...t)=>Su(e,...t),projectRuns:(...t)=>xu(e,...t),replay:(...t)=>wu(e,...t),setActivation:(...t)=>bu(e,...t)},...MP(e)}}function DP(e,t){return{connectors:{...ks(e),list:()=>vc(e),config:(...n)=>Mc(e,...n),create:(...n)=>Lc(e,...n),remove:(...n)=>Fc(e,...n),sync:()=>Ac(e),auth:{discover:(...n)=>jc(e,...n)},setName:(...n)=>Oc(e,...n),setCredentialMode:(...n)=>Rc(e,...n),setAuthorizationStrategy:(...n)=>Cc(e,...n),setCredential:(...n)=>Gc(e,...n),deleteCredential:(...n)=>Wc(e,...n),setSensitive:(...n)=>Tc(e,...n),connections:t,policies:{get:(...n)=>Ic(e,...n),set:(...n)=>Ec(e,...n)},listMoves:()=>$c(e),move:(...n)=>Uc(e,...n),pipedream:{listApps:(...n)=>Nc(e,...n),listSections:(...n)=>Bc(e,...n),connect:(...n)=>Dc(e,...n),finalize:(...n)=>Hc(e,...n)},discover:{list:(...n)=>Po(e,...n),sections:(...n)=>Kc(e,...n),detail:(...n)=>So(e,...n)}},...OP(e)}}function LP(e){return{gateway:{logs:t=>Rp(e,t),log:t=>Cp(e,t),overview:t=>Tp(e,t),series:t=>Ip(e,t),breakdown:t=>Ep(e,t),sessions:t=>Mp(e,t),errors:t=>Op(e,t),budgets:()=>Dp(e),setBudget:t=>Lp(e,t),deleteBudget:t=>jp(e,t),keys:()=>$p(e),createKey:t=>Up(e,t),revokeKey:t=>Fp(e,t),routing:{get:()=>wp(e),set:t=>kp(e,t),reset:()=>vp(e),preview:t=>Ap(e,t)},playground:(t,n,r)=>Np(e,t,n,r)}}}function jP(e){return{modelDefaults:{get:()=>Tu(e),set:t=>Iu(e,t),clear:t=>Eu(e,t)},setDefaultAgent:t=>Du(e,t),sandbox:{list:()=>ol(e),snapshots:()=>Qc(e),rebuildSnapshot:t=>Xc(e,t),fixWithAgent:()=>Zc(e),createTemplate:t=>el(e,t),updateTemplate:(...t)=>tl(e,...t),removeTemplate:t=>nl(e,t),buildTemplate:t=>rl(e,t),setProvider:t=>aa(e,t)},setAgentScope:(...t)=>Mu(e,...t)}}function $P(e){return{channels:{slack:{installation:()=>cp(e),connect:t=>lp(e,t),mode:()=>up(e),completeInstall:t=>pp(e,t),manifest:()=>gp(e),disconnect:()=>mp(e),getFile:t=>fp(e,t),uploadFile:t=>yp(e,t)},teams:{completeInstall:t=>dp(e,t)},email:{installation:t=>_p(e,t),mode:()=>bp(e),connect:t=>Pp(e,t),disconnect:t=>Sp(e,t),updatePolicy:(...t)=>xp(e,...t)}},updateFeatureFlag:(...t)=>sa(e,...t),updateExperimentalFeature:(...t)=>ia(e,...t),...jP(e)}}var OO=["screen","actions","audio"],DO=["password_managers","messaging","banking"],LO={localHours:8760,remoteDays:3650},jO=[500,1e3,2e3,5e3,1e4],$O=[720,1080,1440,2160],UO={intervalMs:2e3,maxHeight:1440},FO=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function NO(e){let t=e.trim().toLowerCase();if(!t)return null;let n;try{n=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{return null}return n=n.replace(/^www\./,"").replace(/\.$/,""),FO.test(n)?n:null}function BO(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||t.endsWith("*")&&t.slice(0,-1).trim().length<3?null:t}function KO(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var X=e=>`/accounts/${e}/capture`;function Qe(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o!==void 0&&o!==""&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}var UP=e=>Qe({q:e.q,kinds:e.kinds?.join(","),app:e.app,limit:e.limit,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,scope:e.scope}),gf=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function mf(e,t={}){return u(await c.get(`${X(e)}/devices${Qe({user_id:t.userId,scope:t.scope})}`))}async function ff(e,t){return u(await c.delete(`${X(e)}/devices/${t}`))}async function yf(e,t,n){return u(await c.put(`${X(e)}/devices/${t}/link`,{user_id:n}))}async function hf(e){return u(await c.get(`${X(e)}/enrollment-tokens`))}async function _f(e,t){return u(await c.post(`${X(e)}/enrollment-tokens`,t))}async function bf(e,t){return u(await c.delete(`${X(e)}/enrollment-tokens/${t}`))}async function Pf(e,t={}){return u(await c.get(`${X(e)}/enrollments${Qe({status:t.status})}`))}async function Sf(e,t,n){return u(await c.post(`${X(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function xf(e,t){return u(await c.post(`${X(e)}/enrollments/${t}/deny`,{}))}async function wf(e){return u(await c.get(`${X(e)}/policy`))}async function kf(e,t){return u(await c.put(`${X(e)}/policy`,{policy:t}))}async function vf(e,t={}){return u(await c.get(`${X(e)}/timeline${Qe(gf(t))}`))}async function Af(e,t={}){return u(await c.get(`${X(e)}/timeline/items${Qe(gf(t))}`))}async function Rf(e,t={}){return u(await c.get(`${X(e)}/days${Qe({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function Cf(e,t){return u(await c.get(`${X(e)}/search${UP(t)}`))}async function Tf(e,t,n={}){return u(await c.get(`${X(e)}/frames/${t}${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function If(e,t,n={}){return u(await c.get(`${X(e)}/chunks/${t}/media${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function Ef(e,t,n){return u(await c.get(`${X(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function Mf(e){return u(await c.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function Of(e,t){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function Df(e){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Lf(e){return u(await c.get(X(e)))}async function jf(e,t){return u(await c.patch(X(e),{enabled:t}))}async function $f(e){return u(await c.get(`/capture/me/search${UP(e)}`))}async function Uf(e={}){return u(await c.get(`/capture/me/timeline${Qe(gf(e))}`))}async function Ff(e){return u(await c.get(`/capture/me/frames/${e}`))}function GO(e){return{workspace:{get:()=>Lf(e),setEnabled:t=>jf(e,t)},devices:{list:t=>mf(e,t),revoke:t=>ff(e,t),link:(t,n)=>yf(e,t,n),assetUrl:(t,n)=>Ef(e,t,n)},enrollment:{tokens:{list:()=>hf(e),create:t=>_f(e,t),revoke:t=>bf(e,t)},list:t=>Pf(e,t),approve:(t,n)=>Sf(e,t,n),deny:t=>xf(e,t)},policy:{get:()=>wf(e),set:t=>kf(e,t)},timeline:{get:t=>vf(e,t),items:t=>Af(e,t),days:t=>Rf(e,t)},search:t=>Cf(e,t),frame:(t,n)=>Tf(e,t,n),media:(t,n)=>If(e,t,n)}}var FP={account:e=>GO(e),deviceGrant:Mf,approveDevice:Of,denyDevice:Df,me:{search:$f,timeline:Uf,frame:Ff}};async function Nf(e){let t=e?.fetch??C().fetch??((o,s)=>fetch(o,s)),n=e?.backendUrl??C().backendUrl,r=await t(`${qe(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new S(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var WO=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function HO(e,t){let n=s=>{let i=WO.exec(s.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),o=n(t);if(!r||!o)return null;for(let s=0;s<3;s++)if(r[s]!==o[s])return r[s]<o[s]?-1:1;return 0}function VO(){return ut()}var NP=null,BP=!1;function zO(e){let t=NP;NP=e,!(BP||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(BP=!0,console.warn("[kortix] createKortix() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedKortix() from @kortix/sdk/server.")))}function KP(e,t){t?.global!==!1&&zO(e),Xr(e,t);let n=ab(e),{auth:r,accounts:o,iam:s,accountInvites:i}=nb(),{billing:a,sandboxShares:l}=Z_(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=X_();function _(y){let k=RP(y);return{...IP(y),...kP(y),...AP(y),...DP(y,k),...LP(y),...$P(y),connector:R=>uf(y,R),session:R=>lf(y,R,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:ks(),connector:y=>uf(void 0,y),project:_,session:(y,k)=>lf(y,k,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,capture:FP,notifications:{registerDeviceToken:rm,unregisterDeviceToken:om,releaseDeviceToken:sm,list:im,markRead:am,preferences:cm,updatePreferences:lm,webPushPublicKey:um,registerWebPushSubscription:pm,unregisterWebPushSubscription:dm},mobileClientPolicy:Nf,validateToken:Qi,runtime:VO}}function qP(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<16;r++)t[r]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(r=>r.toString(16).padStart(2,"0"));return`${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n.slice(10).join("")}`}function GP(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function pn(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function WP(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function HP(e){if(pn(e).length>0)return{state:e};let t=e.pending[0];if(!t)return{state:e};let n={...t,attempts:t.attempts+1};return{state:{...e,pending:[n,...e.pending.slice(1)],inFlightId:n.id,inFlightIds:[n.id]},claimed:n}}function VP(e){let t=pn(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function zP(e,t){let n=pn(e);if(n.length===0)return e;let r=e.pending.filter(o=>n.includes(o.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(o=>!n.includes(o.id)),failed:[...e.failed,...r.map(o=>({...o,lastError:t}))],inFlightId:null,inFlightIds:[]}}function YP(e,t){let n=e.failed.find(s=>s.id===t);if(!n)return e;let{lastError:r,...o}=n;return{...e,pending:[...e.pending,o],failed:e.failed.filter(s=>s.id!==t)}}function JP(e,t){return pn(e).includes(t)?e:e.pending.some(n=>n.id===t)?{...e,pending:e.pending.filter(n=>n.id!==t)}:e.failed.some(n=>n.id===t)?{...e,failed:e.failed.filter(n=>n.id!==t)}:e}function QP(e,t,n){return pn(e).includes(t)||!e.pending.some(r=>r.id===t)?e:{...e,pending:e.pending.map(r=>r.id===t?{...r,text:n}:r)}}function XP(e,t,n){let r=pn(e);if(r.includes(t))return e;let o=e.pending.findIndex(p=>p.id===t);if(o===-1)return e;let s=r.length,i=Math.min(Math.max(n,s),e.pending.length-1);if(i===o)return e;let a=[...e.pending],[l]=a.splice(o,1);return a.splice(i,0,l),{...e,pending:a}}var Bf={thinking:!1,toolDetails:!0,assistantMetadata:!0};function YO(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function JO(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=t%60;return`${n}m ${r.toFixed(0)}s`}function QO(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
22
22
 
23
23
  `;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
24
24
  >
@@ -35,13 +35,13 @@ ${r}
35
35
  \`\`\`
36
36
 
37
37
  </details>
38
- `}catch{}if(t.toolDetails&&e.state?.status==="completed"&&e.state.output){let r=e.state.output,s=r.length>2e3?r.slice(0,2e3)+`
38
+ `}catch{}if(t.toolDetails&&e.state?.status==="completed"&&e.state.output){let r=e.state.output,o=r.length>2e3?r.slice(0,2e3)+`
39
39
  ... (truncated)`:r;n+=`
40
40
  <details>
41
41
  <summary>Output</summary>
42
42
 
43
43
  \`\`\`
44
- ${s}
44
+ ${o}
45
45
  \`\`\`
46
46
 
47
47
  </details>
@@ -51,15 +51,15 @@ ${s}
51
51
  ${e.state.error}
52
52
  \`\`\`
53
53
  `),n+=`
54
- `,n}return""}function yO(e,t){if(!t)return`## Assistant
54
+ `,n}return""}function XO(e,t){if(!t)return`## Assistant
55
55
 
56
- `;let n=e.agent?gO(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=mO(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
56
+ `;let n=e.agent?YO(e.agent):"Assistant",r=e.modelID||"",o="";e.time?.completed&&e.time?.created&&(o=JO(e.time.completed-e.time.created));let s=[r,o].filter(Boolean).join(" \xB7 ");return s?`## ${n} (${s})
57
57
 
58
58
  `:`## ${n}
59
59
 
60
- `}function hO(e,t,n){let r="";e.role==="user"?r+=`## User
60
+ `}function ZO(e,t,n){let r="";e.role==="user"?r+=`## User
61
61
 
62
- `:r+=yO(e,n.assistantMetadata);for(let s of t)r+=fO(s,n);return r}function MP(e,t,n=Pf){let r=`# ${e.title||"Untitled Session"}
62
+ `:r+=XO(e,n.assistantMetadata);for(let o of t)r+=QO(o,n);return r}function ZP(e,t,n=Bf){let r=`# ${e.title||"Untitled Session"}
63
63
 
64
64
  `;r+=`**Session ID:** \`${e.id}\`
65
65
  `,r+=`**Created:** ${new Date(e.time.created).toLocaleString()}
@@ -67,32 +67,32 @@ ${e.state.error}
67
67
 
68
68
  `,r+=`---
69
69
 
70
- `;for(let s of t)r+=hO(s.info,s.parts,n),r+=`---
70
+ `;for(let o of t)r+=ZO(o.info,o.parts,n),r+=`---
71
71
 
72
- `;return r}function OP(e,t){return`session-${e}.md`}var Sf="An error occurred";var _O=["message","error","detail","error_description","msg","errors","data"];function xf(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function cn(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function bO(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=cn(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function PO(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=SO(e,t);if(n)return n;let r=wO(e,t);return r?r.slice(0,200):void 0}function $P(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function DP(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function SO(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!$P(t.charCodeAt(s))){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return;let i=e.indexOf("<",o+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(o+1,i).trim();if(a)return a}n=o+1}}var xO=["script","style"];function wO(e,t){let n=[],r=0;for(;r<e.length;){let s=e.indexOf("<",r);if(s===-1){n.push(e.slice(r));break}n.push(e.slice(r,s));let o=xO.find(i=>t.startsWith(`<${i}`,s)&&$P(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:DP(e,i);continue}r=DP(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function kO(e){if(!e.startsWith("JSON parsing failed: Text:"))return;let t=e.match(/"model"\s*:\s*"([^"\\]{1,120})"/)?.[1]?.trim();return t?`The response from ${t} could not be read.`:"The model response could not be read."}function vO(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function jP(e,t,n){if(typeof e=="string")return Po(e,t,n);if(e&&typeof e=="object")return So(e,t,n)}function Po(e,t,n=new WeakSet){let r=xf(e);if(!r)return;if(t>=4)return r;let s=kO(r);if(s)return s;let o=cn(r);if(o!==void 0)return typeof o=="string"?Po(o,t+1,n):o&&typeof o=="object"?So(o,t+1,n):String(o);let i=UP(r);if(i){let a=cn(i);if(a&&typeof a=="object"){let c=So(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=bO(r);if(a)return Po(a,t+1,n)??a}return PO(r)??r}function So(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let i of e){let a=jP(i,t,n);if(a)return a}return}let r=e;for(let i of _O){let a=jP(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return vO(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function fe(e){return e?typeof e=="string"?Po(e,0)??Sf:typeof e=="object"?So(e,0)??Sf:String(e):Sf}function _r(e){let t=AO(e)?.trim();if(!t)return;let n=fe(e);if(!(t===n||xf(t)===n))return t}function AO(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:s}=n,o=[r,s].filter((i,a,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(o.length>0)return o.join(`
72
+ `;return r}function eS(e,t){return`session-${e}.md`}var Kf="An error occurred";var eD=["message","error","detail","error_description","msg","errors","data"];function qf(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function dn(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function tD(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=dn(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function nD(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=rD(e,t);if(n)return n;let r=sD(e,t);return r?r.slice(0,200):void 0}function oS(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function tS(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function rD(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let o=r+6;if(!oS(t.charCodeAt(o))){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return;let i=e.indexOf("<",s+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(s+1,i).trim();if(a)return a}n=s+1}}var oD=["script","style"];function sD(e,t){let n=[],r=0;for(;r<e.length;){let o=e.indexOf("<",r);if(o===-1){n.push(e.slice(r));break}n.push(e.slice(r,o));let s=oD.find(i=>t.startsWith(`<${i}`,o)&&oS(t.charCodeAt(o+i.length+1)));if(s){let i=t.indexOf(`</${s}`,o);r=i===-1?e.length:tS(e,i);continue}r=tS(e,o)}return n.join(" ").replace(/\s+/g," ").trim()}function iD(e){if(!e.startsWith("JSON parsing failed: Text:"))return;let t=e.match(/"model"\s*:\s*"([^"\\]{1,120})"/)?.[1]?.trim();return t?`The response from ${t} could not be read.`:"The model response could not be read."}function aD(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function nS(e,t,n){if(typeof e=="string")return vs(e,t,n);if(e&&typeof e=="object")return As(e,t,n)}function vs(e,t,n=new WeakSet){let r=qf(e);if(!r)return;if(t>=4)return r;let o=iD(r);if(o)return o;let s=dn(r);if(s!==void 0)return typeof s=="string"?vs(s,t+1,n):s&&typeof s=="object"?As(s,t+1,n):String(s);let i=sS(r);if(i){let a=dn(i);if(a&&typeof a=="object"){let l=As(a,t+1,n);if(l)return l}}if(r.includes("{")){let a=tD(r);if(a)return vs(a,t+1,n)??a}return nD(r)??r}function As(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let i of e){let a=nS(i,t,n);if(a)return a}return}let r=e;for(let i of eD){let a=nS(r[i],t,n);if(a)return a}let o=r.type??r.code;if(typeof o=="string"&&o.trim())return aD(o);let s=r.status??r.statusCode??r.upstream_status;if(typeof s=="number"&&Number.isFinite(s))return`Request failed with status ${s}`}function fe(e){return e?typeof e=="string"?vs(e,0)??Kf:typeof e=="object"?As(e,0)??Kf:String(e):Kf}function Cr(e){let t=cD(e)?.trim();if(!t)return;let n=fe(e);if(!(t===n||qf(t)===n))return t}function cD(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:o}=n,s=[r,o].filter((i,a,l)=>typeof i=="string"&&i.trim()!==""&&l.indexOf(i)===a);if(s.length>0)return s.join(`
73
73
 
74
- `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function UP(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function RO(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(typeof t.message=="string"&&t.message)return t.message;if(typeof t.error=="string"&&t.error)return t.error;let n=t.data;if(typeof n?.message=="string")return n.message;let r=t.error;if(typeof r?.message=="string")return r.message}function CO(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n;!Number.isInteger(r.attempt)||r.attempt<1||typeof r.provider!="string"||!r.provider||typeof r.route_model!="string"||!r.route_model||typeof r.resolved_model!="string"||!r.resolved_model||typeof r.stage!="string"||!r.stage||typeof r.code!="string"&&!(typeof r.code=="number"&&Number.isFinite(r.code))||typeof r.message!="string"||!r.message||r.status!==void 0&&(!Number.isInteger(r.status)||r.status<100||r.status>599)||t.push({attempt:r.attempt,provider:r.provider,routeModel:r.route_model,resolvedModel:r.resolved_model,stage:r.stage,...typeof r.status=="number"?{status:r.status}:{},code:r.code,message:r.message})}return t.length>0?t:void 0}function LP(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,s=typeof e.upstream_status=="number"?e.upstream_status:void 0,o=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=CO(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,c=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&s===void 0&&!o&&!i?void 0:{message:typeof e.message=="string"&&e.message||RO(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function Pe(e){if(e==null)return;if(typeof e=="string"){let a=xf(e),c=cn(a)??cn(UP(a));return c!==void 0?Pe(c):void 0}if(typeof e!="object")return;let t=e,n=LP(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let s=t.error;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=LP(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=cn(o.responseBody);if(a!==void 0){let c=Pe(a);if(c)return c}}if(o&&typeof o.message=="string"){let a=Pe(o.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let c=Pe(a);if(c)return c}}return n}var FP={};function V(e,t){for(let n of t)FP[n]=e}V("read",["read"]);V("list",["list","ls"]);V("glob",["glob"]);V("grep",["grep"]);V("write",["write"]);V("edit",["edit","multiedit","morph_edit","MultiEdit","NotebookEdit"]);V("apply_patch",["apply_patch","patch"]);V("bash",["bash"]);V("script",["codemode"]);V("web_search",["web_search","websearch","image_search"]);V("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);V("media",["image_gen","video_gen"]);V("show",["show","show_user","presentation_gen"]);V("task",["task"]);V("delegate",["agent_spawn","agent_task","agent_task_create","agent_task_start","task_create","task_start","session_spawn","session_start_background","agent_message","agent_task_message","task_message","agent_task_update","task_update","session_message","agent_status","agent_task_list","agent_task_get","task_list","task_get","agent_stop","agent_task_cancel","task_cancel","agent_task_approve","task_approve","task_done","task_delete"]);V("todowrite",["todowrite","todo_write","todoread"]);V("question",["question","ask"]);V("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);V("connectors",["connector_get","connector_list","connector_setup","kortix_connector_call","kortix_connectors","kortix_connectors_connectors","kortix_connectors_discover","kortix_connectors_describe","kortix_connectors_call","kortix_connector_describe","kortix_connector_discover"]);V("automations",["triggers"]);V("skill",["skill"]);V("context",["prune","distill","compress","context_info"]);V("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var TO=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ae(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=FP[t];if(n)return n;for(let[r,s]of TO)if(t.startsWith(r))return s;return"other"}function ve(e){for(let t of[e?.filePath,e?.file_path,e?.path,e?.notebook_path])if(typeof t=="string"&&t)return t}var IO=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function EO(){return new RegExp(`(^|\\s)([-+]?)(${IO.join("|")}):("[^"]*"|\\S+)`,"gi")}function MO(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function OO(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function DO(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function jO(e){return DO(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function NP(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function br(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(EO(),(s,o,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=jO(c);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(MO(),"$1").replace(OO(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${NP(n)}`:r:n.length>0?NP(n):t}var LO=/\s/,$O=/\w/;function ye(e){return e!==void 0&&LO.test(e)}function Pr(e){return e===`
75
- `||e==="\r"||e==="\u2028"||e==="\u2029"}function wf(e){return e!==void 0&&$O.test(e)}function Mt(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(UO(n.charCodeAt(0))):n;return t}function UO(e){if(e<128)return e>=97&&e<=122?e-32:e;let t=String.fromCharCode(e).toUpperCase();if(t.length!==1)return e;let n=t.charCodeAt(0);return n<128?e:n}function Qe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function KP(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Qe(e.slice(t))}function Sr(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let s=e.indexOf(n,r+t.length);return s===-1?null:e.slice(r+t.length,s)}function kf(e,t){let n=Sr(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
74
+ `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function sS(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function lD(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(typeof t.message=="string"&&t.message)return t.message;if(typeof t.error=="string"&&t.error)return t.error;let n=t.data;if(typeof n?.message=="string")return n.message;let r=t.error;if(typeof r?.message=="string")return r.message}function uD(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n;!Number.isInteger(r.attempt)||r.attempt<1||typeof r.provider!="string"||!r.provider||typeof r.route_model!="string"||!r.route_model||typeof r.resolved_model!="string"||!r.resolved_model||typeof r.stage!="string"||!r.stage||typeof r.code!="string"&&!(typeof r.code=="number"&&Number.isFinite(r.code))||typeof r.message!="string"||!r.message||r.status!==void 0&&(!Number.isInteger(r.status)||r.status<100||r.status>599)||t.push({attempt:r.attempt,provider:r.provider,routeModel:r.route_model,resolvedModel:r.resolved_model,stage:r.stage,...typeof r.status=="number"?{status:r.status}:{},code:r.code,message:r.message})}return t.length>0?t:void 0}function rS(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,o=typeof e.upstream_status=="number"?e.upstream_status:void 0,s=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=uD(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,l=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&o===void 0&&!s&&!i?void 0:{message:typeof e.message=="string"&&e.message||lD(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:o,requestId:s,attemptFailures:i,...a?{requestedModel:a}:{},...l?{resolvedModel:l}:{}}}function be(e){if(e==null)return;if(typeof e=="string"){let a=qf(e),l=dn(a)??dn(sS(a));return l!==void 0?be(l):void 0}if(typeof e!="object")return;let t=e,n=rS(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let o=t.error;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=rS(o);if(a)return a}let s=t.data;if(s&&typeof s.responseBody=="string"){let a=dn(s.responseBody);if(a!==void 0){let l=be(a);if(l)return l}}if(s&&typeof s.message=="string"){let a=be(s.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let l=be(a);if(l)return l}}return n}var iS={};function H(e,t){for(let n of t)iS[n]=e}H("read",["read"]);H("list",["list","ls"]);H("glob",["glob"]);H("grep",["grep"]);H("write",["write"]);H("edit",["edit","multiedit","morph_edit","MultiEdit","NotebookEdit"]);H("apply_patch",["apply_patch","patch"]);H("bash",["bash"]);H("script",["codemode"]);H("web_search",["web_search","websearch","image_search"]);H("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);H("media",["image_gen","video_gen"]);H("show",["show","show_user","presentation_gen"]);H("task",["task"]);H("delegate",["agent_spawn","agent_task","agent_task_create","agent_task_start","task_create","task_start","session_spawn","session_start_background","agent_message","agent_task_message","task_message","agent_task_update","task_update","session_message","agent_status","agent_task_list","agent_task_get","task_list","task_get","agent_stop","agent_task_cancel","task_cancel","agent_task_approve","task_approve","task_done","task_delete"]);H("todowrite",["todowrite","todo_write","todoread"]);H("question",["question","ask"]);H("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);H("connectors",["connector_get","connector_list","connector_setup","kortix_connector_call","kortix_connectors","kortix_connectors_connectors","kortix_connectors_discover","kortix_connectors_describe","kortix_connectors_call","kortix_connector_describe","kortix_connector_discover"]);H("automations",["triggers"]);H("skill",["skill"]);H("context",["prune","distill","compress","context_info"]);H("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var pD=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ae(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=iS[t];if(n)return n;for(let[r,o]of pD)if(t.startsWith(r))return o;return"other"}function ve(e){for(let t of[e?.filePath,e?.file_path,e?.path,e?.notebook_path])if(typeof t=="string"&&t)return t}var dD=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function gD(){return new RegExp(`(^|\\s)([-+]?)(${dD.join("|")}):("[^"]*"|\\S+)`,"gi")}function mD(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function fD(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function yD(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function hD(e){return yD(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function aS(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Tr(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(gD(),(o,s,i,a,l)=>{if(!i&&a.toLowerCase()==="site"){let p=hD(l);p&&!n.includes(p)&&n.push(p)}return s});return r=r.replace(mD(),"$1").replace(fD(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${aS(n)}`:r:n.length>0?aS(n):t}var _D=/\s/,bD=/\w/;function ye(e){return e!==void 0&&_D.test(e)}function Ir(e){return e===`
75
+ `||e==="\r"||e==="\u2028"||e==="\u2029"}function Gf(e){return e!==void 0&&bD.test(e)}function Mt(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(PD(n.charCodeAt(0))):n;return t}function PD(e){if(e<128)return e>=97&&e<=122?e-32:e;let t=String.fromCharCode(e).toUpperCase();if(t.length!==1)return e;let n=t.charCodeAt(0);return n<128?e:n}function Xe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function cS(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Xe(e.slice(t))}function Er(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let o=e.indexOf(n,r+t.length);return o===-1?null:e.slice(r+t.length,o)}function Wf(e,t){let n=Er(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
76
76
  `)&&(n=n.slice(1)),n.endsWith(`
77
- `)&&(n=n.slice(0,-1)),n)}function vf(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let s=e.indexOf(">",r+1+t.length);return s===-1?null:{open:r,end:s}}function BP(e,t){let n=vf(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function qP(e,t){let n=vf(e,t);if(!n)return null;let r=e.indexOf(`</${t}>`,n.end+1);return r===-1?null:e.slice(n.end+1,r)}function GP(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=vf(e,t,s);if(!o)break;let i=e.indexOf(n,o.end+1);if(i===-1)break;r+=e.slice(s,o.open),s=i+n.length}return r+e.slice(s)}function WP(e,t,n){let r=[];for(let s of e.split(/[\n\r\u2028\u2029]/)){let o=0;for(;;){let i=s.indexOf(t,o);if(i===-1)break;let a=s.indexOf(n,i+t.length);if(a===-1)break;r.push(s.slice(i+t.length,a)),o=a+n.length}}return r}function xo(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&ye(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function VP(e,t,n){let r=Mt(t),s=Mt(n);for(let o of Mt(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function HP(e,t){let n=Mt(e),r=t.map(Mt),s=e.length,o=c=>{let p=c;for(;p<s&&ye(e[p]);)p++;return p},i=c=>{for(let p=c;p<s;p++)if(Pr(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let c=o(a);if(c>=s)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=o(c+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!Pr(e[m]);)m++;for(;m>g+1&&ye(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Pr(e[m]))return e[m];return null}}a=i(c)}return null}function zP(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=ye(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!ye(e[a-1]))continue;let c=a+1;if(ye(e[c])){for(;c<t&&ye(e[c]);)c++;wf(e[c])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(Pr(e[a])?1:0);let o=(a,c)=>s[c]===s[a],i=a=>{let c=a+1;for(;ye(e[c]);)c++;let p=c;for(;p<t&&wf(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&ye(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(o(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Pr(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function YP(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&ye(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&ye(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!wf(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&ye(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function JP(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(o<c&&(o=e.indexOf("]",c)),o===-1)break;let p=o;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(s,a)+(t?" ":e.slice(c,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function QP(e){return JP(e,!0)}function XP(e){return JP(e,!1)}function FO(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function ZP(e,t){let n=Mt(e),r=Mt(t),s=e.length,o=i=>{let a=i;for(;a<s&&ye(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=o(i+r.length);if(e[a]!==":")continue;let c=o(a+1);for(let p=c;p<s;){if(!ye(e[p])){p++;continue}let d=o(p);if(FO(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var eS=new Set(["read","glob","grep","list"]);function Z(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function NO(e){return eS.has(ae(e))}function KO(e){let t=0,n=0,r=0;for(let s of e){let o=ae(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function Af(e){if(!e)return"";let t=Qe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function wo(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function ko(e){let t=qe(e),r=(t.state??{}).input??{};switch(Z(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=ve(r);return i?Af(i):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${wo(String(i),40)}" in ${Af(String(a))}`:i?`"${wo(String(i),60)}"`:""}case"list":return r.path?Af(String(r.path)):"";case"bash":return wo(String(r.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of o){let a=r[i];if(typeof a=="string"&&a.length>0)return wo(i==="query"&&br(a)||a,60)}return""}var tS={read:"Read",search:"Search",list:"List",shell:"Shell",edit:"Edit",write:"Write",fetch:"Fetch",webSearch:"Web Search",scrape:"Scrape",applyPatch:"Apply Patch",task:"Task",worker:"Worker",workspace:"Workspace"};function BO(e,t={}){let n=ge(e)?oe(e):e,r={...tS,...t},s=Z(n.tool),o=ko(n);switch(s){case"read":return{title:r.read,subtitle:o};case"glob":case"grep":return{title:r.search,subtitle:o};case"list":return{title:r.list,subtitle:o};case"bash":return{title:r.shell,subtitle:o};case"edit":case"morph_edit":return{title:r.edit,subtitle:o};case"write":return{title:r.write,subtitle:o};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:o};case"websearch":case"web_search":return{title:r.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:o};case"apply_patch":return{title:r.applyPatch,subtitle:o};case"task":return{title:r.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:o};case"project_select":case"project_list":return{title:r.workspace,subtitle:o};default:return{title:s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:o}}}function Oe(e){return e.type==="text"}function we(e){return e.type==="reasoning"}function ee(e){return e.type==="tool"}function Cf(e){return e.type==="file"}function qO(e){return e.type==="agent"}function GO(e){return e.type==="compaction"}function WO(e){return e.type==="snapshot"}function VO(e){return e.type==="patch"}function HO(e){return e.type==="step-start"||e.type==="step-finish"}function zO(e){if(Oe(e)||we(e))return e.text}function YO(e){if(!Cf(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function JO(e){let t=[],n=[];for(let r of e)Cf(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function QO(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function XO(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var ZO=new Set(["todoread","context_info"]);function ln(e){return!ZO.has(ge(e)?e.name:e.tool)}var eD=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function wr(e){let t=ge(e)?oe(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=ae(n);if(r==="task"||r==="delegate"){let s=t.state?.metadata?.sessionId;if(typeof s=="string"&&s)return s;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return tD(n,t.state)}function tD(e,t){let n=Z(e);if(eD.has(n)){let r=t?.title?.match(/\bses_[a-zA-Z0-9]+/);return r?r[0]:t?.output?.match(/\bses_[a-zA-Z0-9]+/)?.[0]}if(n==="session_spawn"||n==="session_start_background")return t?.output?.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/)?.[1]}function nD(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return fe(n.error)}}function rD(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)ee(r)&&ln(r)&&t.push(r);return t}var sD={webfetch:{icon:"globe",title:"Web Fetch",subtitle:e=>e.url},websearch:{icon:"search",title:"Web Search",subtitle:e=>e.query},web_search:{icon:"search",title:"Web Search",subtitle:e=>e.query},scrape_webpage:{icon:"globe",title:"Scrape",subtitle:e=>e.urls?.split?.(",")[0]},image_search:{icon:"image",title:"Image Search",subtitle:e=>e.query},image_gen:{icon:"image",title:"Image Gen",subtitle:e=>e.prompt?.slice?.(0,40)},video_gen:{icon:"cpu",title:"Video Gen",subtitle:e=>e.prompt?.slice?.(0,40)},presentation_gen:{icon:"presentation",title:e=>{let t=e.action||"";return{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[t]||"Presentation"},subtitle:e=>e.slide_title||e.presentation_name},show:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},show_user:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},task:{icon:"square-kanban",title:e=>`Agent (${e.subagent_type||"task"})`,subtitle:e=>sS(e)},session_spawn:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},session_start_background:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},apply_patch:{icon:"file-pen",title:"Patch",subtitle:e=>e.files?.length?`${e.files.length} file${e.files.length>1?"s":""}`:void 0},todoread:{icon:"check-square",title:"Todos (read)"},prune:{icon:"scissors",title:"DCP Prune",subtitle:e=>e.reason},distill:{icon:"scissors",title:"DCP Distill"},compress:{icon:"scissors",title:"DCP Compress",subtitle:e=>e.topic},context_info:{icon:"scissors",title:"Context Info"},session_read:{icon:"glasses",title:e=>`Session Read (${e.mode||"summary"})`,subtitle:e=>e.session_id?.slice(-12)},session_search:{icon:"search",title:"Session Search",subtitle:e=>e.query},session_message:{icon:"message-circle",title:"Message \u2192 Session",subtitle:e=>e.session_id?.slice(-12)},session_lineage:{icon:"list-tree",title:"Session Lineage",subtitle:e=>e.session_id?.slice(-12)},session_list_background:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_list_spawned:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_stats:{icon:"layers",title:"Session Stats",subtitle:e=>e.session_id?.slice(-12)||"current"},session_list:{icon:"list",title:"Session List",subtitle:e=>e.search},session_get:{icon:"book-open",title:"Session Get",subtitle:e=>e.session_id?.slice(-12)},session_context:{icon:"book-open",title:"Session Context",subtitle:e=>e.session_id?.slice(-12)},project_delete:{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:e=>e.project},project_list:{icon:"folder",title:"Projects"},project_get:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_update:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_select:{icon:"folder",title:"Project Select",subtitle:e=>e.project},project_create:{icon:"folder-plus",title:"Project Create",subtitle:e=>e.name},triggers:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_create:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_list:{icon:"clock",title:"List Triggers"},trigger_get:{icon:"clock",title:"Trigger Details",subtitle:e=>e.name||e.id},trigger_delete:{icon:"clock",title:"Delete Trigger",subtitle:e=>e.name||e.id},trigger_update:{icon:"clock",title:"Update Trigger",subtitle:e=>e.name||e.id},trigger_test:{icon:"clock",title:"Test Trigger",subtitle:e=>e.name||e.id},trigger_pause:{icon:"clock",title:"Pause Trigger",subtitle:e=>e.name||e.id},trigger_resume:{icon:"clock",title:"Resume Trigger",subtitle:e=>e.name||e.id},agent_spawn:{icon:"cpu",title:e=>`Agent (${e.agent_type||"worker"})`,subtitle:e=>e.description},agent_message:{icon:"message-circle",title:"Agent Message",subtitle:e=>e.agent_id},agent_stop:{icon:"ban",title:"Agent Stop",subtitle:e=>e.agent_id},agent_status:{icon:"layers",title:"Agent Status"},agent_task:{icon:"check-square",title:"Create Task",subtitle:e=>e.title},agent_task_update:{icon:"check-square",title:"Update Task",subtitle:e=>e.task_id},agent_task_list:{icon:"check-square",title:"List Tasks"},agent_task_get:{icon:"check-square",title:"Task Details",subtitle:e=>e.task_id},task_create:{icon:"plus",title:"Create Task",subtitle:e=>e.title},task_list:{icon:"list",title:"Tasks",subtitle:e=>e.status||"all"},task_update:{icon:"refresh-cw",title:"Update Task",subtitle:e=>e.id},task_done:{icon:"check-circle",title:"Task Done",subtitle:e=>e.id},task_delete:{icon:"trash-2",title:"Delete Task",subtitle:e=>e.id},pty_spawn:{icon:"terminal",title:"Spawn",subtitle:e=>e.title||e.command},pty_read:{icon:"terminal",title:"Terminal Output",subtitle:e=>e.id},pty_write:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_input:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_kill:{icon:"terminal",title:"Kill Process",subtitle:e=>e.id}};function oD(e,t={}){let n=sD[Z(e)];if(!n)return iD(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function iD(e,t){switch(ae(e)){case"read":return{icon:"glasses",title:"Read",subtitle:nS(ve(t))};case"list":return{icon:"list",title:"List",subtitle:rS(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:Rf(ve(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Rf(ve(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function nS(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Rf(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function rS(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function aD(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function xr(e,t=120){if(typeof e!="string")return"";let n=e.split(`
78
- `).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function sS(e){let t=xr(e.description);if(t)return t;let n=xr(e.title,80);if(n)return n;let r=xr(e.message);if(r)return r;let s=xr(e.prompt);if(s)return s;let o=xr(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function cD(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function lD(e,t){return e.find(n=>n.tool?.callID===t)}function uD(e,t){return e.find(n=>n.tool?.callID===t)}var pD=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function Tf(e){return e?e.replace(pD,""):""}function vo(e){let t=oS(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?oS(r):void 0;return s?[s]:[]})}function oS(e){let t=e?.oldString??e?.old_string??e?.oldText,n=e?.newString??e?.new_string??e?.newText;return typeof t=="string"&&typeof n=="string"?[t,n]:void 0}var dD={bash:"Shell",pty_spawn:"Spawn Terminal",pty_read:"Terminal Output",pty_write:"Terminal Input",pty_input:"Terminal Input",pty_kill:"Kill Process",read:"Read File",list:"List Directory",ls:"List Directory",write:"Write File",edit:"Edit File",multiedit:"Edit File",morph_edit:"Edit File",apply_patch:"Apply Patch",patch:"Apply Patch",grep:"Search Code",glob:"Find Files",image_search:"Image Search",session_search:"Search Sessions",webfetch:"Fetch Page",scrape_webpage:"Scrape Page",websearch:"Web Search",web_search:"Web Search",image_gen:"Generate Image",video_gen:"Generate Video",task:"Delegate to Agent",todowrite:"Plan Tasks",todoread:"Read Plan",question:"Ask Question",presentation_gen:"Presentation",show:"Show Output",show_user:"Show Output",prune:"Prune Context",distill:"Distill Context",compress:"Compress Context",context_info:"Context Info"},gD={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",script:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function mD(e){return e.replace(/^oc[-_]/,"")}function If(e){return mD(e).replace(/-/g,"_")}function Ef(e){return If(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Ao(e){return{label:dD[If(e)]??Ef(e),category:gD[ae(e)]}}var fD=256*1024;function yD(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function hD(e){if(e===void 0)return{};if(e.length>fD)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function _D(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?fe(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var pe=e=>typeof e=="string"?e:void 0,Ro=e=>typeof e=="number"?e:void 0,Co=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function Mf(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var bD=new Set(["add","update","delete","move"]);function PD(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=Co(d),m=g&&(pe(g.relativePath)||pe(g.filePath));if(!g||!m)return[];let f=pe(g.type);return[Mf({path:m,type:f&&bD.has(f)?f:void 0,before:pe(g.before),after:pe(g.after),patch:pe(g.patch)??pe(g.diff),additions:Ro(g.additions),deletions:Ro(g.deletions),movePath:pe(g.movePath)})]});return p.length?p:void 0}let r=ve(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[Mf({path:r,after:pe(t.content)})];if(e!=="edit")return;let s=Co(n.filediff),o=s?void 0:pe(n.patch),i=o?SD(o):void 0,a=s||o?[]:vo(t);return[Mf({path:r,before:pe(s?.before)??(a.length?a.map(([c])=>c).join(`
79
- `):void 0),after:pe(s?.after)??(a.length?a.map(([,c])=>c).join(`
80
- `):pe(t.new_source)),patch:o,additions:Ro(s?.additions)??i?.additions,deletions:Ro(s?.deletions)??i?.deletions})]}function SD(e){let t=0,n=0;for(let r of e.split(`
81
- `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function xD(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function iS(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=hD(r),i=yD(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=_D(s);m&&(i="error",a=m)}let c=ae(e),p=t.input??{},d="metadata"in t&&Co(t.metadata)||{},g=Co(d.diagnostics);return{name:e,kind:c,title:n||Ao(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:PD(c,p,d),diff:pe(d.patch)??pe(d.diff),diagnostics:g,answers:c==="question"?xD(d):void 0,childSessionId:wr({tool:e,state:t})}}function Of(e){let t=ge(e)?oe(e):e;return iS(t.tool,t.state)}function wD(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function kD(e){return{kind:"reasoning",id:e.id,text:e.text}}function vD(e){return{kind:"tool",id:e.id,tool:iS(e.tool,e.state)}}function AD(e){let t=e.mime;return{kind:"file",id:e.id,filename:e.filename,mime:t,url:e.url,isImage:t.startsWith("image/"),isPdf:t==="application/pdf"}}function RD(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function CD(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function TD(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function ID(e){return{kind:"agent",id:e.id,name:e.name}}function ED(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:fe(e.error),createdAt:e.time.created}}function MD(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function OD(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function DD(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Df(e){switch(e.type){case"text":return wD(e);case"reasoning":return kD(e);case"tool":return vD(e);case"file":return AD(e);case"subtask":return RD(e);case"patch":return CD(e);case"snapshot":return TD(e);case"agent":return ID(e);case"retry":return ED(e);case"compaction":return MD(e);case"step-start":return OD(e);case"step-finish":return DD(e);default:return{kind:"unknown",raw:e}}}function jD(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=Pe(e);return{name:t,message:n?.message||fe(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function LD(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function To(e){let t=e.parts.map(Df),n=e.info.role==="assistant"?e.info.error:void 0,r=jD(n),s=!r&&!t.some(LD);return{parts:t,error:r,isEmpty:s}}var jf=Ve+BigInt(1),aS=jf/BigInt(2);function Io(e){return BigInt(Math.trunc(e))*zt}function Lf(e,t){let r=t-(t&Ve)+e;return r-t>aS?r-=jf:t-r>aS&&(r+=jf),r}function cS(e,t){let n=Tt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return Lf(n,t);let s=Io(r),o=Lf(n,s);return(o>s?o-s:s-o)<=it?o:s}function lS(e){return Tt(e)===null?1:0}function uS(e,t){return e<t?-1:e>t?1:0}function $D(e,t){return Eo(e,t,Io(Date.now()))}function $f(e){let t=null;for(let n of e){let r=n.info.time?.created;typeof r=="number"&&(t===null||r>t)&&(t=r)}return Io(t??Date.now())}function Eo(e,t,n){let r=lS(e.info.id),s=lS(t.info.id);if(r!==s)return r-s;if(r===0){let a=cS(e,n),c=cS(t,n);return a!==c?a<c?-1:1:uS(e.info.id,t.info.id)}let o=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return o===null&&i===null?0:o===null?1:i===null?-1:o!==i?o<i?-1:1:uS(e.info.id,t.info.id)}function UD(e){let t=new Map;for(let n of e){if(!n.parentID)continue;let r=t.get(n.parentID);r?r.push(n.id):t.set(n.parentID,[n.id])}return t}function FD(e){let t=e-6e4;return(n,r)=>{let s=n.time.updated??n.time.created,o=r.time.updated??r.time.created,i=s>t,a=o>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:o-s}}function pS(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let s of n)r.push(s),r.push(...pS(e,s));return r}function ND(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=$f(e),s=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:Eo(d,g,r)}),o=[],i=new Map;for(let d of s)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};o.push(g),i.set(d.info.id,g)}let a=null,c=[],p=[];for(let d of s){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=c[c.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):c.push({userMessage:BD(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=o[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;o.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...o]:o}var kr=new Map,KD=256;function BD(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=kr.get(s);if(o)return o;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(kr.size>=KD){let a=kr.keys().next().value;a!==void 0&&kr.delete(a)}return kr.set(s,i),i}function qD(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function GD(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Oe(n)&&n.text?.trim())return n}}function WD(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function VD(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!ee(o))continue;let i=o,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:o,message:s})}return r}function dS(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function Uf(e){if(!e?.length)return!1;for(let t=e.length-1;t>=0;t--){let n=e[t].info;if(n.role==="assistant")return!n.time?.completed&&dS(n.error)}return!1}function Ff(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Nf(e){let t=e.trim();return t.length>500?!1:!!(/^Error:\s/i.test(t)||/^([\w._-]+Error|[\w._-]+Exception):\s/i.test(t)||/Traceback \(most recent call last\)/i.test(t)||/^\s*\[\s*\{[\s\S]*"message"\s*:/.test(t))}function HD(e){return!!e&&(Nf(e)||Kf(e)!==null)}function Mo(e){let t=ge(e)?oe(e):e,n=gS.get(t);if(n&&n.state===t.state)return n.outcome;let r=zD(t);return gS.set(t,{state:t.state,outcome:r}),r}var gS=new WeakMap;function zD(e){let t=e.state;if(t.status==="error")return"failed";if(t.status!=="completed")return"ok";let n=typeof t.output=="string"?t.output.trim():"";if(!n)return"ok";if(Nf(n))return"failed";let r=YD(n);return r===void 0?"ok":JD(r)?"failed":QD(r)}function YD(e){try{return JSON.parse(e)}catch{return}}function JD(e){return Ff(e)&&e.success===!1&&typeof e.error=="string"}function QD(e){let t=Ff(e)?e.results:void 0;if(!Array.isArray(t)||t.length===0)return"ok";let n=t.filter(r=>r!==null&&typeof r=="object"&&r.success===!1).length;return n===0?"ok":n===t.length?"failed":"partial"}function Kf(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Ff(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},s=xo(r.errorSummary);if(s===null)return r;try{let o=JSON.parse(s);typeof o.message=="string"&&o.message.trim()&&(r.nestedMessage=o.message.trim()),typeof o.status=="number"&&(r.status=o.status),typeof o.error=="boolean"&&(r.nestedError=o.error)}catch{}return r}function XD(e){return YP(e).replace(/\s+/g," ").trim()||e.trim()}function ZD(e){let t=Kf(e);if(!t)return null;let n=[];return n.push(t.errorSummary),t.nestedMessage!==void 0&&n.push(`Details: ${t.nestedMessage}`),t.hint&&n.push(`Hint: ${t.hint}`),n.join(`
82
-
83
- `)}function ej(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function tj(e,t=2e3){let n=(e??"").trim();try{let r=JSON.parse(n);if(typeof r=="string")try{r=JSON.parse(r)}catch{}r&&typeof r=="object"&&(n=JSON.stringify(r,null,2))}catch{}return n.length>t?{text:n.slice(0,t).trimEnd(),truncatedChars:n.length-t}:{text:n,truncatedChars:0}}function nj(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=QP(n),n=XP(n),n=n.replace(/[#*_`>]+/g," "),n=n.replace(/\s+/g," ").trim(),n=n.replace(/\b(\w{2,})(?:\s+\1\b)+/gi,"$1"),n.length>t?n.slice(0,t).trimEnd()+"\u2026":n}function rj(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let s=r.error.trim(),o;for(let i=0;i<3;i++){let a=xo(s);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(o=c.status),typeof c.message=="string"&&c.message.trim())s=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())s=c.error.trim();else break}return{message:s,status:o}}function vr(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Oo(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},o=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=o.exec(e))!==null;)if(s(vr(i[1]),vr(i[2]),i[3]?vr(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(s(vr(i[2]),vr(i[1])),n.length>=t)return n}return n}function pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mS(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{let r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{}return null}}function Do(e){return e.filter(t=>pt(t)&&!!t.title&&!!t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function Bf(e){if(!e)return[];let t=mS(e,!0),n=t&&!Array.isArray(t)?t:void 0;if(n?.success===!1)return[];let r=n&&Array.isArray(n.results)?n.results:void 0;if(r&&r.length>0){let s=r[0];if(pt(s)&&typeof s.query=="string"){let o=[];for(let i of r)!pt(i)||typeof i.query!="string"||o.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?Do(i.results):[]});if(o.length>0)return o}else if(pt(s)&&(s.title||s.url)){let o=Do(r);if(o.length>0)return[{query:n?.query||"",answer:n?.answer||void 0,sources:o}]}}if(n?.query&&typeof n.query=="string")return[{query:n.query,answer:n.answer||void 0,sources:r?Do(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(pt(s)&&(s.title||s.url)){let o=Do(t);if(o.length>0)return[{query:"",sources:o}]}}if(typeof e=="string"){let s=e.split(/(?=^Title: )/m).filter(Boolean),o=[];for(let i of s){let a=i.match(/^Title:\s*(.+)/m),c=i.match(/^URL:\s*(.+)/m),p=i.match(/^Author:\s*(.+)/m),d=i.match(/^Published Date:\s*(.+)/m),g=i.match(/^Text:\s*([\s\S]*?)$/m);a&&c&&o.push({title:a[1].trim(),url:c[1].trim(),snippet:g?.[1]?.trim()||void 0,author:p?.[1]?.trim()||void 0,publishedDate:d?.[1]?.trim()||void 0})}if(o.length>0)return[{query:"",sources:o}]}if(typeof e=="string"){let s=Oo(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function jo(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function sj(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return jo(e)}}function oj(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function ij(e){if(!e)return!1;let t=e.slice(0,600).toLowerCase();return t.includes("<!doctype html")||t.includes("<html")?!0:/<\/(body|head|div|p|span|table)>/i.test(e.slice(0,3e3))}function fS(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let s=r.trim();/^https?:\/\//i.test(s)&&n.push(s)}return n}return[]}function yS(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=ZP(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function aj(e,t){let n=hS(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?yS(r,fS(t)):[]}function hS(e){if(!e)return null;let t=mS(e),n=t&&!Array.isArray(t)?t:void 0;if(!n)return null;if(n.results&&Array.isArray(n.results)){let r=n.results;return{total:n.total||r.length,successful:n.successful??r.filter(s=>pt(s)&&s.success!==!1).length,failed:n.failed??r.filter(s=>pt(s)&&s.success===!1).length,results:r.map(s=>{let o=pt(s)?s:{};return{url:o.url||"",success:o.success!==!1,title:o.title||void 0,content:o.content||o.text||o.snippet||void 0,error:o.error||void 0}})}}if(typeof e=="string"){let r=Oo(e);if(r.length>0)return{total:r.length,successful:r.length,failed:0,results:r.map(s=>({url:s.url,success:!0,title:s.title||void 0,content:s.snippet||void 0}))}}return null}function cj(e){if(typeof e!="string"||!e.trim())return null;try{let t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"?t.toString():null}catch{return null}}var lj={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",script:"script",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function pn(e){return lj[ae(e)]}function Rr(e){let t=Z(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var uj={run:"Terminal",memory:"Memory"};function pj(e){let t=pn(e);return(t==="hidden"?void 0:uj[t])??Rr(e)}function Ar(e,t,n){return e===1?t:n}function qf(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function PS(e){return e.length?ko(e[0]):""}function De(e){return(e.state??{}).input??{}}var dj={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function gj(e){let t=Z(e.tool);if(t==="agent_task_update"||t==="task_update")switch(De(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return dj[t]??"message"}function _S(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function mj(e){let t=Z(e.tool);if(t==="triggers"){let r=De(e).action||"list";return _S(r)}let n=t.match(/^trigger_(.+)$/);return _S(n?n[1]:"list")}var fj={connector_setup:"connect",connector_get:"read",connector_list:"read",kortix_connector_discover:"read",kortix_connector_describe:"read",kortix_connectors:"read",kortix_connectors_connectors:"read",kortix_connectors_discover:"read",kortix_connectors_describe:"read",kortix_connector_call:"call",kortix_connectors_call:"call"};function yj(e){return fj[Z(e.tool)]??"read"}var hj={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function _j(e){return hj[Z(e.tool)]??"open"}function un(e){return e.every(t=>t===e[0])}var bj={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function Pj(e){if(Z(e.tool)!=="memory")return"read";let n=De(e).command;return n&&bj[n]||"unknown"}var Sj={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},xj={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function wj(e){let t=Qe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function kj(e){let t=De(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return vj(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return wj(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=cj(o);return i?jo(i):"a link"}return""}function vj(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function Aj(e){let t=De(e).action;return t&&Sj[t]||"Worked on an image"}function Rj(e){let t=De(e).action;return t&&xj[t]||"Worked on a presentation"}function Cj(e){return e.slice(0,e.indexOf(":"))}var Tj={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},Ij={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function Ej(e){let t=Z(e.tool);if(t==="image_gen"){let n=De(e).action;return n&&Tj[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=De(e).action;return n&&Ij[n]||"presentation:unknown"}return"shown:result"}var Mj=new Set(["create_slide","export_pdf","export_pptx"]);function Oj(e){let t=qe(e),n=Z(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=De(t).action;return r?Mj.has(r)?"presentation":null:"presentation"}return null}var Dj={"image:generate":e=>`Made ${e} images`,"image:edit":e=>`Edited ${e} images`,"image:upscale":e=>`Upscaled ${e} images`,"image:remove_bg":e=>`Removed backgrounds from ${e} images`,"image:unknown":e=>`Worked on ${e} images`,"video:create":e=>`Made ${e} videos`,"presentation:create_slide":e=>`Added ${e} slides`,"presentation:delete_slide":e=>`Deleted ${e} slides`,"presentation:delete_presentation":e=>`Deleted ${e} presentations`,"presentation:list_slides":()=>"Checked a presentation's slides","presentation:list_presentations":()=>"Checked your presentations","presentation:validate_slide":()=>"Checked slides","presentation:export_pdf":e=>`Exported ${e} presentations to PDF`,"presentation:export_pptx":e=>`Exported ${e} presentations to PPTX`,"presentation:preview":e=>`Previewed ${e} presentations`,"presentation:unknown":e=>`Worked on ${e} presentations`,"shown:result":e=>`Showed you ${e} results`},bS={image:"image",video:"video",presentation:"presentation",shown:"result"};function jj(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[Cj(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Ar(s,bS[r],`${bS[r]}s`)}`)}),`Worked on ${qf(n)}`}function Cr(e,t){let n=t.map(qe),r=n.length,s=PS(n);switch(e){case"explore":{let o=n.filter(i=>Z(i.tool)==="read").length;return o===r?`Read ${r} ${Ar(r,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(n.map(a=>ve(De(a))).filter(Boolean)).size||r,i=n.every(a=>Z(a.tool)==="write")?"Wrote":"Updated";return o===1?s?`${i} ${s}`:`${i} a file`:`${i} ${o} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let o=p=>{let d=Z(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(o).length;if(i===r)return`Searched the web \xB7 ${r} ${Ar(r,"query","queries")}`;if(i===0)return`Read ${r} ${Ar(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of Bf(d).flatMap(m=>m.sources))g.url&&a.add(g.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let c=a.size||r;return`Searched and read ${c} ${Ar(c,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=Z(i.tool);if(a==="image_gen")return Aj(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return Rj(i);let c=kj(i);return c?`Showed you ${c}`:"Showed you the result"}let o=n.map(Ej);return un(o)?Dj[o[0]](r):jj(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(gj);if(un(o))switch(o[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=n.map(Pj);if(un(o))switch(o[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=n.map(yj);if(un(o))switch(o[0]){case"connect":return r===1?s?`Connected to ${s}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=n.map(mj);if(un(o))switch(o[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=n.map(_j);if(un(o))switch(o[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?s?`Created ${s}`:"Created a project":`Created ${r} projects`;case"update":return r===1?s?`Updated ${s}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?s?`Opened ${s}`:"Opened your project":`Opened ${r} projects`}return s?`Worked in ${s}`:"Worked in your project"}case"skills":return r===1?s?`Used the ${s} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${Rr(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>Rr(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${qf(o)}`}}}function Gf(e,t){let n=t.map(qe),r=PS(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=Z(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>Rr(a.tool))));return`Couldn't finish using ${qf(i)}`}}}var SS=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),Lj={read:{verb:"Read",running:"Reading",objectKeys:["filePath","path","file"]},write:{verb:"Wrote",running:"Writing",objectKeys:["filePath","path","file"]},edit:{verb:"Edited",running:"Editing",objectKeys:["filePath","path","file"]},apply_patch:{verb:"Edited",running:"Editing",objectKeys:["filePath","path"]},bash:{verb:"Ran",running:"Running",objectKeys:["command"]},glob:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},grep:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},list:{verb:"Listed",running:"Listing",objectKeys:["path"]},web_search:{verb:"Searched",running:"Searching",objectKeys:["query"]},websearch:{verb:"Searched",running:"Searching",objectKeys:["query"]},webfetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},web_fetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},scrape:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},scrape_webpage:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},task:{verb:"Delegated",running:"Delegating",objectKeys:["description"]},memory:{verb:"Remembered",running:"Remembering"},get_mem:{verb:"Recalled",running:"Recalling"},memory_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},mem_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},ltm_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},dcp_compress:{verb:"Compacted",running:"Compacting"},dcp_distill:{verb:"Distilled",running:"Distilling"},dcp_prune:{verb:"Pruned",running:"Pruning"},compress:{verb:"Compacted",running:"Compacting"},distill:{verb:"Distilled",running:"Distilling"},prune:{verb:"Pruned",running:"Pruning"},context_info:{verb:"Checked context",running:"Checking context"}};function $j(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&br(t)||t}function Uj(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let s=n[r];if(typeof s=="string"&&s.trim())return $j(r,s.trim())}}function dn(e){let t=ge(e)?oe(e):e;if(we(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!ee(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=me(t.tool),r=Lj[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:Uj(s,r.objectKeys),tier:SS.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function Lo(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(dn(o).tier==="plumbing"){r=!0;continue}if(we(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,ee(o)&&Mo(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function Wf(e){return`${e} ${e===1?"step":"steps"}`}function xS(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${Wf(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${Wf(n)}`:s===0?`${Wf(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function Vf(e){let t=new Map,n=0;for(let s of e){if(!ee(s)||dn(s).tier==="plumbing")continue;let o=pn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),Mo(s)!=="ok"&&(n+=1))}if(t.size===0)return xS(Lo(e),!1);let r=[...t].map(([s,o],i)=>{let a=Cr(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function Fj(e){let t=!1,n=!1,r=!1,s=null,o=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),s==null&&d.error!=null&&(s=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(t=!0),e.userMessage&&o(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)o(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function Nj(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function Kj(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let s=r.state.time;typeof s?.start=="number"&&(t=Math.min(t,s.start)),typeof s?.end=="number"&&(n=Math.max(n,s.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function wS(e,t){let n=t.map(qe),r=Nj(n);return{id:n[0].callID,family:e,label:r==="error"?Gf(e,n):Cr(e,n),parts:t,status:r,durationMs:r==="running"?void 0:Kj(n)}}function Hf(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(wS(n,r)),n=null,r=[]};for(let o of e){let i=qe(o),a=pn(i.tool);if(a!=="hidden"&&!Bs(i)){if(Zg(i.tool)){s(),t.push(wS(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function $o(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function zf(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of Hf(s))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});s=[]}};for(let a of e)if(t(a)!=="plumbing"){if(we(a)){let c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=$o(a);continue}if(o(),ee(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var Bj=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function qj(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]*)`/g,"$1").replace(/^#{1,6}\s*/gm,"").replace(/\*\*([^*]*)\*\*/g,"$1").replace(/(^|\s)[*_]([^*_]+)[*_]/g,"$1$2").replace(/^\s*[-*+]\s+/gm,"").replace(/\s+/g," ").trim()}function Gj(e){let t=e.flatMap(s=>{let o=qj(s);return o?[o]:[]}).join(" ").trim();return t?Bj.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function CS(e){return e?.info?.time??{}}function Wj(e){let t=CS(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Uo=6e4,Vj=10080*Uo,kS=1440;function vS(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function Hj(e,t){let n=t.getTime()-e.getTime(),r=n/Uo,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<kS)return s(Math.round(r/60),"hour");let o=(n-(vS(t)-vS(e)))/Uo;return s(Math.round(o/kS),"day")}function TS(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}var AS=new Map;function zj(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=AS.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),AS.set(r,s)),s}function Fo(e,t,n){return zj(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?Yj(r.value,n):r.value).join("")}function Yj(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function RS(e,t){return Fo(e,{year:"numeric"},t)}function Jj(e,t,n={}){let r=TS(e);if(!r)return"";let s=i=>Fo(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return s(!0);let o=Math.max(0,t-r.getTime());return o<Uo?"just now":o<Vj?Hj(r,new Date(t)):s(RS(r,n)!==RS(new Date(t),n))}function Qj(e,t={}){let n=TS(e);if(!n)return"";let r=Fo(n,{month:"long",day:"numeric",year:"numeric"},t),s=Fo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function Yf(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!em(o)){if(Oe(o)){s(),n.push({kind:"text",part:o});continue}if(ee(o)&&(tm(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function Xj(e){let t=me(e);return t==="show"||t==="show_user"}function Jf(e,t={}){let n=[],r=[],s=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(o=>o.part)}),r=[]};for(let o of e){if(o.kind==="standalone"&&Xj(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var Zj=["title","description","path","url","content","language","aspect_ratio","attachment"];function IS(e,t){if(!t||typeof t!="object")return null;let n=t;if(Yn(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of Zj){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function eL(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function Qf(e){let t=[];for(let n of e){let r=n.state,s=r.input??{};if(r.status==="error"){let a=typeof s.title=="string"&&s.title?s.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let o=eL(s.items),i=o?o.map(a=>IS(n.callID,a)).filter(a=>!!a):[IS(n.callID,s)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function Xf(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Tr=e=>"id"in e?e.id:e.userMessage.info.id,ES=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,tL=e=>e.time?.completed;function nL(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function rL(e,t){let n=Tr(e);return t.pendingTurnIds.has(n)||ES(e)===0&&t.pendingPromptIds.has(n)}function sL(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Tr(r)));if(t)return Tr(t);let n=e.turns.findIndex(r=>rL(r,e));return n<=0?null:Tr(e.turns[n-1])}function oL(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function iL(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function aL(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Xf({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function cL(e,t){for(let n=e.length-1;n>=0;n--){let r=Tr(e[n]);if(t(r))return ES(e[n])===0?r:null}return null}function Zf(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),s=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),o=e.hintMessageId??null;if(o){if(n>=0&&t[n].userMessage.info.id===o)return s(n);let a=r.indexOf(o);if(a>=0)return s(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!tL(c.info)&&!c.info.error)return s(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return s(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:s(n)}function lL(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].info.role==="user")return t[n].info.id===e;return!1}function uL(e,t){return!t||!e?!1:e.type!=="idle"}function pL(e,t){return!e&&!!t}function dL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Pe(n.error)?.message||fe(n.error)}}function gL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return _r(n.error)}}function mL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Pe(n.error)}}function ey(e){if(e){if(ee(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(we(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(Oe(e))return"Gathering thoughts..."}}var fL=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function yL(e){if(!(!e||e.length===0))for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.info.role==="assistant")for(let r=n.parts.length-1;r>=0;r--){let s=ey(n.parts[r]);if(s)return s}}}function hL(e,t){let n=ee(e)?e:void 0;if(n&&fL.has(n.tool)&&n.state.status==="running"){let r=yL(t);return r||(t?.length?"Handing off to an agent...":void 0)}return ey(e)}function ty(e,t){for(let n=e.length-1;n>=0;n--){let r=hL(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function ny(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}var ry=1.055;function MS(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),s=e.cache?.read??0,o=e.cache?.write??0,i=Math.max(0,n-s-o),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,s>0&&(p+=s/1e6*(c.cacheReadPer1M??c.inputPer1M)),o>0&&(p+=o/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function sy(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function OS(e,t,n,r){if(sy(t,n))return 0;let s=e.cost||0;if(s>0)return s;if(!r||!t||!n)return 0;let o=r(t,n);return o?MS(e.tokens,o):0}function DS(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function No(e,t){let n=0,r=0,s=0,o=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let g=p,{providerID:m,modelID:f}=DS(d.info);n+=OS(g,m,f,t),r+=g.tokens?.input||0,s+=g.tokens?.output||0,o+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=jS(g,t),f=g.tokens&&sy(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let _=g.tokens;_&&(r+=_.input??0,s+=_.output??0,o+=_.reasoning??0,i+=_.cache?.read??0,a+=_.cache?.write??0)}}if(c)return{cost:n*ry,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function jS(e,t){if(sy(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?MS({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function _L(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=DS(s),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=OS(p,o,i,t));c||(a+=jS(s,t)),n+=a}return n*ry}function bL(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function PL(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function SL(e){if(!e||e.type!=="retry")return;let t=e,n=fe(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:Pe(t.message)}}function xL(e){if(!(!e||e.type!=="retry"))return fe(e.message)}function wL(e){return(e.info.summary?.diffs?.length??0)>0}function LS(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=me(e.part.tool);return t==="show"||t==="show_user"}function kL(e){return e.kind==="text"&&!e.part.text?.trim()}function oy(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(LS(o)||kL(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):LS(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function vL(e){let t=e==null?"":ny(e);return t?`Worked for ${t}`:"Worked"}function $S(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>Oe(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return ee(s)&&s.tool==="bash"}function AL(e){if($S(e))return e.assistantMessages[0].parts[0]}function RL(e){if(!e)return"";let t=e;return t=t.replace(/^##\s*Worker Result\s*\n/i,""),t=t.replace(/^\*\*Agent:\*\*.*\n?/m,""),t=t.replace(/^\*\*Task:\*\*.*\n?/m,""),t=t.replace(/^\*\*Status:\*\*.*\n?/m,""),t=t.replace(/^\*\*Session:\*\*.*\n?/m,""),t=t.replace(/^\*\*Duration:\*\*.*\n?/m,""),t=GP(t,"kortix_goal_system"),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created and started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created:.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* failed to start.*$/gm,""),t=t.replace(/^Message sent to task.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* approved.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* cancelled.*$/gm,""),t=t.replace(/Worker session: ses_[a-zA-Z0-9]+/g,""),t=t.replace(/^---\s*\n/gm,""),t=t.trim(),t||""}function CL(e){return e?e.split(`
84
- `).filter(n=>n.trim()).length<=3:!1}function TL(e){if(!e)return null;let n=e.split(`
85
- `).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function IL(e){if(!e)return[];let t=[],n=e.split(`
86
- `).filter(r=>r.trim());for(let r of n){let s=zP(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var dt={write:{verb:"Wrote",running:"Writing",failed:"Couldn't write"},edit:{verb:"Edited",running:"Editing",failed:"Couldn't update"},delete:{verb:"Deleted",running:"Deleting",failed:"Couldn't delete"},rename:{verb:"Renamed",running:"Renaming",failed:"Couldn't rename"},change:{verb:"Changed",running:"Changing",failed:"Couldn't apply"},read:{verb:"Read",running:"Reading",failed:"Couldn't read"},list:{verb:"Listed",running:"Listing",failed:"Couldn't list"}};function EL(e,t){let n=dt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function ML(e,t){return t?"failed":e?"running":"done"}var OL={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function DL(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function jL(e,t){if(!e)return null;let n=e.indexOf(`
87
- `),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(VP(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
77
+ `)&&(n=n.slice(0,-1)),n)}function Hf(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let o=e.indexOf(">",r+1+t.length);return o===-1?null:{open:r,end:o}}function lS(e,t){let n=Hf(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function uS(e,t){let n=Hf(e,t);if(!n)return null;let r=e.indexOf(`</${t}>`,n.end+1);return r===-1?null:e.slice(n.end+1,r)}function pS(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=Hf(e,t,o);if(!s)break;let i=e.indexOf(n,s.end+1);if(i===-1)break;r+=e.slice(o,s.open),o=i+n.length}return r+e.slice(o)}function dS(e,t,n){let r=[];for(let o of e.split(/[\n\r\u2028\u2029]/)){let s=0;for(;;){let i=o.indexOf(t,s);if(i===-1)break;let a=o.indexOf(n,i+t.length);if(a===-1)break;r.push(o.slice(i+t.length,a)),s=a+n.length}}return r}function Rs(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&ye(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function gS(e,t,n){let r=Mt(t),o=Mt(n);for(let s of Mt(e).split(/[\n\r\u2028\u2029]/)){let i=s.indexOf(r);if(i!==-1&&s.lastIndexOf(o)>=i+r.length)return!0}return!1}function mS(e,t){let n=Mt(e),r=t.map(Mt),o=e.length,s=l=>{let p=l;for(;p<o&&ye(e[p]);)p++;return p},i=l=>{for(let p=l;p<o;p++)if(Ir(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=o;){let l=s(a);if(l>=o)return null;let p=r.find(d=>n.startsWith(d,l));if(p!==void 0){let d=s(l+p.length);if(e[d]===":"){let g=s(d+1);if(g<o){let m=g;for(;m<o&&!Ir(e[m]);)m++;for(;m>g+1&&ye(e[m-1]);)m--;return e.slice(g,m)}for(let m=o-1;m>d;m--)if(!Ir(e[m]))return e[m];return null}}a=i(l)}return null}function fS(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=ye(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!ye(e[a-1]))continue;let l=a+1;if(ye(e[l])){for(;l<t&&ye(e[l]);)l++;Gf(e[l])&&(r[a]=a)}}let o=new Array(t+1);o[0]=0;for(let a=0;a<t;a++)o[a+1]=o[a]+(Ir(e[a])?1:0);let s=(a,l)=>o[l]===o[a],i=a=>{let l=a+1;for(;ye(e[l]);)l++;let p=l;for(;p<t&&Gf(e[p]);)p++;return e.slice(l,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let l=a+7;for(;l<t&&/[a-z0-9]/.test(e[l]);)l++;if(l===a+7||e[l]!=="*"||e[l+1]!=="*")continue;let p=l+2,d=p;for(;d<t&&ye(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(s(d,m))return{id:e.slice(a+2,l),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Ir(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function yS(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&ye(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&ye(e[i]);)i++;n=i}let r=e.slice(n),o="",s=0;for(;s<r.length;){if(t(r,s)&&(s===0||!Gf(r[s-1]))){let i=s,a=0;for(;t(r,i);){for(i+=6;i<r.length&&ye(r[i]);)i++;a++}if(a>=2){s=i;continue}}o+=r[s],s++}return o}function hS(e,t){let n=t?"![":"[",r="",o=0,s=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let l=a+n.length;if(s<l&&(s=e.indexOf("]",l)),s===-1)break;let p=s;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(o,a)+(t?" ":e.slice(l,p)),o=i+1,a=e.indexOf(n,o)}return r+e.slice(o)}function _S(e){return hS(e,!0)}function bS(e){return hS(e,!1)}function SD(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function PS(e,t){let n=Mt(e),r=Mt(t),o=e.length,s=i=>{let a=i;for(;a<o&&ye(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=s(i+r.length);if(e[a]!==":")continue;let l=s(a+1);for(let p=l;p<o;){if(!ye(e[p])){p++;continue}let d=s(p);if(SD(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var SS=new Set(["read","glob","grep","list"]);function Z(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function xD(e){return SS.has(ae(e))}function wD(e){let t=0,n=0,r=0;for(let o of e){let s=ae(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function Vf(e){if(!e)return"";let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Cs(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Ts(e){let t=We(e),r=(t.state??{}).input??{};switch(Z(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=ve(r);return i?Vf(i):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${Cs(String(i),40)}" in ${Vf(String(a))}`:i?`"${Cs(String(i),60)}"`:""}case"list":return r.path?Vf(String(r.path)):"";case"bash":return Cs(String(r.command??""),80);default:break}let s=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of s){let a=r[i];if(typeof a=="string"&&a.length>0)return Cs(i==="query"&&Tr(a)||a,60)}return""}var xS={read:"Read",search:"Search",list:"List",shell:"Shell",edit:"Edit",write:"Write",fetch:"Fetch",webSearch:"Web Search",scrape:"Scrape",applyPatch:"Apply Patch",task:"Task",worker:"Worker",workspace:"Workspace"};function kD(e,t={}){let n=ge(e)?se(e):e,r={...xS,...t},o=Z(n.tool),s=Ts(n);switch(o){case"read":return{title:r.read,subtitle:s};case"glob":case"grep":return{title:r.search,subtitle:s};case"list":return{title:r.list,subtitle:s};case"bash":return{title:r.shell,subtitle:s};case"edit":case"morph_edit":return{title:r.edit,subtitle:s};case"write":return{title:r.write,subtitle:s};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:s};case"websearch":case"web_search":return{title:r.webSearch,subtitle:s};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:s};case"apply_patch":return{title:r.applyPatch,subtitle:s};case"task":return{title:r.task,subtitle:s};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:s};case"project_select":case"project_list":return{title:r.workspace,subtitle:s};default:return{title:o.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:s}}}function Oe(e){return e.type==="text"}function we(e){return e.type==="reasoning"}function ee(e){return e.type==="tool"}function Yf(e){return e.type==="file"}function vD(e){return e.type==="agent"}function AD(e){return e.type==="compaction"}function RD(e){return e.type==="snapshot"}function CD(e){return e.type==="patch"}function TD(e){return e.type==="step-start"||e.type==="step-finish"}function ID(e){if(Oe(e)||we(e))return e.text}function ED(e){if(!Yf(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function MD(e){let t=[],n=[];for(let r of e)Yf(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function OD(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function DD(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var LD=new Set(["todoread","context_info"]);function gn(e){return!LD.has(ge(e)?e.name:e.tool)}var jD=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function Or(e){let t=ge(e)?se(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=ae(n);if(r==="task"||r==="delegate"){let o=t.state?.metadata?.sessionId;if(typeof o=="string"&&o)return o;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return $D(n,t.state)}function $D(e,t){let n=Z(e);if(jD.has(n)){let r=t?.title?.match(/\bses_[a-zA-Z0-9]+/);return r?r[0]:t?.output?.match(/\bses_[a-zA-Z0-9]+/)?.[0]}if(n==="session_spawn"||n==="session_start_background")return t?.output?.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/)?.[1]}function UD(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return fe(n.error)}}function FD(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)ee(r)&&gn(r)&&t.push(r);return t}var ND={webfetch:{icon:"globe",title:"Web Fetch",subtitle:e=>e.url},websearch:{icon:"search",title:"Web Search",subtitle:e=>e.query},web_search:{icon:"search",title:"Web Search",subtitle:e=>e.query},scrape_webpage:{icon:"globe",title:"Scrape",subtitle:e=>e.urls?.split?.(",")[0]},image_search:{icon:"image",title:"Image Search",subtitle:e=>e.query},image_gen:{icon:"image",title:"Image Gen",subtitle:e=>e.prompt?.slice?.(0,40)},video_gen:{icon:"cpu",title:"Video Gen",subtitle:e=>e.prompt?.slice?.(0,40)},presentation_gen:{icon:"presentation",title:e=>{let t=e.action||"";return{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[t]||"Presentation"},subtitle:e=>e.slide_title||e.presentation_name},show:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},show_user:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},task:{icon:"square-kanban",title:e=>`Agent (${e.subagent_type||"task"})`,subtitle:e=>vS(e)},session_spawn:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},session_start_background:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},apply_patch:{icon:"file-pen",title:"Patch",subtitle:e=>e.files?.length?`${e.files.length} file${e.files.length>1?"s":""}`:void 0},todoread:{icon:"check-square",title:"Todos (read)"},prune:{icon:"scissors",title:"DCP Prune",subtitle:e=>e.reason},distill:{icon:"scissors",title:"DCP Distill"},compress:{icon:"scissors",title:"DCP Compress",subtitle:e=>e.topic},context_info:{icon:"scissors",title:"Context Info"},session_read:{icon:"glasses",title:e=>`Session Read (${e.mode||"summary"})`,subtitle:e=>e.session_id?.slice(-12)},session_search:{icon:"search",title:"Session Search",subtitle:e=>e.query},session_message:{icon:"message-circle",title:"Message \u2192 Session",subtitle:e=>e.session_id?.slice(-12)},session_lineage:{icon:"list-tree",title:"Session Lineage",subtitle:e=>e.session_id?.slice(-12)},session_list_background:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_list_spawned:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_stats:{icon:"layers",title:"Session Stats",subtitle:e=>e.session_id?.slice(-12)||"current"},session_list:{icon:"list",title:"Session List",subtitle:e=>e.search},session_get:{icon:"book-open",title:"Session Get",subtitle:e=>e.session_id?.slice(-12)},session_context:{icon:"book-open",title:"Session Context",subtitle:e=>e.session_id?.slice(-12)},project_delete:{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:e=>e.project},project_list:{icon:"folder",title:"Projects"},project_get:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_update:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_select:{icon:"folder",title:"Project Select",subtitle:e=>e.project},project_create:{icon:"folder-plus",title:"Project Create",subtitle:e=>e.name},triggers:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_create:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_list:{icon:"clock",title:"List Triggers"},trigger_get:{icon:"clock",title:"Trigger Details",subtitle:e=>e.name||e.id},trigger_delete:{icon:"clock",title:"Delete Trigger",subtitle:e=>e.name||e.id},trigger_update:{icon:"clock",title:"Update Trigger",subtitle:e=>e.name||e.id},trigger_test:{icon:"clock",title:"Test Trigger",subtitle:e=>e.name||e.id},trigger_pause:{icon:"clock",title:"Pause Trigger",subtitle:e=>e.name||e.id},trigger_resume:{icon:"clock",title:"Resume Trigger",subtitle:e=>e.name||e.id},agent_spawn:{icon:"cpu",title:e=>`Agent (${e.agent_type||"worker"})`,subtitle:e=>e.description},agent_message:{icon:"message-circle",title:"Agent Message",subtitle:e=>e.agent_id},agent_stop:{icon:"ban",title:"Agent Stop",subtitle:e=>e.agent_id},agent_status:{icon:"layers",title:"Agent Status"},agent_task:{icon:"check-square",title:"Create Task",subtitle:e=>e.title},agent_task_update:{icon:"check-square",title:"Update Task",subtitle:e=>e.task_id},agent_task_list:{icon:"check-square",title:"List Tasks"},agent_task_get:{icon:"check-square",title:"Task Details",subtitle:e=>e.task_id},task_create:{icon:"plus",title:"Create Task",subtitle:e=>e.title},task_list:{icon:"list",title:"Tasks",subtitle:e=>e.status||"all"},task_update:{icon:"refresh-cw",title:"Update Task",subtitle:e=>e.id},task_done:{icon:"check-circle",title:"Task Done",subtitle:e=>e.id},task_delete:{icon:"trash-2",title:"Delete Task",subtitle:e=>e.id},pty_spawn:{icon:"terminal",title:"Spawn",subtitle:e=>e.title||e.command},pty_read:{icon:"terminal",title:"Terminal Output",subtitle:e=>e.id},pty_write:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_input:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_kill:{icon:"terminal",title:"Kill Process",subtitle:e=>e.id}};function BD(e,t={}){let n=ND[Z(e)];if(!n)return KD(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function KD(e,t){switch(ae(e)){case"read":return{icon:"glasses",title:"Read",subtitle:wS(ve(t))};case"list":return{icon:"list",title:"List",subtitle:kS(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:zf(ve(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:zf(ve(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function wS(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function zf(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function kS(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function qD(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function Mr(e,t=120){if(typeof e!="string")return"";let n=e.split(`
78
+ `).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function vS(e){let t=Mr(e.description);if(t)return t;let n=Mr(e.title,80);if(n)return n;let r=Mr(e.message);if(r)return r;let o=Mr(e.prompt);if(o)return o;let s=Mr(e.agent_id,40);return s?`Agent ${s}`:"Worker task"}function GD(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function WD(e,t){return e.find(n=>n.tool?.callID===t)}function HD(e,t){return e.find(n=>n.tool?.callID===t)}var VD=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function Jf(e){return e?e.replace(VD,""):""}function Is(e){let t=AS(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let o=r&&typeof r=="object"?AS(r):void 0;return o?[o]:[]})}function AS(e){let t=e?.oldString??e?.old_string??e?.oldText,n=e?.newString??e?.new_string??e?.newText;return typeof t=="string"&&typeof n=="string"?[t,n]:void 0}var zD={bash:"Shell",pty_spawn:"Spawn Terminal",pty_read:"Terminal Output",pty_write:"Terminal Input",pty_input:"Terminal Input",pty_kill:"Kill Process",read:"Read File",list:"List Directory",ls:"List Directory",write:"Write File",edit:"Edit File",multiedit:"Edit File",morph_edit:"Edit File",apply_patch:"Apply Patch",patch:"Apply Patch",grep:"Search Code",glob:"Find Files",image_search:"Image Search",session_search:"Search Sessions",webfetch:"Fetch Page",scrape_webpage:"Scrape Page",websearch:"Web Search",web_search:"Web Search",image_gen:"Generate Image",video_gen:"Generate Video",task:"Delegate to Agent",todowrite:"Plan Tasks",todoread:"Read Plan",question:"Ask Question",presentation_gen:"Presentation",show:"Show Output",show_user:"Show Output",prune:"Prune Context",distill:"Distill Context",compress:"Compress Context",context_info:"Context Info"},YD={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",script:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function JD(e){return e.replace(/^oc[-_]/,"")}function Qf(e){return JD(e).replace(/-/g,"_")}function Xf(e){return Qf(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Es(e){return{label:zD[Qf(e)]??Xf(e),category:YD[ae(e)]}}var QD=256*1024;function XD(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function ZD(e){if(e===void 0)return{};if(e.length>QD)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function eL(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,o=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!o))return o?fe(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var pe=e=>typeof e=="string"?e:void 0,Ms=e=>typeof e=="number"?e:void 0,Os=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function Zf(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var tL=new Set(["add","update","delete","move"]);function nL(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=Os(d),m=g&&(pe(g.relativePath)||pe(g.filePath));if(!g||!m)return[];let f=pe(g.type);return[Zf({path:m,type:f&&tL.has(f)?f:void 0,before:pe(g.before),after:pe(g.after),patch:pe(g.patch)??pe(g.diff),additions:Ms(g.additions),deletions:Ms(g.deletions),movePath:pe(g.movePath)})]});return p.length?p:void 0}let r=ve(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[Zf({path:r,after:pe(t.content)})];if(e!=="edit")return;let o=Os(n.filediff),s=o?void 0:pe(n.patch),i=s?rL(s):void 0,a=o||s?[]:Is(t);return[Zf({path:r,before:pe(o?.before)??(a.length?a.map(([l])=>l).join(`
79
+ `):void 0),after:pe(o?.after)??(a.length?a.map(([,l])=>l).join(`
80
+ `):pe(t.new_source)),patch:s,additions:Ms(o?.additions)??i?.additions,deletions:Ms(o?.deletions)??i?.deletions})]}function rL(e){let t=0,n=0;for(let r of e.split(`
81
+ `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function oL(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function RS(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:o,outputText:s}=ZD(r),i=XD(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=eL(o);m&&(i="error",a=m)}let l=ae(e),p=t.input??{},d="metadata"in t&&Os(t.metadata)||{},g=Os(d.diagnostics);return{name:e,kind:l,title:n||Es(e).label,status:i,input:t.input,output:r,outputParsed:o,outputText:s,error:a,files:nL(l,p,d),diff:pe(d.patch)??pe(d.diff),diagnostics:g,answers:l==="question"?oL(d):void 0,childSessionId:Or({tool:e,state:t})}}function ey(e){let t=ge(e)?se(e):e;return RS(t.tool,t.state)}function sL(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function iL(e){return{kind:"reasoning",id:e.id,text:e.text}}function aL(e){return{kind:"tool",id:e.id,tool:RS(e.tool,e.state)}}function cL(e){let t=e.mime;return{kind:"file",id:e.id,filename:e.filename,mime:t,url:e.url,isImage:t.startsWith("image/"),isPdf:t==="application/pdf"}}function lL(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function uL(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function pL(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function dL(e){return{kind:"agent",id:e.id,name:e.name}}function gL(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:fe(e.error),createdAt:e.time.created}}function mL(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function fL(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function yL(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function ty(e){switch(e.type){case"text":return sL(e);case"reasoning":return iL(e);case"tool":return aL(e);case"file":return cL(e);case"subtask":return lL(e);case"patch":return uL(e);case"snapshot":return pL(e);case"agent":return dL(e);case"retry":return gL(e);case"compaction":return mL(e);case"step-start":return fL(e);case"step-finish":return yL(e);default:return{kind:"unknown",raw:e}}}function hL(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=be(e);return{name:t,message:n?.message||fe(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function _L(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function Ds(e){let t=e.parts.map(ty),n=e.info.role==="assistant"?e.info.error:void 0,r=hL(n),o=!r&&!t.some(_L);return{parts:t,error:r,isEmpty:o}}var ny=Ve+BigInt(1),CS=ny/BigInt(2);function Ls(e){return BigInt(Math.trunc(e))*Xt}function ry(e,t){let r=t-(t&Ve)+e;return r-t>CS?r-=ny:t-r>CS&&(r+=ny),r}function TS(e,t){let n=Tt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return ry(n,t);let o=Ls(r),s=ry(n,o);return(s>o?s-o:o-s)<=ct?s:o}function IS(e){return Tt(e)===null?1:0}function ES(e,t){return e<t?-1:e>t?1:0}function bL(e,t){return js(e,t,Ls(Date.now()))}function oy(e){let t=null;for(let n of e){let r=n.info.time?.created;typeof r=="number"&&(t===null||r>t)&&(t=r)}return Ls(t??Date.now())}function js(e,t,n){let r=IS(e.info.id),o=IS(t.info.id);if(r!==o)return r-o;if(r===0){let a=TS(e,n),l=TS(t,n);return a!==l?a<l?-1:1:ES(e.info.id,t.info.id)}let s=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return s===null&&i===null?0:s===null?1:i===null?-1:s!==i?s<i?-1:1:ES(e.info.id,t.info.id)}function PL(e){let t=new Map;for(let n of e){if(!n.parentID)continue;let r=t.get(n.parentID);r?r.push(n.id):t.set(n.parentID,[n.id])}return t}function SL(e){let t=e-6e4;return(n,r)=>{let o=n.time.updated??n.time.created,s=r.time.updated??r.time.created,i=o>t,a=s>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:s-o}}function MS(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let o of n)r.push(o),r.push(...MS(e,o));return r}function xL(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=oy(e),o=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:js(d,g,r)}),s=[],i=new Map;for(let d of o)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};s.push(g),i.set(d.info.id,g)}let a=null,l=[],p=[];for(let d of o){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=l[l.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):l.push({userMessage:kL(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=s[0]??l[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;s.push({userMessage:g,assistantMessages:m})}}return l.length>0?[...l,...s]:s}var Dr=new Map,wL=256;function kL(e,t){let n=t.info,r=n.time?.created,o=`${n.sessionID??""}|${e}|${r??""}`,s=Dr.get(o);if(s)return s;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(Dr.size>=wL){let a=Dr.keys().next().value;a!==void 0&&Dr.delete(a)}return Dr.set(o,i),i}function vL(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function AL(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Oe(n)&&n.text?.trim())return n}}function RL(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function CL(e,t,n){if(n)return[];let r=[];for(let o of e.assistantMessages)for(let s of o.parts){if(!ee(s))continue;let i=s,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:s,message:o})}return r}function OS(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function sy(e){if(!e?.length)return!1;for(let t=e.length-1;t>=0;t--){let n=e[t].info;if(n.role==="assistant")return!n.time?.completed&&OS(n.error)}return!1}function iy(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ay(e){let t=e.trim();return t.length>500?!1:!!(/^Error:\s/i.test(t)||/^([\w._-]+Error|[\w._-]+Exception):\s/i.test(t)||/Traceback \(most recent call last\)/i.test(t)||/^\s*\[\s*\{[\s\S]*"message"\s*:/.test(t))}function TL(e){return!!e&&(ay(e)||cy(e)!==null)}function $s(e){let t=ge(e)?se(e):e,n=DS.get(t);if(n&&n.state===t.state)return n.outcome;let r=IL(t);return DS.set(t,{state:t.state,outcome:r}),r}var DS=new WeakMap;function IL(e){let t=e.state;if(t.status==="error")return"failed";if(t.status!=="completed")return"ok";let n=typeof t.output=="string"?t.output.trim():"";if(!n)return"ok";if(ay(n))return"failed";let r=EL(n);return r===void 0?"ok":ML(r)?"failed":OL(r)}function EL(e){try{return JSON.parse(e)}catch{return}}function ML(e){return iy(e)&&e.success===!1&&typeof e.error=="string"}function OL(e){let t=iy(e)?e.results:void 0;if(!Array.isArray(t)||t.length===0)return"ok";let n=t.filter(r=>r!==null&&typeof r=="object"&&r.success===!1).length;return n===0?"ok":n===t.length?"failed":"partial"}function cy(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!iy(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},o=Rs(r.errorSummary);if(o===null)return r;try{let s=JSON.parse(o);typeof s.message=="string"&&s.message.trim()&&(r.nestedMessage=s.message.trim()),typeof s.status=="number"&&(r.status=s.status),typeof s.error=="boolean"&&(r.nestedError=s.error)}catch{}return r}function DL(e){return yS(e).replace(/\s+/g," ").trim()||e.trim()}function LL(e){let t=cy(e);if(!t)return null;let n=[];return n.push(t.errorSummary),t.nestedMessage!==void 0&&n.push(`Details: ${t.nestedMessage}`),t.hint&&n.push(`Hint: ${t.hint}`),n.join(`
82
+
83
+ `)}function jL(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function $L(e,t=2e3){let n=(e??"").trim();try{let r=JSON.parse(n);if(typeof r=="string")try{r=JSON.parse(r)}catch{}r&&typeof r=="object"&&(n=JSON.stringify(r,null,2))}catch{}return n.length>t?{text:n.slice(0,t).trimEnd(),truncatedChars:n.length-t}:{text:n,truncatedChars:0}}function UL(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=_S(n),n=bS(n),n=n.replace(/[#*_`>]+/g," "),n=n.replace(/\s+/g," ").trim(),n=n.replace(/\b(\w{2,})(?:\s+\1\b)+/gi,"$1"),n.length>t?n.slice(0,t).trimEnd()+"\u2026":n}function FL(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let o=r.error.trim(),s;for(let i=0;i<3;i++){let a=Rs(o);if(a===null)break;let l;try{l=JSON.parse(a)}catch{break}if(typeof l.status=="number"&&(s=l.status),typeof l.message=="string"&&l.message.trim())o=l.message.trim();else if(typeof l.error=="string"&&l.error.trim())o=l.error.trim();else break}return{message:o,status:s}}function Lr(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Us(e,t=30){if(!e)return[];let n=[],r=new Set,o=(a,l,p)=>{!/^https?:\/\//i.test(l)||r.has(l)||n.length>=t||(r.add(l),n.push({title:a.trim()||l,url:l,snippet:p?.trim()||void 0}))},s=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=s.exec(e))!==null;)if(o(Lr(i[1]),Lr(i[2]),i[3]?Lr(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(o(Lr(i[2]),Lr(i[1])),n.length>=t)return n}return n}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function LS(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{let r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{}return null}}function Fs(e){return e.filter(t=>gt(t)&&!!t.title&&!!t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function ly(e){if(!e)return[];let t=LS(e,!0),n=t&&!Array.isArray(t)?t:void 0;if(n?.success===!1)return[];let r=n&&Array.isArray(n.results)?n.results:void 0;if(r&&r.length>0){let o=r[0];if(gt(o)&&typeof o.query=="string"){let s=[];for(let i of r)!gt(i)||typeof i.query!="string"||s.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?Fs(i.results):[]});if(s.length>0)return s}else if(gt(o)&&(o.title||o.url)){let s=Fs(r);if(s.length>0)return[{query:n?.query||"",answer:n?.answer||void 0,sources:s}]}}if(n?.query&&typeof n.query=="string")return[{query:n.query,answer:n.answer||void 0,sources:r?Fs(r):[]}];if(Array.isArray(t)&&t.length>0){let o=t[0];if(gt(o)&&(o.title||o.url)){let s=Fs(t);if(s.length>0)return[{query:"",sources:s}]}}if(typeof e=="string"){let o=e.split(/(?=^Title: )/m).filter(Boolean),s=[];for(let i of o){let a=i.match(/^Title:\s*(.+)/m),l=i.match(/^URL:\s*(.+)/m),p=i.match(/^Author:\s*(.+)/m),d=i.match(/^Published Date:\s*(.+)/m),g=i.match(/^Text:\s*([\s\S]*?)$/m);a&&l&&s.push({title:a[1].trim(),url:l[1].trim(),snippet:g?.[1]?.trim()||void 0,author:p?.[1]?.trim()||void 0,publishedDate:d?.[1]?.trim()||void 0})}if(s.length>0)return[{query:"",sources:s}]}if(typeof e=="string"){let o=Us(e);if(o.length>0)return[{query:"",sources:o.map(s=>({title:s.title,url:s.url,snippet:s.snippet}))}]}return[]}function Ns(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function NL(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Ns(e)}}function BL(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function KL(e){if(!e)return!1;let t=e.slice(0,600).toLowerCase();return t.includes("<!doctype html")||t.includes("<html")?!0:/<\/(body|head|div|p|span|table)>/i.test(e.slice(0,3e3))}function jS(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let o=r.trim();/^https?:\/\//i.test(o)&&n.push(o)}return n}return[]}function $S(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=PS(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function qL(e,t){let n=US(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?$S(r,jS(t)):[]}function US(e){if(!e)return null;let t=LS(e),n=t&&!Array.isArray(t)?t:void 0;if(!n)return null;if(n.results&&Array.isArray(n.results)){let r=n.results;return{total:n.total||r.length,successful:n.successful??r.filter(o=>gt(o)&&o.success!==!1).length,failed:n.failed??r.filter(o=>gt(o)&&o.success===!1).length,results:r.map(o=>{let s=gt(o)?o:{};return{url:s.url||"",success:s.success!==!1,title:s.title||void 0,content:s.content||s.text||s.snippet||void 0,error:s.error||void 0}})}}if(typeof e=="string"){let r=Us(e);if(r.length>0)return{total:r.length,successful:r.length,failed:0,results:r.map(o=>({url:o.url,success:!0,title:o.title||void 0,content:o.snippet||void 0}))}}return null}function GL(e){if(typeof e!="string"||!e.trim())return null;try{let t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"?t.toString():null}catch{return null}}var WL={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",script:"script",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function fn(e){return WL[ae(e)]}function $r(e){let t=Z(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var HL={run:"Terminal",memory:"Memory"};function VL(e){let t=fn(e);return(t==="hidden"?void 0:HL[t])??$r(e)}function jr(e,t,n){return e===1?t:n}function uy(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function BS(e){return e.length?Ts(e[0]):""}function De(e){return(e.state??{}).input??{}}var zL={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function YL(e){let t=Z(e.tool);if(t==="agent_task_update"||t==="task_update")switch(De(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return zL[t]??"message"}function FS(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function JL(e){let t=Z(e.tool);if(t==="triggers"){let r=De(e).action||"list";return FS(r)}let n=t.match(/^trigger_(.+)$/);return FS(n?n[1]:"list")}var QL={connector_setup:"connect",connector_get:"read",connector_list:"read",kortix_connector_discover:"read",kortix_connector_describe:"read",kortix_connectors:"read",kortix_connectors_connectors:"read",kortix_connectors_discover:"read",kortix_connectors_describe:"read",kortix_connector_call:"call",kortix_connectors_call:"call"};function XL(e){return QL[Z(e.tool)]??"read"}var ZL={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function ej(e){return ZL[Z(e.tool)]??"open"}function mn(e){return e.every(t=>t===e[0])}var tj={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function nj(e){if(Z(e.tool)!=="memory")return"read";let n=De(e).command;return n&&tj[n]||"unknown"}var rj={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},oj={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function sj(e){let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function ij(e){let t=De(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return aj(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return sj(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=GL(s);return i?Ns(i):"a link"}return""}function aj(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function cj(e){let t=De(e).action;return t&&rj[t]||"Worked on an image"}function lj(e){let t=De(e).action;return t&&oj[t]||"Worked on a presentation"}function uj(e){return e.slice(0,e.indexOf(":"))}var pj={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},dj={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function gj(e){let t=Z(e.tool);if(t==="image_gen"){let n=De(e).action;return n&&pj[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=De(e).action;return n&&dj[n]||"presentation:unknown"}return"shown:result"}var mj=new Set(["create_slide","export_pdf","export_pptx"]);function fj(e){let t=We(e),n=Z(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=De(t).action;return r?mj.has(r)?"presentation":null:"presentation"}return null}var yj={"image:generate":e=>`Made ${e} images`,"image:edit":e=>`Edited ${e} images`,"image:upscale":e=>`Upscaled ${e} images`,"image:remove_bg":e=>`Removed backgrounds from ${e} images`,"image:unknown":e=>`Worked on ${e} images`,"video:create":e=>`Made ${e} videos`,"presentation:create_slide":e=>`Added ${e} slides`,"presentation:delete_slide":e=>`Deleted ${e} slides`,"presentation:delete_presentation":e=>`Deleted ${e} presentations`,"presentation:list_slides":()=>"Checked a presentation's slides","presentation:list_presentations":()=>"Checked your presentations","presentation:validate_slide":()=>"Checked slides","presentation:export_pdf":e=>`Exported ${e} presentations to PDF`,"presentation:export_pptx":e=>`Exported ${e} presentations to PPTX`,"presentation:preview":e=>`Previewed ${e} presentations`,"presentation:unknown":e=>`Worked on ${e} presentations`,"shown:result":e=>`Showed you ${e} results`},NS={image:"image",video:"video",presentation:"presentation",shown:"result"};function hj(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[uj(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${jr(o,NS[r],`${NS[r]}s`)}`)}),`Worked on ${uy(n)}`}function Ur(e,t){let n=t.map(We),r=n.length,o=BS(n);switch(e){case"explore":{let s=n.filter(i=>Z(i.tool)==="read").length;return s===r?`Read ${r} ${jr(r,"file","files")}`:s===0?"Looked through your files":`Looked through your files \xB7 ${s} read`}case"edit":{let s=new Set(n.map(a=>ve(De(a))).filter(Boolean)).size||r,i=n.every(a=>Z(a.tool)==="write")?"Wrote":"Updated";return s===1?o?`${i} ${o}`:`${i} a file`:`${i} ${s} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let s=p=>{let d=Z(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(s).length;if(i===r)return`Searched the web \xB7 ${r} ${jr(r,"query","queries")}`;if(i===0)return`Read ${r} ${jr(r,"page","pages")}`;let a=new Set;for(let p of n)if(s(p)){let d=p.state?.output;for(let g of ly(d).flatMap(m=>m.sources))g.url&&a.add(g.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let l=a.size||r;return`Searched and read ${l} ${jr(l,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=Z(i.tool);if(a==="image_gen")return cj(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return lj(i);let l=ij(i);return l?`Showed you ${l}`:"Showed you the result"}let s=n.map(gj);return mn(s)?yj[s[0]](r):hj(s)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let s=n.map(YL);if(mn(s))switch(s[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let s=n.map(nj);if(mn(s))switch(s[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let s=n.map(XL);if(mn(s))switch(s[0]){case"connect":return r===1?o?`Connected to ${o}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let s=n.map(JL);if(mn(s))switch(s[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let s=n.map(ej);if(mn(s))switch(s[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?o?`Created ${o}`:"Created a project":`Created ${r} projects`;case"update":return r===1?o?`Updated ${o}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?o?`Opened ${o}`:"Opened your project":`Opened ${r} projects`}return o?`Worked in ${o}`:"Worked in your project"}case"skills":return r===1?o?`Used the ${o} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${$r(n[0].tool)}`;let s=Array.from(new Set(n.map(i=>$r(i.tool))));return s.length===1?`Used ${s[0]} \xB7 ${r} times`:`Used ${uy(s)}`}}}function py(e,t){let n=t.map(We),r=BS(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let o=Z(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${o} ${r}`:`Couldn't ${o} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let o=n.filter(a=>a.state?.status==="error"),s=o.length?o:n,i=Array.from(new Set(s.map(a=>$r(a.tool))));return`Couldn't finish using ${uy(i)}`}}}var KS=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),_j={read:{verb:"Read",running:"Reading",objectKeys:["filePath","path","file"]},write:{verb:"Wrote",running:"Writing",objectKeys:["filePath","path","file"]},edit:{verb:"Edited",running:"Editing",objectKeys:["filePath","path","file"]},apply_patch:{verb:"Edited",running:"Editing",objectKeys:["filePath","path"]},bash:{verb:"Ran",running:"Running",objectKeys:["command"]},glob:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},grep:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},list:{verb:"Listed",running:"Listing",objectKeys:["path"]},web_search:{verb:"Searched",running:"Searching",objectKeys:["query"]},websearch:{verb:"Searched",running:"Searching",objectKeys:["query"]},webfetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},web_fetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},scrape:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},scrape_webpage:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},task:{verb:"Delegated",running:"Delegating",objectKeys:["description"]},memory:{verb:"Remembered",running:"Remembering"},get_mem:{verb:"Recalled",running:"Recalling"},memory_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},mem_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},ltm_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},dcp_compress:{verb:"Compacted",running:"Compacting"},dcp_distill:{verb:"Distilled",running:"Distilling"},dcp_prune:{verb:"Pruned",running:"Pruning"},compress:{verb:"Compacted",running:"Compacting"},distill:{verb:"Distilled",running:"Distilling"},prune:{verb:"Pruned",running:"Pruning"},context_info:{verb:"Checked context",running:"Checking context"}};function bj(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Tr(t)||t}function Pj(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim())return bj(r,o.trim())}}function yn(e){let t=ge(e)?se(e):e;if(we(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!ee(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=me(t.tool),r=_j[n],o=t.state?.input;return r?{verb:r.verb,running:r.running,object:Pj(o,r.objectKeys),tier:KS.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function Bs(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if(yn(s).tier==="plumbing"){r=!0;continue}if(we(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,ee(s)&&$s(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function dy(e){return`${e} ${e===1?"step":"steps"}`}function qS(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${dy(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${dy(n)}`:o===0?`${dy(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function gy(e){let t=new Map,n=0;for(let o of e){if(!ee(o)||yn(o).tier==="plumbing")continue;let s=fn(o.tool);s!=="hidden"&&(t.set(s,[...t.get(s)??[],o]),$s(o)!=="ok"&&(n+=1))}if(t.size===0)return qS(Bs(e),!1);let r=[...t].map(([o,s],i)=>{let a=Ur(o,s);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function Sj(e){let t=!1,n=!1,r=!1,o=null,s=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),o==null&&d.error!=null&&(o=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},l=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");l&&(t=!0),e.userMessage&&s(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)s(p.info),i(p.parts);return l&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:o}}function xj(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function wj(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let o=r.state.time;typeof o?.start=="number"&&(t=Math.min(t,o.start)),typeof o?.end=="number"&&(n=Math.max(n,o.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function GS(e,t){let n=t.map(We),r=xj(n);return{id:n[0].callID,family:e,label:r==="error"?py(e,n):Ur(e,n),parts:t,status:r,durationMs:r==="running"?void 0:wj(n)}}function my(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push(GS(n,r)),n=null,r=[]};for(let s of e){let i=We(s),a=fn(i.tool);if(a!=="hidden"&&!Jo(i)){if(xm(i.tool)){o(),t.push(GS(a,[s]));continue}a!==n&&(o(),n=a),r.push(s)}}return o(),t}function Ks(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function fy(e,t){let n=[],r=null,o=[],s=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:l}=r,p=typeof a=="number"&&typeof l=="number"&&l>a?l-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(o.length!==0){for(let a of my(o))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});o=[]}};for(let a of e)if(t(a)!=="plumbing"){if(we(a)){let l=a.text?.trim();if(!l)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(l);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=Ks(a);continue}if(s(),ee(a)){o.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}s(),i();for(let a=0;a<n.length-1;a++){let l=n[a];l.kind==="thought"&&(l.running=!1)}return n}var kj=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function vj(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]*)`/g,"$1").replace(/^#{1,6}\s*/gm,"").replace(/\*\*([^*]*)\*\*/g,"$1").replace(/(^|\s)[*_]([^*_]+)[*_]/g,"$1$2").replace(/^\s*[-*+]\s+/gm,"").replace(/\s+/g," ").trim()}function Aj(e){let t=e.flatMap(o=>{let s=vj(o);return s?[s]:[]}).join(" ").trim();return t?kj.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function YS(e){return e?.info?.time??{}}function Rj(e){let t=YS(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var qs=6e4,Cj=10080*qs,WS=1440;function HS(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function Tj(e,t){let n=t.getTime()-e.getTime(),r=n/qs,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<WS)return o(Math.round(r/60),"hour");let s=(n-(HS(t)-HS(e)))/qs;return o(Math.round(s/WS),"day")}function JS(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}var VS=new Map;function Ij(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=VS.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),VS.set(r,o)),o}function Gs(e,t,n){return Ij(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?Ej(r.value,n):r.value).join("")}function Ej(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function zS(e,t){return Gs(e,{year:"numeric"},t)}function Mj(e,t,n={}){let r=JS(e);if(!r)return"";let o=i=>Gs(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return o(!0);let s=Math.max(0,t-r.getTime());return s<qs?"just now":s<Cj?Tj(r,new Date(t)):o(zS(r,n)!==zS(new Date(t),n))}function Oj(e,t={}){let n=JS(e);if(!n)return"";let r=Gs(n,{month:"long",day:"numeric",year:"numeric"},t),o=Gs(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function yy(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!wm(s)){if(Oe(s)){o(),n.push({kind:"text",part:s});continue}if(ee(s)&&(km(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function Dj(e){let t=me(e);return t==="show"||t==="show_user"}function hy(e,t={}){let n=[],r=[],o=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(s=>s.part)}),r=[]};for(let s of e){if(s.kind==="standalone"&&Dj(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var Lj=["title","description","path","url","content","language","aspect_ratio","attachment"];function QS(e,t){if(!t||typeof t!="object")return null;let n=t;if(ar(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of Lj){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function jj(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function _y(e){let t=[];for(let n of e){let r=n.state,o=r.input??{};if(r.status==="error"){let a=typeof o.title=="string"&&o.title?o.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let s=jj(o.items),i=s?s.map(a=>QS(n.callID,a)).filter(a=>!!a):[QS(n.callID,o)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function by(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Fr=e=>"id"in e?e.id:e.userMessage.info.id,XS=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,$j=e=>e.time?.completed;function Uj(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function Fj(e,t){let n=Fr(e);return t.pendingTurnIds.has(n)||XS(e)===0&&t.pendingPromptIds.has(n)}function Nj(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Fr(r)));if(t)return Fr(t);let n=e.turns.findIndex(r=>Fj(r,e));return n<=0?null:Fr(e.turns[n-1])}function Bj(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function Kj(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function qj(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:by({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function Gj(e,t){for(let n=e.length-1;n>=0;n--){let r=Fr(e[n]);if(t(r))return XS(e[n])===0?r:null}return null}function Py(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),o=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(l=>l.userMessage.info.id)}),s=e.hintMessageId??null;if(s){if(n>=0&&t[n].userMessage.info.id===s)return o(n);let a=r.indexOf(s);if(a>=0)return o(n+1+a)}if(n>=0){let a=t[n],l=a.assistantMessages[a.assistantMessages.length-1];if(!$j(l.info)&&!l.info.error)return o(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return o(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:o(n)}function Wj(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].info.role==="user")return t[n].info.id===e;return!1}function Hj(e,t){return!t||!e?!1:e.type!=="idle"}function Vj(e,t){return!e&&!!t}function zj(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return be(n.error)?.message||fe(n.error)}}function Yj(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Cr(n.error)}}function Jj(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return be(n.error)}}function Sy(e){if(e){if(ee(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(we(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(Oe(e))return"Gathering thoughts..."}}var Qj=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function Xj(e){if(!(!e||e.length===0))for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.info.role==="assistant")for(let r=n.parts.length-1;r>=0;r--){let o=Sy(n.parts[r]);if(o)return o}}}function Zj(e,t){let n=ee(e)?e:void 0;if(n&&Qj.has(n.tool)&&n.state.status==="running"){let r=Xj(t);return r||(t?.length?"Handing off to an agent...":void 0)}return Sy(e)}function xy(e,t){for(let n=e.length-1;n>=0;n--){let r=Zj(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function wy(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}var ky=1.055;function ZS(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),o=e.cache?.read??0,s=e.cache?.write??0,i=Math.max(0,n-o-s),l=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*l.inputPer1M;return p+=r/1e6*l.outputPer1M,o>0&&(p+=o/1e6*(l.cacheReadPer1M??l.inputPer1M)),s>0&&(p+=s/1e6*(l.cacheWritePer1M??l.inputPer1M)),p}function vy(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function ex(e,t,n,r){if(vy(t,n))return 0;let o=e.cost||0;if(o>0)return o;if(!r||!t||!n)return 0;let s=r(t,n);return s?ZS(e.tokens,s):0}function tx(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function Ws(e,t){let n=0,r=0,o=0,s=0,i=0,a=0,l=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){l=!0;let g=p,{providerID:m,modelID:f}=tx(d.info);n+=ex(g,m,f,t),r+=g.tokens?.input||0,o+=g.tokens?.output||0,s+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!l){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=nx(g,t),f=g.tokens&&vy(g.providerID,g.modelID);if(m<=0&&!f)continue;l=!0,n+=m;let _=g.tokens;_&&(r+=_.input??0,o+=_.output??0,s+=_.reasoning??0,i+=_.cache?.read??0,a+=_.cache?.write??0)}}if(l)return{cost:n*ky,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function nx(e,t){if(vy(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?ZS({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function e$(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=tx(o),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=ex(p,s,i,t));l||(a+=nx(o,t)),n+=a}return n*ky}function t$(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function n$(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function r$(e){if(!e||e.type!=="retry")return;let t=e,n=fe(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:be(t.message)}}function o$(e){if(!(!e||e.type!=="retry"))return fe(e.message)}function s$(e){return(e.info.summary?.diffs?.length??0)>0}function rx(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=me(e.part.tool);return t==="show"||t==="show_user"}function i$(e){return e.kind==="text"&&!e.part.text?.trim()}function Ay(e,t){if(t.working)return null;let n=-1;for(let o=e.length-1;o>=0;o--){let s=e[o];if(!(rx(s)||i$(s))){s.kind==="text"&&(n=o);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((o,s)=>{s===n?r.final.push(o):rx(o)?r.hoisted.push(o):r.work.push(o)}),r.work.length>0?r:null}function a$(e){let t=e==null?"":wy(e);return t?`Worked for ${t}`:"Worked"}function ox(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>Oe(s)&&s.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let o=r[0];return ee(o)&&o.tool==="bash"}function c$(e){if(ox(e))return e.assistantMessages[0].parts[0]}function l$(e){if(!e)return"";let t=e;return t=t.replace(/^##\s*Worker Result\s*\n/i,""),t=t.replace(/^\*\*Agent:\*\*.*\n?/m,""),t=t.replace(/^\*\*Task:\*\*.*\n?/m,""),t=t.replace(/^\*\*Status:\*\*.*\n?/m,""),t=t.replace(/^\*\*Session:\*\*.*\n?/m,""),t=t.replace(/^\*\*Duration:\*\*.*\n?/m,""),t=pS(t,"kortix_goal_system"),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created and started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created:.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* failed to start.*$/gm,""),t=t.replace(/^Message sent to task.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* approved.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* cancelled.*$/gm,""),t=t.replace(/Worker session: ses_[a-zA-Z0-9]+/g,""),t=t.replace(/^---\s*\n/gm,""),t=t.trim(),t||""}function u$(e){return e?e.split(`
84
+ `).filter(n=>n.trim()).length<=3:!1}function p$(e){if(!e)return null;let n=e.split(`
85
+ `).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function d$(e){if(!e)return[];let t=[],n=e.split(`
86
+ `).filter(r=>r.trim());for(let r of n){let o=fS(r);if(o){let s=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...o,sessionId:s?.[0]})}}return t}var mt={write:{verb:"Wrote",running:"Writing",failed:"Couldn't write"},edit:{verb:"Edited",running:"Editing",failed:"Couldn't update"},delete:{verb:"Deleted",running:"Deleting",failed:"Couldn't delete"},rename:{verb:"Renamed",running:"Renaming",failed:"Couldn't rename"},change:{verb:"Changed",running:"Changing",failed:"Couldn't apply"},read:{verb:"Read",running:"Reading",failed:"Couldn't read"},list:{verb:"Listed",running:"Listing",failed:"Couldn't list"}};function g$(e,t){let n=mt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function m$(e,t){return t?"failed":e?"running":"done"}var f$={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function y$(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function h$(e,t){if(!e)return null;let n=e.indexOf(`
87
+ `),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);if(gS(r,"content of "," with line numbers"))return{type:"file",content:o.split(`
88
88
  `).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
89
- `)};if(/files and directories/i.test(r)){let o=t.replace(/\/$/,""),i=[];for(let a of s.split(`
90
- `)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var LL={add:{...dt.write,icon:"create"},delete:{...dt.delete,icon:"delete"},move:{...dt.rename,icon:"edit"},update:{...dt.edit,icon:"edit"}},US={...dt.change,icon:"edit"};function $L(e){if(e.length===0)return US;let t=FS(e[0]);for(let n=1;n<e.length;n++)if(FS(e[n])!==t)return US;return LL[t]}function FS(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function UL(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.startsWith("Error:")?{success:!1,action:"unknown",error:e.replace(/^Error:\s*/,"")}:null}}function iy(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],s;for(;(s=n.exec(e))!==null;)r.push(s[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(o,i)=>r[i]?[r[i]]:[])}function FL(e){if(!e)return null;let t=Sr(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=kf(e,"content");if(r!==null){let o=r.split(`
89
+ `)};if(/files and directories/i.test(r)){let s=t.replace(/\/$/,""),i=[];for(let a of o.split(`
90
+ `)){if(!a.trim())continue;let l=a.indexOf(" ");if(l===-1)continue;let p=a.slice(0,l).trim(),d=a.slice(l+1).trim();d!==s&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var _$={add:{...mt.write,icon:"create"},delete:{...mt.delete,icon:"delete"},move:{...mt.rename,icon:"edit"},update:{...mt.edit,icon:"edit"}},sx={...mt.change,icon:"edit"};function b$(e){if(e.length===0)return sx;let t=ix(e[0]);for(let n=1;n<e.length;n++)if(ix(e[n])!==t)return sx;return _$[t]}function ix(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function P$(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.startsWith("Error:")?{success:!1,action:"unknown",error:e.replace(/^Error:\s*/,"")}:null}}function Ry(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],o;for(;(o=n.exec(e))!==null;)r.push(o[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(s,i)=>r[i]?[r[i]]:[])}function S$(e){if(!e)return null;let t=Er(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=Wf(e,"content");if(r!==null){let s=r.split(`
91
91
  `).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
92
- `);return{path:n,type:"file",content:o}}let s=kf(e,"entries");if(s!==null){let o=s.split(`
93
- `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function NL(e){let t=qP(e,"skill_content");return t!==null?t.trim():e}function NS(e){let t=Sr(e,"<skill_files>","</skill_files>");return t===null?[]:WP(t,"<file>","</file>").map(n=>n.trim())}function KL(e){let t=BP(e,"skill_content");if(t===null)return"";for(let n of["dir","directory","path","base","baseDir","base_dir"]){let r=t.match(new RegExp(`\\b${n}\\s*=\\s*["']([^"']+)["']`,"i"));if(r?.[1]?.trim())return r[1].trim()}return""}function BL(e){return HP(e,["Base directory","Directory","Skill directory"])?.trim()??""}function KS(e){return Qe(KL(e)||BL(e))}function qL(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Qe(n.trim())}return""}var GL="skills";function WL(e){let t=KP(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(s=>s.trim());if(n.some(s=>s===".."||s==="."))return"";let r=n.at(-1)??"";return r?`${GL}/${r}`:""}function VL(e,t,n){let s=Qe(t?.trim()??"")||KS(e)||WL(n),o=NS(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(o){if(o.startsWith("/"))return o;if(s)return`${s}/${o}`}return s?`${s}/SKILL.md`:null}var HL=4e3;function Ir(e,t=HL){return e.length>t?`${e.slice(0,t)}
94
- \u2026`:e}function BS(e){if(e!==void 0)try{return Ir(JSON.stringify(e,null,2))}catch{return}}function ne(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function zL(e){let t=ne(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=gn(e.outputParsed);if(!n)return{kind:"web-search",query:t};let s=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(o=>{let i=gn(o)??{};return{title:ne(i.title)??"",url:ne(i.url,i.link)??"",snippet:ne(i.snippet,i.description,i.source)}});return{kind:"web-search",query:ne(n.query)??t,results:s.length>0?s:void 0,answer:ne(n.answer)}}var YL=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function cy(e){let t=e.match(YL);return t?Number(t[1]):void 0}function JL(e,t,n){let r="",s=0;for(;;){let o=e.indexOf(t,s);if(o===-1)return r+e.slice(s);let i=e.indexOf(n,o+t.length);if(i===-1)return r+e.slice(s);r+=e.slice(s,o),s=i+n.length}}var QL=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function XL(e){let t=-1;for(let n of QL){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}function ZL(e){let t=ne(e.input?.command)??"",n=e.output??"",r=cy(n),o=Tf(XL(JL(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:o||void 0,exitCode:r}}function ly(e){return ne(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function e$(e){let t=e.status==="error"?e.error:e.output&&Ir(e.output)||void 0;return{kind:"file-read",path:ly(e),preview:t}}function t$(e){let t=ne(e.input?.content),n=e.status==="error"?e.error:Ir(t??e.output??"")||void 0;return{kind:"file-write",path:ly(e),preview:n}}var n$=256*1024;function r$(e,t){if(e.length+t.length>n$)return;let n=e.split(`
92
+ `);return{path:n,type:"file",content:s}}let o=Wf(e,"entries");if(o!==null){let s=o.split(`
93
+ `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:s}}return null}function x$(e){let t=uS(e,"skill_content");return t!==null?t.trim():e}function ax(e){let t=Er(e,"<skill_files>","</skill_files>");return t===null?[]:dS(t,"<file>","</file>").map(n=>n.trim())}function w$(e){let t=lS(e,"skill_content");if(t===null)return"";for(let n of["dir","directory","path","base","baseDir","base_dir"]){let r=t.match(new RegExp(`\\b${n}\\s*=\\s*["']([^"']+)["']`,"i"));if(r?.[1]?.trim())return r[1].trim()}return""}function k$(e){return mS(e,["Base directory","Directory","Skill directory"])?.trim()??""}function cx(e){return Xe(w$(e)||k$(e))}function v$(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Xe(n.trim())}return""}var A$="skills";function R$(e){let t=cS(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(o=>o.trim());if(n.some(o=>o===".."||o==="."))return"";let r=n.at(-1)??"";return r?`${A$}/${r}`:""}function C$(e,t,n){let o=Xe(t?.trim()??"")||cx(e)||R$(n),s=ax(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(s){if(s.startsWith("/"))return s;if(o)return`${o}/${s}`}return o?`${o}/SKILL.md`:null}var T$=4e3;function Nr(e,t=T$){return e.length>t?`${e.slice(0,t)}
94
+ \u2026`:e}function lx(e){if(e!==void 0)try{return Nr(JSON.stringify(e,null,2))}catch{return}}function ne(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function hn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function I$(e){let t=ne(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=hn(e.outputParsed);if(!n)return{kind:"web-search",query:t};let o=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(s=>{let i=hn(s)??{};return{title:ne(i.title)??"",url:ne(i.url,i.link)??"",snippet:ne(i.snippet,i.description,i.source)}});return{kind:"web-search",query:ne(n.query)??t,results:o.length>0?o:void 0,answer:ne(n.answer)}}var E$=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Ty(e){let t=e.match(E$);return t?Number(t[1]):void 0}function M$(e,t,n){let r="",o=0;for(;;){let s=e.indexOf(t,o);if(s===-1)return r+e.slice(o);let i=e.indexOf(n,s+t.length);if(i===-1)return r+e.slice(o);r+=e.slice(o,s),o=i+n.length}}var O$=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function D$(e){let t=-1;for(let n of O$){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}function L$(e){let t=ne(e.input?.command)??"",n=e.output??"",r=Ty(n),s=Jf(D$(M$(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:s||void 0,exitCode:r}}function Iy(e){return ne(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function j$(e){let t=e.status==="error"?e.error:e.output&&Nr(e.output)||void 0;return{kind:"file-read",path:Iy(e),preview:t}}function $$(e){let t=ne(e.input?.content),n=e.status==="error"?e.error:Nr(t??e.output??"")||void 0;return{kind:"file-write",path:Iy(e),preview:n}}var U$=256*1024;function F$(e,t){if(e.length+t.length>U$)return;let n=e.split(`
95
95
  `),r=t.split(`
96
- `),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let c=0;c<s;c++)a.push({type:"unchanged",text:n[c]});for(let c=s;c<o;c++)a.push({type:"removed",text:n[c]});for(let c=s;c<i;c++)a.push({type:"added",text:r[c]});for(let c=o;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function s$(e){let t=vo(e.input),n=t.map(([s,o])=>r$(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:ly(e),diff:r}}var GS=/^Found\s+(\d+)\s+match/i,o$=/^(\/[^:]+?):\s*/,qS=/Line\s+(\d+):/g;function i$(e){let t=e.trim(),n=t.match(GS),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let s=[];for(let o of r.split(/\n\n+/)){let i=o.trim();if(!i)continue;let a=i.match(o$);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(qS.lastIndex=0;(g=qS.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,_=p.slice(d[m].contentStart,f).trim();s.push({path:c,line:d[m].line,content:_.endsWith(";")?_.slice(0,-1):_})}}return s}function a$(e){return e.trim().split(`
97
- `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function c$(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=GS.test(e.output.trim())?i$(e.output):a$(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function l$(e){let t=ne(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=ne(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function ay(e){let t=gn(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function u$(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(ay)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(ay)};let n=gn(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(ay)}:{kind:"todo",items:[]}}function p$(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=gn(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let c=gn(a),p=c&&ne(c.label);return p?[{label:p,description:c?ne(c.description):void 0}]:[]});return{question:ne(s.question)??"",header:ne(s.header),options:i}})}}function d$(e){let n=e.input&&Object.keys(e.input).length>0?BS(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Ir(e.outputParsed):BS(e.outputParsed):e.outputText!==void 0?r=Ir(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function WS(e){switch(ae(e.name)){case"web_search":return zL(e);case"bash":return ZL(e);case"read":return e$(e);case"write":return t$(e);case"edit":return s$(e);case"grep":case"glob":return c$(e);case"task":return l$(e);case"todowrite":return u$(e);case"question":return p$(e);default:return d$(e)}}var g$=new Set(["AbortError","MessageAbortedError"]),m$=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],f$=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function VS(e){let t=e.toLowerCase();return f$.some(n=>t.includes(n))?!1:m$.some(n=>t.includes(n))}function y$(e){let t=e.data,n=t&&typeof t=="object"?t.message:void 0;return typeof n=="string"?n:typeof e.message=="string"?e.message:void 0}function Er(e){if(typeof e=="string")return VS(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&g$.has(n))return!0;let r=y$(t);return typeof r=="string"?VS(r):!1}var HS=["user","runtime-disposed","orphan-finalized","wake"],h$=["orphan-finalized","wake"];function _$(e){if(!e||typeof e!="object")return;let t=e.data;if(!t||typeof t!="object")return;let n=t.reason;if(!(typeof n!="string"||!n))return HS.includes(n)?n:void 0}var Mr="kortix-active-instance",zS=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function YS(e){return zS.some(t=>e===t||e.startsWith(`${t}/`))}function mn(e){let t=e.match(/^\/instances\/([^/]+)(?:\/(.*))?$/);if(!t)return null;let n=decodeURIComponent(t[1]),r=t[2]??"";return{instanceId:n,innerPath:r?`/${r}`:""}}function b$(e){let t=mn(e);return!!t&&t.innerPath===""}function P$(e){let t=mn(e);return!t||!t.innerPath?e:t.innerPath}function JS(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=mn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return YS(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function QS(e){return e?mn(e)?.instanceId??null:null}function S$(){return typeof window>"u"?null:QS(window.location.pathname)||XS()}function XS(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Mr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function x$(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Mr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Mr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Mr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function w$(e,t){return t?JS(t,e):e}function k$(e){let t=mn(e);return t?t.innerPath||"/dashboard":e}function Dr(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e??"")}function uy(e){let t=Dr(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}var v$=uy;function Ko(e){let t=uy(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var A$=Ko;function ZS(e){return Ko(e)!==null}var R$=ZS,C$=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],T$=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],I$=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function ex(e){return I$.test(Dr(e))}function fn(e){let t=Dr(e);return t?ex(t)||C$.some(n=>n.test(t)):!1}var E$=/server url not ready|sandbox is still loading/i;function M$(e){return E$.test(Dr(e))||fn(e)}var Or=class extends Error{constructor(t){let n=t?.trim();super(n&&fn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function tx(e){let t=Ko(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:o?`${i?`${i}: `:""}${o}`:void 0}}let n=Dr(e);return fn(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var O$=tx;function py(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${st()}/p/${e.external_id}/${We.KORTIX_MASTER}`}function D$(e,t){return e.external_id?`${st()}/p/${e.external_id}/${t}`:null}async function j$(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function nx(e){let t=await er();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Pt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await vt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await tt(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Ws(r,s,o),created:!0}}async function L$(){return(await er().catch(()=>null))?.sandbox??null}async function $$(e){return{sandbox:(await nx(e)).sandbox}}async function U$(e){let t=Zn(e);if(!t)return null;try{let n=await um(t);return n?Ws(await St(n.project_id),n,null):(await er(t))?.sandbox??null}catch{return null}}async function F$(e,t){throw await Vs(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function N$(e){let t=Zn(e);return(await lm().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function K$(){return null}async function B$(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Vs(e);if(!t)throw new Error("Project session sandbox not found");await Bn(t.projectId,t.sessionId)}async function q$(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Vs(e);if(!t)throw new Error("Project session sandbox not found");await qn(t.projectId,t.sessionId)}async function G$(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function W$(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function dy(e,t,n){let r=py(e),s=await L(`${ue(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function V$(e,t){return dy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function H$(e,t,n,r="member"){await dy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function z$(e,t,n){await dy(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var gy="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function Y$(e){throw U("getInvite",gy)}async function J$(e){throw U("acceptInvite",gy)}async function Q$(e){throw U("declineInvite",gy)}async function X$(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function Z$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function e0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function t0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function n0(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function r0(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var rx=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function s0(e){return rx.includes(e)}async function o0(e){return{phase:"idle",progress:0,message:"Sandbox image updates are managed by project-session provisioning.",targetVersion:null,previousVersion:null,currentVersion:e?.version??null,error:null,startedAt:null,updatedAt:null}}async function i0(e){let t=e?`?channel=${e}`:"",r=await(await Le(`${st()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await sx(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function sx(e){let t=e?`?channel=${e}`:"";return(await(await Le(`${st()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function a0(){return(await Le(`${st()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function c0(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function l0(e){}async function u0(e){}async function p0(e){return{serverTypes:[],location:e||"hel1"}}async function d0(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function g0(e){throw U("deleteInstance")}async function m0(e,t){}async function f0(){throw U("claimComputer")}async function y0(e){return null}function h0(e,t){throw U("getSandboxProvisionStreamUrl")}var jr=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function ox(e,t){let n=new Headers(e.headers);return n.set("Accept","application/json"),t&&n.set("Content-Type","application/json"),e.accessToken&&n.set("Authorization",`Bearer ${e.accessToken}`),n}async function ix(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function ax(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function te(e,t,n){let r=n?.body!==void 0,s=await fetch(`${At(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:ox(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await ix(s);if(!s.ok)throw new jr(ax(s,o),s.status,o);return o}function _0(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString();return n?`?${n}`:""}function b0(e,t){return te(`/marketplace/items${_0(t)}`,e)}function P0(e){return te("/marketplace/marketplaces",e)}function S0(e,t){return te(`/marketplace/items/${encodeURIComponent(e)}`,t)}function x0(e,t,n){return te(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function w0(e,t){return te("/access/check-email",t,{method:"POST",body:{email:e}})}function k0(e,t){return te("/access/request-access",t,{method:"POST",body:e})}function v0(e){return te("/auth/logout",e,{method:"POST",body:{}})}function A0(e,t){return te(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function R0(e,t){return te("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function C0(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function T0(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function I0(e,t,n={}){return te(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function E0(e,t){return te(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function M0(e,t,n,r){return te(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function O0(e,t){return te(`/p/public-share/${encodeURIComponent(e)}`,t)}function D0(e,t,n){return te(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function j0(e){return te("/system/maintenance",e)}function L0(e,t){return te("/system/maintenance",t,{method:"PUT",body:e})}function $0(e){return te("/user-roles",e)}function U0(e,t){return te("/system/demo-request",t,{method:"POST",body:e})}async function F0(e,t,n){let r=await fetch(`${At(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Bt(t)}`,{headers:ox(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await ix(r);throw new jr(ax(r,s),r.status,s)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function N0(e,t){throw U("openStressTestStream")}function K0(e,t){throw U("buildPublicTemplateUrl")}async function B0(e,t,n){throw U("getPublicTemplate")}var q0="kortix:connect-link:";function my(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);t=Math.imul(t^s,16777619)>>>0,n=Math.imul(n^s,1540483477)>>>0}return`${q0}${t.toString(36)}${n.toString(36)}`}function G0(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(my(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(my(i));return}return c}catch{return}},o=(i,a)=>{if(t)try{t.setItem(my(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=s(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var cx="Could not start the connect flow.";async function W0(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:cx}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:cx};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var lx=3e3,ux=5e3,px=5*6e4;function V0(e,t){let n=e===0?lx:ux;return t+n>px?null:n}function H0(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}async function z0(){let e=await l.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function Y0(e={}){let t=await l.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function J0(e){let t=await l.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function Q0(e){let t=await l.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function X0(){let e=await l.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var Y2="1";var Z0="kortix.query-cache";function gx(e){return!!e&&typeof e.then=="function"}function dx(e){return gx(e)?e:Promise.resolve()}function eU(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function tU(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=Z0,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,_=Promise.resolve(),y=()=>{try{return dx(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},v=(P,k)=>{if(!k)return 0;let C;try{C=JSON.parse(k)}catch{return y(),0}if(!C||C.v!==s||C.user!==n||!Array.isArray(C.queries)||p()-C.at>o)return y(),0;let j=0;for(let w of C.queries){if(!w||!Array.isArray(w.k)||w.d===void 0||typeof w.t!="number"||p()-w.t>o||!r(w.k))continue;let D=P.getQueryState(w.k);D&&D.data!==void 0&&D.dataUpdatedAt>=w.t||(P.setQueryData(w.k,w.d,{updatedAt:w.t}),P.invalidateQueries?.({queryKey:w.k,exact:!0,refetchType:"none"}),j+=1)}return j},R=P=>P.getQueryCache().getAll().filter(k=>k.state.data!==void 0&&r(k.queryKey)).map(k=>({k:k.queryKey,d:k.state.data,t:k.state.dataUpdatedAt})).sort((k,C)=>C.t-k.t),T=(P,k)=>{let C=[],j=0;for(let w of P){let D=JSON.stringify(w).length+1;j+D>k||(C.push(w),j+=D)}return C},b=async P=>{let k=T(R(P),i);for(;;){let C={v:s,user:n,at:p(),queries:k};try{await dx(t.setItem(d,JSON.stringify(C)));return}catch{if(k.length===0)return;k=k.slice(0,Math.floor(k.length/2))}}},M=()=>{f!==null&&(clearTimeout(f),f=null)},h=()=>{M();let P=g;return!P||!m||(m=!1,_=_.then(()=>b(P)).catch(()=>{})),_},S=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,h()},a))};return{storageKey:d,restore(P){let k;try{k=t.getItem(d)}catch{return 0}return gx(k)?k.then(C=>v(P,C)).catch(()=>0):v(P,k)},persist(P){g=P,m=!0;let k=P.getQueryCache().subscribe(C=>{C.type!=="updated"&&C.type!=="removed"&&C.type!=="added"||r(C.query.queryKey)&&S()});return()=>{k(),g===P&&(g=null,M())}},flush(){return h()},async clear(){M(),g=null,m=!1,await _,await y()}}}function nU(){let e;try{e=globalThis.localStorage}catch{e=void 0}if(!e)return null;let t=e;return{getItem:n=>{try{return t.getItem(n)}catch{return null}},setItem:(n,r)=>t.setItem(n,r),removeItem:n=>{try{t.removeItem(n)}catch{}}}}var mx="/kortix/part/";function fx(e){return typeof e=="string"&&e.startsWith(mx)}async function rU(e){if(!fx(e))throw new Error(`not an attachment part reference: ${e}`);let t=He();if(!t)throw new Error("runtime url not bound");let n=await L(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function yx(e){try{let t=new URL(e);if(/^\/proxy\/\d+(?:\/|$)/.test(t.pathname))return`${t.origin}/v1/p/auth`;let n=t.pathname.indexOf("/p/");return n!==-1?`${t.origin}${t.pathname.slice(0,n)}/p/auth`:`${t.origin}/v1/p/auth`}catch{return null}}function sU(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function fy(e,t){return sU(e,t)?(t?yx(t):null)??yx(e):null}function Lr(e){try{let{hostname:t}=new URL(e);return/^p\d+-[^.]+\./.test(t)||/^(?:dev|staging|prod|preview)-p\d+-[a-z0-9-]+\./i.test(t)}catch{return!1}}function yy(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var oU=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function iU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function aU(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),o=`${r}://${s}`.split("{port}").map(i=>i.split("{sandbox}").map(iU).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function cU(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function hx(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function lU(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:oU.test(n.hostname)?t.backendUrls.some(r=>{let s=cU(r);return s!==null&&hx(s)===hx(n)}):t.templates.some(r=>aU(n.origin,r))}async function _x(e,t={}){if(!Lr(e))return!1;let n=I().backendUrl;n&&await ot(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return lU(e,{templates:$_(),backendUrls:r})}async function bx(e,t={}){let n=fy(e,t.serverUrl||I().backendUrl||void 0);if(!n)return!1;let r=await $t();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function uU(e,t={}){if(Lr(e)){if(!await _x(e,t))return e;let n=await $t();return n?yy(e,n):e}return await bx(e,t),e}var pU=3e3;function Px(e){return!Number.isFinite(e)||e<100||e>599?"unknown":e===502||e===503||e===504?"unreachable":e===401||e===403?"unknown":"reachable"}async function dU(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return Px(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function gU(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function mU(e,t){throw U("buildPresentationTemplatePdfUrl")}function fU(e,t){throw U("buildPresentationTemplateImageUrl")}function Sx(e,t){return`${gU(e)}/presentation/convert-to-${t}`}async function yU(e,t,n,r){let s=Sx(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let _=await p.blob();if(_.size===0)throw new Error("Downloaded file is empty");return _}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((_,y)=>{let v=setTimeout(_,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(v),y(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let _=JSON.parse(m);f=String(_.error||_.detail||_.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function hU(e){return e.activityFresh||e.runtimeReady?"live":e.unreachable||e.stalled?"unreachable":e.sandbox==="stopped"||e.sandbox==="archived"||e.sandbox==="provisioning"||e.sandbox==="queued"||e.sandbox==="branching"?"waking":e.sandbox==="completed"?"unknown":e.sandbox==="failed"?"unreachable":e.sandbox==="running"?"connecting":"unknown"}function _U(e){return e==="unreachable"}function bU(e){return!e||e.status===0?"unknown":e.ok&&$m(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var xx=1e4,PU={connection:"unknown",faultSinceMs:null};function SU(e,t,n,r=xx){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let s=e.faultSinceMs??n;return n-s>=r?{connection:t,faultSinceMs:s}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:s}}function wx({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Bo,c=!!t&&i-t.atMs<Wo;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=qo,streamFresh:!!s&&i-s.atMs<=yn,inboxFresh:!!n&&i-n.atMs<=Go,activityFresh:!!o&&i-o.atMs<=yn}}function hn(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function hy(e,t,n){if(!t)return!1;let r=hn(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=hn(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function xU(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!hy(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function wU(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,c=i?s.turns.filter(g=>!hy(g,n,s)):[],p=c.find(g=>g.state==="active")??c[0],d=!!o&&!(o.type==="idle"&&o.origin==="local");return p&&s.atMs>=a&&(!d||s.atMs>=o.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:hn(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function kU(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&o.type!=="idle"&&(!p||o.atMs>s.atMs)&&o.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&s.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function vU(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:_}=t,y=c&&!n&&s.atMs>=p,v=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(y&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:hn(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(v)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:_,since:i.atMs,serverOpenTurnToken:r};let R=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:a};return{state:"idle",source:R.source,turnId:null,since:R.atMs,serverOpenTurnToken:r}}function kx(e){let t=wx(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=xU(e,t,s,o);if(i)return i;let{result:a,openTurn:c}=wU(e,t,s,o);return a??kU(e,t,o)??vU(e,t,c,o)}var Bo=6e4,qo=45e3,yn=45e3,Go=1e4,AU=3e3,Wo=15e3;function RU(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function CU(e){let t=0;for(let n of e)(n.state==="queued"||n.state==="delivering"||n.state==="waiting"&&n.reason!=="held")&&(t+=1);return t}function TU(e){return kx(e)}function IU(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,c=[null,t?t.atMs+Bo:null,n?n.atMs+Wo:null,r?r.atMs+Go:null,s?s.atMs+qo:null,o?o.atMs+yn:null,i?i.atMs+yn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function vx(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(o=>o.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||Er({name:s.name??void 0,message:s.message})?null:s}var EU="SandboxMemoryGuard";function MU(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=vx(e,t);if(r?.message){if(r.name!==EU)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let o=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(o)&&typeof e.atMs=="number"&&e.atMs-o<2500?null:{kind:"unexplained"}}var OU=6e4;function DU(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function jU(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var Ax=9e4;function LU(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+Ax}var $U=75e3,UU=2,FU=2e4;function _y(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function NU(e){return e.filter(t=>t!=null).join("|")}function KU(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function BU(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{..._y(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{..._y(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return g;let f=KU(e.attempts,s);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var qU={"retry-start":"retrying",restart:"restarting"};function GU(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${qU[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function WU(e){return e===1?"once":e===2?"twice":`${e} times`}function VU(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${WU(t)}`),`Tried: ${r.join(", then ")}.`}var HU={"needs-you":{label:"Needs you",tone:"actionable",description:"Waiting for your review"},starting:{label:"Starting",tone:"progress",description:"Its computer is starting"},running:{label:"Running",tone:"live",description:"Its computer is up"},done:{label:"Done",tone:"muted",description:"Finished"},stopped:{label:"Stopped",tone:"muted",description:"Asleep. Opening it wakes its computer"},failed:{label:"Failed",tone:"danger",description:"Its computer didn't start"},legacy:{label:"Legacy",tone:"muted",description:"Imported. Open it to restore"}};function Rx(e){return!!(e.metadata??{}).legacy_migration}function zU(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return Rx(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function YU(e){switch(e){case"waking":return{label:"Waking computer",tone:"progress"};case"connecting":return{label:"Connecting",tone:"progress"};case"unreachable":return{label:"Can't reach computer",tone:"danger"};default:return null}}var JU={unreachable:"Lost contact with this session's computer. Messages you send are queued until it reconnects.",unreachableMidTurn:"Lost contact with this session's computer while a turn is still open. Messages you send stay queued until it answers.",stalled:"Waking this session's computer is taking longer than usual. Messages you send are queued.",starting:"Starting this session's computer. Your message sends automatically.",idle:"This session's computer is asleep. Your next message wakes it up and is delivered.",waking:"Waking this session's computer. Messages you send are queued and go out automatically."};function QU(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function Vo(e){return e.runtime_sessions??e.opencode_sessions??[]}function Cx(e){let t=Vo(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function XU(e){let t=Cx(e);return t?Vo(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function ZU(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Vo(r).some(s=>s.id===t))??null)}var eF=new Set;function Tx(e){for(let t of[...eF])try{t(e)}catch{}}var Dx={schema:ce,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var jx=e=>Object.values(e.ext??{}).find(t=>t.version===ke),Lx=e=>!!e&&jx(e)!==void 0,tF=e=>{let t=jx(e);return t?t.native_id??null:e.thread_id},Ix=new WeakMap;function $x(e,t){let n=tF(e),r=Ix.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=Ns({...Dx,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return Ix.set(t,{native:n,rows:o}),o}var by=e=>e.info.time?.created;var nF=(e,t)=>(by(e)??-1/0)-(by(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var Ex=new WeakMap,Mx=new WeakMap,Ux=e=>typeof e=="object"&&e!==null,rF=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,sF=e=>e.info.role==="user"&&e.parts.some(t=>Ux(t)&&t.type==="compaction"),oF=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},Ox=new WeakMap;function iF(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,c)=>{let p=t.parts[c];if(!Ux(p)||a.type==="compaction")return a;let d=`${s}|${c}|${a.id}`,g=Ox.get(p);return g&&g.key===d?(o=!0,g.block):(Ox.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function aF(e){let t=new Map,n=new Set;for(let r of e){if(!sF(r))continue;let s=e.find(o=>!n.has(o)&&oF(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function cF(e,t,n,r,s){let o=Ex.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=Ks({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),c=iF(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...c,seq:s},lost:a.grade_counts};return Ex.set(n,p),p}function Fx(e,t,n){let r=Mx.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(nF),{paired:o,used:i}=aF(s),a={tool_input:0,cut_point:0,attachment:0},c=[];for(let m of s){if(i.has(m))continue;let f=cF(e,t,m,o.get(m),c.length+1);for(let _ of["tool_input","cut_point","attachment"])a[_]+=f.lost[_];c.push(f.message)}let p=rF(s.map(by).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=c.filter(m=>m.role==="user"&&m.kind==="turn"),g={...Dx,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:ce,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:c[0]?.created_at||p,messages:c,ext:{opencode:{version:ke,native_id:t}}}]};return Mx.set(n,{sessionId:e,native:t,log:g}),g}var Py=new WeakMap,_n=new WeakMap,Nx=new WeakMap;function Ho(e){let t,n=_n.get(e);return n&&(t=lF(n).get(e.id)),t?(Py.set(t,e),t):(e.type!=="harness"?t=Qg(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=Nx.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},Nx.set(e,t)),t&&Py.set(t,e),t)}var $r=e=>Py.get(e),Ot=e=>e.flatMap(t=>Ho(t)??[]),Kx=new WeakMap;function lF(e){let t=Kx.get(e);return t||Kx.set(e,t=new Map(gt(e)[0]?.parts.map(n=>[n.id,n]))),t}var Bx=new Map;function gt(e){let t=Bx.get(e.thread_id);return t||(t={schema:ce,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},Bx.set(e.thread_id,t)),$x(t,e)}var uF="kortix-v1-import",Sy={schema:ce,v:1};function zo(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var xy=e=>e.type==="tool_call",pF=e=>e.status==="pending"||e.status==="running",wy=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function zx(e,t){let n=wy(e);return!pF(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var qx=new WeakMap;function Yx(e,t){let n=qx.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),s={...Sy,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"kortix-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return qx.set(e,s),s}var Gx=new WeakMap;function dF(e){let t=Gx.get(e);return t||(t={...Sy,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},Gx.set(e,t)),t}var Wx=new WeakMap;function gF(e){let t=Wx.get(e);return t||(t={...Sy,message_id:`${e.message_id}:continued`,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},Wx.set(e,t)),t}var mF=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function fF(e,t){let n=[],r=new Map;for(let g of e){if(g.role!=="user"||g.kind==="context"||r.has(g.message_id))continue;let m={user:g,assistant:[],partial:!1};r.set(g.message_id,m),n.push(m)}let s=[],o=[],i=new Map,a=new Map,c=null,p=null;for(let g of e){if(g.role==="user"){let y=r.get(g.message_id);y&&!t.has(g.message_id)&&(c=y,i.has(y)||i.set(y,i.size),y.user.kind==="compaction"&&(p=y));continue}if(g.role!=="assistant"||mF(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??c;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let y=a.get(p);y||(y={user:gF(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,y)),f=y}if(f){f.assistant.push(g);continue}if(!g.reply_to){o.push(g);continue}let _=s[s.length-1];_&&_.user.message_id===g.reply_to?_.assistant.push(g):s.push({user:dF(g),assistant:[g],partial:!0})}if(o.length){let g=n[0]??s[0];g?g.assistant.unshift(...o):n.push({user:o[0],assistant:o.slice(1),partial:!1})}let d=n.filter(g=>!t.has(g.user.message_id)).flatMap(g=>{let m=a.get(g);return m?[g,m]:[g]});return[...s,...d,...[...t].flatMap(g=>r.get(g)??[])]}function yF(e,t){if(!t)return t;let n=t;for(let r of e){let s=r.continues;s&&(n===s.marker||n===s.prompt||t===s.prompt)&&(n=r.user.message_id)}return n}function Jx(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=gt(n)[0]?.info?.error??n.error.message,s=Pe(r),o=_r(r);return{code:n.error.code,message:s?.message||fe(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function hF(e,t,n){return e.length&&e.every(t)?No(e.flatMap(r=>gt(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:ky(e,n)}function ky(e,t){let n=e.flatMap(r=>{let s=r.usage;if(!s)return[];let o={type:"step-finish",cost:s.cost??0,tokens:{input:s.input,output:s.output,reasoning:s.reasoning??0,cache:{read:s.cache_read,write:s.cache_write}}};return[{part:o,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[o]}}]});return No(n,t)??null}function _F(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function bF(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&xy(n)&&n.name==="bash"?n:null}function PF(e,t,n,r){if(!n.length)return[];let s=new Set(e.assistant.map(i=>i.message_id)),o=new Set;for(let i of n)i.spawned_by&&s.has(i.spawned_by.message_id)&&o.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:xy(i)?wr(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var SF=e=>e.assistant.some(t=>t.blocks.some(n=>xy(n)&&ae(n.name)==="todowrite"&&ln(n))),xF=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function wF(e,t){let n=e.map(s=>Jx(s)!==null),r=e.map((s,o)=>n[o]===!0&&t[o+1]===!0);return e.map((s,o)=>{if(r[o])return{continued:!0,retries:0};if(!n[o])return;let i=0;for(let a=o-1;a>=0&&r[a];a--)i+=1;return i>0?{continued:!1,retries:i}:void 0})}var Vx=new WeakMap,kF=[];function vy(e){let t=zo(e.messages,n=>n.role==="assistant");return!!t&&Uf(gt(t))}var Hx=new WeakMap;function vF(e){let t=Hx.get(e);if(!t){let n=e.messages.filter(r=>r.in_context||r.status==="streaming");t=n.length===e.messages.length?e:{...e,messages:n},Hx.set(e,t)}return t}function Yo(e,t={}){let n=t.hideOutOfContext?vF(e):e,r=new Set(t.held??kF),s=fF(n.messages,r),o=zo(n.messages,y=>y.role==="assistant"),i=vy(n),a=Zf({turns:s.map(y=>({userMessage:{info:{id:y.user.message_id}},assistantMessages:y.assistant.map(v=>({info:{time:v.status==="streaming"?{}:{completed:1},error:v.error??void 0}}))})),hintMessageId:yF(s,t.liveMessageId),unrunTurnIds:r}),c=zo(s,SF)??s[s.length-1],p=s.map(y=>!y.partial&&xF(y.user)),d=wF(s,p),g=Lx(n),m=y=>g||y.producer.harness===uF,f=t.threads??[],_=new Set(f.map(y=>y.thread_id));return s.map((y,v)=>{let R=t.busy===!0&&a.workingTurnId===y.user.message_id,T=a.pendingTurnIds.includes(y.user.message_id),b=i&&y.assistant.includes(o),M=d[v],h=`${y.partial}|${R}|${T}|${y===c}|${b}|${M?(M.continued?"c":"")+M.retries:"-"}`,S=Vx.get(y.user);if(S&&S.key===h&&S.pricing===t.pricing&&S.heads===t.threads&&S.assistant.length===y.assistant.length&&S.assistant.every((w,D)=>w===y.assistant[D]))return S.turn;let P=y.assistant.flatMap(w=>w.blocks);for(let w of y.assistant)for(let D of w.blocks)_n.set(D,w);let k=PF(y,P,f,_),C=y.assistant[y.assistant.length-1],j={internal:p[v],autoRetry:M,id:y.user.message_id,user:y.user,assistant:y.assistant,partial:y.partial,continues:y.continues??null,blocks:P,status:b?"streaming":C?C.status:y.user.kind==="compaction"?y.user.status:"pending",error:Jx(y),cost:hF([y.user,...y.assistant],m,t.pricing),compaction:_F(y.user),threads:k,plan:y===c,shell:bF(y),response:zo(P,w=>w.type==="text"&&!!w.text.trim())??null,attachments:y.user.blocks.filter(w=>w.type==="attachment"&&(w.mime.startsWith("image/")||w.mime==="application/pdf")),live:R,queued:T,retrying:b};return Vx.set(y.user,{assistant:y.assistant,key:h,pricing:t.pricing,heads:t.threads,turn:j}),j})}var Ay=e=>$r(e);function ew(e,t={}){return Jf(Yf(Ot(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map($r)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Ay)}:n.kind==="text"?{kind:n.kind,block:$r(n.part)}:{kind:n.kind,block:Ay(n.part)})}var AF=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:Ot(e.blocks)}:{kind:e.kind,part:Ho(e.block)};function tw(e,t){let n=new Map(e.map(o=>[AF(o),o])),r=oy([...n.keys()],t);if(!r)return null;let s=o=>o.map(i=>n.get(i));return{work:s(r.work),hoisted:s(r.hoisted),final:s(r.final)}}function RF(e){if(!ee(e)||!Xg(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=Of(e);return(n.answers??iy(n.outputText??"",t.length)??[]).length>0}function nw(e){return zf(Ot(e),n=>dn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(RF)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:$r(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Ay),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(o=>o.id===n.key.slice(8)),s=r&&_n.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function rw(e,t){return ty(Ot(e.blocks).map(n=>({part:n})),t?.flatMap(gt))}function sw(e){return Lo(Ot(e))}function ow(e){return Vf(Ot(e))}function iw(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=Ho(n),s=_n.get(n);return!!r&&we(r)&&$o(r)&&(!s||s.status==="streaming")}):!1}var Qx=new WeakMap;function aw(e){if(!wy(e))return e;let t=Qx.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},Qx.set(e,t)}return t}function CF(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function cw(e){let t=e.map(oe),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=Qf(t).map(CF);return Qn({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function lw(e,t,n){let r=oe(e),s=r.state;return Qn({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function uw(e){let t=gt(e).map(r=>To(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}var Xx=Object.freeze([]),Zx=new WeakMap;function pw(e){if(!e)return Xx;let t=Zx.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&ln(s)):[]);t=n.length?n:Xx,Zx.set(e,t)}return t}function dw(e,t={}){let n={cost:0,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of Yo(e)){let s=ky([r.user,...r.assistant],t.pricing);if(s){n.cost+=s.cost;for(let o of Object.keys(n.tokens))n.tokens[o]+=s.tokens[o]}}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let s=r.usage;(r.role==="assistant"||r.kind==="compaction")&&s&&s.input+s.output+(s.reasoning??0)+s.cache_read+s.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}var TF="prt_kortix_restore_g";function mw(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(TF))}function fw(e,t){let n=new Map,r=[...e??[]].sort((s,o)=>s.from_seq-o.from_seq);for(let s=1;s<r.length;s++){let o=r[s],i=r[s-1].harness;if(o.harness===i)continue;let a=t.findIndex(c=>c.user.seq>=o.from_seq);a<0||a===0&&t[0].user.seq!==o.from_seq||n.set(t[a].id,{harness:o.harness,previous:i,version:o.version,at:o.at})}return n}var Ry=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xe=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,IF=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function yw(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=Ry(t)?t.restore:void 0;if(!Ry(n))return null;let r=Ry(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:Xe(r.message)},{kind:"attachment",count:Xe(s?.attachment)},{kind:"text",count:Xe(r.text)+Xe(n.truncated)},{kind:"tool_input",count:Xe(s?.tool_input)},{kind:"tool_result",count:Xe(r.tool_result)},{kind:"cut_point",count:Xe(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,c])=>IF.has(a)?i:i+Xe(c),0)}];return{generation:Xe(n.generation),missing:o.filter(i=>i.count>0)}}var hw=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function _w(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of hw(r))s.ref&&s.bytes!==void 0&&!t.has(s.ref)&&t.set(s.ref,s.bytes);return[...t].map(([n,r])=>({ref:n,bytes:r}))}var bw=(e,t)=>{let n=e.ref===void 0?void 0:t.get(e.ref);if(n===void 0)return e;let{ref:r,bytes:s,...o}=e;return{...o,text:n}},EF=(e,t)=>e.map(n=>n.type==="text"?bw(n,t):n),gw=new WeakMap;function MF(e,t){let n=gw.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>hw(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?bw(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:EF(s.result.content,t)}}:s)}:e;return gw.set(e,{texts:t,out:r}),r}var Jo=1024*1024;function Pw(e){return e.reduce((t,n)=>t+n.bytes,0)>Jo?"download":"inline"}function Sw(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>Jo)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function xw(e,t){if(t.size===0)return e;let n=e.messages.map(r=>MF(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function OF(e){return e==="TIMEOUT"||e==="request_deadline"}function DF(e){let t=kw(e)?e.code:void 0;return typeof t=="string"?t:void 0}var kw=e=>typeof e=="object"&&e!==null;function ww(e){let t=e?.metadata;return!!kw(t)&&t.warm===!0}var jF=5,LF=2e3,$F=e=>new Promise(t=>setTimeout(t,e));async function UF(e,{attempts:t=jF,delayMs:n=LF,sleep:r=$F}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function FF(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(c,p,d)=>{if(r.has(c)||n.has(c))return Promise.resolve();r.add(c);let g=i,m=(async()=>{let f=null;try{let _=await e.ensure(c,p);if(g!==i)return;s.has(_.sessionId)?f=_.sessionId:n.set(c,_)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return o.add(m),m.finally(()=>o.delete(m)),m};return{ensure:(c,p)=>a(c,p?.excludeSessionId,1),take:(c,p,{replenish:d})=>{let g=n.get(c);return g?(n.delete(c),s.add(g.sessionId),d&&a(c,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(c,p,d)=>{try{return await e.claim(c,d),!0}catch(g){return OF(DF(g))?UF(async()=>!ww(await e.read(c,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:c=>{for(let[p,d]of n)if(d.sessionId===c)return n.delete(p),s.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(ww(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),s.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var NF=12e4,Qo=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},KF=1e3,BF=15e3,vw=100,qF=50,GF=10;function Aw(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let i=new URLSearchParams({limit:String(r)});s&&i.set("before",s);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!c.ok)throw c.status===503?new Or(`session ${c.status}`):new x(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function Rw(e){return WF(Aw(e))}function Cw(e){return new Cy({...e,loadPage:Aw(e)})}async function WF(e){let t=[],n=new Set,r;do{let i=await e({limit:vw,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])o.has(a.info.id)||(o.add(a.info.id),s.push(a));return s}var VF={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Cy=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??VF,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??NF,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed||t==="visible"&&this.streamReliable&&this.snapshot.freshness==="fresh"?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":this.snapshot.freshness}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof Qo;if(!r&&Er(n))return;if(r||this.update({freshness:fn(n)?"loading":"error"}),n instanceof x&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(KF*2**this.retryAttempt,BF);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?qF:vw,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let o,i=new Promise((c,p)=>{o=this.startTimer(()=>{let d=new Qo(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(o),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(s?[s]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<GF&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw o?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,o?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,i=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};var HF=5e3,Iw=40,HQ=5*6e4,zF=16,Ur=new Map;function Ew(e,t,n,r=Date.now()){let s=Mw(e,t);for(Ur.delete(s),Ur.set(s,{envelope:n,atMs:r});Ur.size>zF;){let o=Ur.keys().next().value;if(o===void 0)break;Ur.delete(o)}}var Tw=new Map;function Mw(e,t){return`${e}/${t}`}function YF(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=HF}function Ow(e,t,n=Date.now()){if(!e||!t)return null;let r=Mw(e,t),s=Tw.get(r);return s?YF(s,n)?s.promise:(Tw.delete(r),null):null}function Dw(e){let t=e.transcript;if(!t||t.known!==!0||t.requested!==!0)return null;let{known:n,requested:r,...s}=t;if(!s.available)return s;let o=e.session?.runtime_session_id??e.session?.opencode_session_id,i=s.runtime_session_id??s.opencode_session_id;return o&&i===o?s:null}var JF=2e3;async function QF(e,t,n){let r=Ow(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??JF,null)})]).finally(()=>clearTimeout(s)):null;return(o&&Dw(o))??Fn(e,t,{limit:Iw,history:!0,signal:n.signal})}async function jw(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s;try{s=await QF(t,n,{})}catch{return{envelope:null,empty:!1}}if(Ew(t,n,s),Ty(s)!==r)return{envelope:s,empty:!1};try{let o=await Nn(t,n);return{envelope:s,empty:Iy({savedEmptyRoot:r,rootSessionId:r,turnRead:!0,hasEndedTurn:o.last_ended!=null,hasOpenOrQueuedTurn:o.turns.length>0})}}catch{return{envelope:s,empty:!1}}}function Ty(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function Iy(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function XF(e){throw U("buildTunnelEventStreamUrl")}function ZF(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function _(b,M){o?.(b,M);let h=d.get(b);if(h)for(let S of h)try{S(M)}catch{}}async function y(){if(m)return;let b=new AbortController;g=b,p&&(p.aborted?b.abort():p.addEventListener("abort",()=>b.abort(),{once:!0}));let M=b.signal;try{let h={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(h["Content-Type"]="application/json"),f&&(h["Last-Event-ID"]=f);let S=await fetch(t,{method:r,headers:h,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:M,credentials:"include"});if(!S.ok)throw new Error(`SSE connection failed: ${S.status} ${S.statusText}`);if(!S.body)throw new Error("SSE response has no body");i?.();let P=S.body.getReader(),k=new TextDecoder,C="",j="message",w=[],D=N=>{if(N===""){w.length>0&&_(j,w.join(`
98
- `)),j="message",w=[];return}if(N.startsWith(":"))return;let z=N.indexOf(":"),G=z===-1?N:N.slice(0,z),B=z===-1?"":N.slice(z+1);B.startsWith(" ")&&(B=B.slice(1)),G==="event"?j=B.trim()||"message":G==="data"?w.push(B):G==="id"&&!B.includes("\0")&&(f=B)},xe=N=>{let z="";!N&&C.endsWith("\r")&&(z="\r",C=C.slice(0,-1));let G=C.split(/\r\n|\n|\r/);C=(G.pop()??"")+z;for(let B of G)D(B)};for(;!m;){let{done:N,value:z}=await P.read();if(N)break;C+=k.decode(z,{stream:!0}),xe(!1)}m||(C+=k.decode(),xe(!0),c?.())}catch(h){if(m||h instanceof DOMException&&h.name==="AbortError")return;a?.(h instanceof Error?h:new Error(String(h)))}}function v(){m=!0,g?.abort(),g=null,d.clear()}function R(b,M){let h=d.get(b)??new Set;h.add(M),d.set(b,h)}function T(b,M){d.get(b)?.delete(M)}return{connect:y,close:v,addEventListener:R,removeEventListener:T}}function eN(e,t){throw U("createTunnelEventStream")}var Lw="/_kortix/viewer",Xo=6e4,bn=new Map;function $w(){bn.clear(),Fr.clear()}async function tN(e,t){let n;try{n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}})}catch{return null}if(n.status===401||n.status===404||!n.ok)return null;let r=await n.json().catch(()=>null);return r&&typeof r.user_id=="string"?r:null}async function Ey(e={}){let t=e.path??Lw,n=e.fetch??((o,i)=>fetch(o,i)),r=bn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=tN(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-Xo:Date.now()+Xo;return bn.set(t,{session:o,expiresAt:a}),o});return bn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function Uw(e={}){let t=e.path??Lw;return Object.assign(async()=>(await Ey(e))?.access_token??null,{invalidate:n=>{let r=bn.get(t);r&&!r.inflight&&r.session?.access_token===n&&bn.delete(t)}})}var Fr=new Map;async function nN(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let o=await n.json().catch(()=>null);o?.error==="app_not_linked"&&console.warn(`[kortix] ${String(o.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let s=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return Fr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-Xo:Date.now()+Xo}),r.token}catch{return null}}function My(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((s,o)=>fetch(s,o));return async(s={})=>{let o=Fr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=nN(n,r).then(a=>(a===null&&Fr.delete(n),a));return Fr.set(n,i),i}}function Fw(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("kortixBinding needs the App origin: pass { origin } outside a browser.");return{url:`${ue(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:My({audience:e,fetch:t.fetch})}}var mt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},Se=e=>typeof e=="string"&&e.length>0?e:null;function Nw(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Zo(e){if(!e||typeof e!="object")return null;let t=e,n=Se(t.sub)??Se(t.subject)??Se(t.user_id)??Se(t.userId);return n?{userId:n,email:Se(t.email),name:Se(t.name),picture:Se(t.picture)??Se(t.pictureUrl),groups:Nw(t.groups),groupIds:Nw(t.group_ids??t.groupIds),role:Se(t.role),accountId:Se(t.account_id)??Se(t.accountId),projectId:Se(t.project_id)??Se(t.projectId)}:null}function Bw(e,t={}){let n=Zo(e);if(!n)throw new mt("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:s}=t;if(r&&!r.some(o=>n.groups.includes(o)||n.groupIds.includes(o)))throw new mt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new mt("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var rN=60,Oy=new Map;function qw(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function Kw(e){return JSON.parse(new TextDecoder().decode(qw(e)))}async function sN(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),s=e.slice(n+1),o=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(s),i=>i.charCodeAt(0))):decodeURIComponent(s);return JSON.parse(o)}if(/^https?:\/\//.test(e)){let n=Oy.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>Oy.delete(e)),Oy.set(e,n)),n}return JSON.parse(e)}async function Gw(e,t={}){let n=b=>{throw new mt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??rt("KORTIX_AUTH_JWKS"),s=t.issuer??rt("KORTIX_AUTH_ISSUER"),o=t.audience??rt("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(o!==!1&&!o)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,g;try{d=Kw(a),g=Kw(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await sN(r,t.fetch??((b,M)=>fetch(b,M)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(b=>b.kty==="EC"&&(d.kid===void 0||b.kid===d.kid));if(f.length===0)return n("unknown key");let _=new TextEncoder().encode(`${a}.${c}`),y;try{y=qw(p)}catch{return n("malformed")}let v=!1;for(let b of f)try{let{kid:M,alg:h,use:S,key_ops:P,...k}=b,C=await crypto.subtle.importKey("jwk",k,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,y,_)){v=!0;break}}catch{}if(!v)return n("bad signature");let R=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+rN<R)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let b=g.aud;if(!(b===o||Array.isArray(b)&&b.includes(o)))return n("wrong audience")}let T=Zo(g);return T||n("no subject")}function Dy(e){let t=e.agents.map(oN),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function oN(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function jy(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Gs(n?{...r,mode:null}:r))}function Ww(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let o=e.selectedAgent?.trim();return o?{selected:o,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=jy(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(o=>o.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let s=e.defaultAgent?.trim();return s&&n.some(o=>o.name===s)?{selected:s,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var Vw=Dy;function Hw(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Ly(e){return{providerID:"kortix",modelID:e}}function ei(e,t){let n=e.startsWith("kortix/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return Ly(n)}var $y=[{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"poe",env:["POE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"infer",env:["INFER_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]}];function Uy(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function aN(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function zw(e,t){let n=new Map;for(let r of e){let s=t(r),o=n.get(s);o?o.push(r):n.set(s,[r])}return n}function he(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function Yw(e){return e.reduce((t,n)=>{let r=Uy(n)??0,s=Uy(t)??0;return r!==s?r>s?n:t:he(n.id)>he(t.id)?n:t})}function Fy(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of zw(e,aN)){let a=[...zw(o,p=>p.family||p.id).values()].map(Yw),c=a.filter(p=>{let d=Uy(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[Yw(a)])s.add(p.id)}return s}function ti(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>he(r.id)>0)?n.filter(r=>he(r.id)>0):n}function Nr(e){let t;for(let n of ti(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&he(n.id)>he(t.id))&&(t=n)}return t}var cN={"amazon-bedrock":{methods:[{label:"Bearer token",envVars:["AWS_BEARER_TOKEN_BEDROCK","AWS_REGION"]}]},google:{methods:[{envVars:["GOOGLE_GENERATIVE_AI_API_KEY"]},{envVars:["GOOGLE_API_KEY"]},{envVars:["GEMINI_API_KEY"]}]}};function Jw(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var lN=(()=>{let e=new Map;for(let{id:n,env:r}of $y)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let s=[...r].sort((o,i)=>o.length-i.length||o.localeCompare(i));t.set(n,r.find(o=>Jw(o)===n)??s[0])}return t})();function Qw(e){let t=cN[e.id];if(t)return t;let n=e.env??[],r=n.length===1?lN.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Jw(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function Ky(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var uN=["low","medium","high"];function Xw(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...uN]}:void 0,s=e.temperature===!0,o=e.limit?.output,i=typeof o=="number"&&o>0?{ceiling:o}:void 0;return{reasoningEffort:r,temperature:s,topP:s,maxOutputTokens:i}}var Zw=$y;var Ny={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var ni=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash-1017",transport:"openrouter",morphModelId:"morph-dsv41flash-1017",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"morph/fp8":{inputPerMillion:.09,cachedInputPerMillion:.008,outputPerMillion:.55}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["morph/fp8"],...Ny,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{"decart/fp4":{inputPerMillion:.1275,cachedInputPerMillion:.0255,outputPerMillion:.425},"coreweave/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["decart/fp4","coreweave/nvfp4"],...Ny,max_price:{prompt:.15,completion:.5}}},{id:"kimi-k3",name:"Kimi K3 2.8T",upstreamModelId:"moonshotai/kimi-k3",transport:"openrouter",morphModelId:"morph-kimik3",morphPricing:{inputPerMillion:2.5,cachedInputPerMillion:.29,outputPerMillion:14},pricingRef:"openrouter/moonshotai/kimi-k3",pricing:{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5},openrouterEndpointPricing:{"fireworks/us":{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5}},tier:"flagship",vision:!0,limit:{context:1e6,output:65536},openrouterProvider:{only:["fireworks/us"],...Ny,max_price:{prompt:3.3,completion:16.5}}}],dX=new Map(ni.map(e=>[e.id,e]));var ek=ni.map(e=>e.id),tk=(ni.find(e=>e.tier==="flagship")??ni[0]).id,nk="deepseek-v4.1-flash";var sk=Zw.map(e=>({id:e.id,authRequirement:Qw(e)})),Kr=new Set(["kortix"]),By=new Set(["kortix"]);function Pn(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,s=Array.isArray(r)?r:[];return s.length===0?{...e,all:[],connected:[]}:{...e,all:s,connected:s.map(o=>o.id)}}function pN(e){if(!e)return!1;let t=Pn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(s=>r.includes(s.id)&&s.models&&Object.keys(s.models).length>0)}function dN(e){let t=Pn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(s=>!By.has(s.id)),connected:r.filter(s=>!By.has(s))}}function gN(e,t,n){let r=Pn(e),s=Array.isArray(r.all)?r.all:[],o=new Set(s.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)o.has(a.id)&&Ky(a.authRequirement,c=>t.has(c))&&i.add(a.id);return o.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var mN=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function fN(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var qy="opencode";function yN(e){return e.cost?.input===0&&e.cost?.output===0}function rk(e){return e===qy?Number.MAX_SAFE_INTEGER:mN.get(e)??Number.MAX_SAFE_INTEGER-1}function hN(e,t){let n=bN(t),r={},s=(e.providers??[]).map(o=>{let i=(o.models??[]).filter(a=>a.status!=="deprecated");return o.id===qy&&!n.has(qy)?{...o,models:i.filter(yN),keyless:!0}:{...o,models:i,keyless:!1}}).filter(o=>(o.keyless||n.has(o.id))&&!By.has(o.id)&&(o.models?.length??0)>0).sort((o,i)=>rk(o.id)-rk(i.id)).map(o=>{let i=[...o.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||he(p.id)-he(c.id)),a=Nr(i)?.id??i[0]?.id;return a&&(r[o.id]=a),{id:o.id,name:o.name,source:o.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=fN(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:s,connected:s.map(o=>o.id),default:r}}function _N(e,t){if(!e)return t;if(!t)return e;let n=Pn(e),r=Pn(t),s=new Map;for(let d of Array.isArray(r.all)?r.all:[])s.set(d.id,d);let o=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])o.push(s.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(o.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=s.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:o,connected:a,default:p}}function bN(e){let t=new Set;for(let n of sk)Ky(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function PN(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,s])=>{if(s.variants&&Object.keys(s.variants).length>0)return[r,s];let o=Xw({id:r,name:s.name,reasoning:s.reasoning,reasoning_options:s.reasoning_options}).reasoningEffort?.values;return o?.length?[r,{...s,variants:Object.fromEntries(o.map(i=>[i,{}]))}]:[r,s]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function SN(e,t){return dN(gN(Pn(e),t,sk))}function ok(e){if(e.gatewayEnabled)return e.modelPicker?PN(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?SN(e.runtimeProviders,t):void 0;return _N(e.llmCatalogProviders?hN(e.llmCatalogProviders,t):void 0,pN(n)?n:void 0)}function xN(e){return"capabilities"in e&&e.capabilities!=null}function ri(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function ik(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],s=Array.isArray(e.connected)?e.connected:[],o=[];for(let i of r)if(s.includes(i.id)&&!(n==="gateway"?!Kr.has(i.id):Kr.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(xN(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}o.push({id:Hw({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return o}function ak(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var wN=new Set([tk]),kN="kortix",ck="codex",vN=new Set(ek);function AN(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Sn(e){return wN.has(e.modelID)}function RN(e){return Fy(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function lk(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=RN(e.catalogModels),s=ak(e.catalogModels),o=new Map;for(let i of e.pins??[])o.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=o.get(a);if(c==="hide")return!1;if(i.providerID===kN){let d=AN(i.modelID,i.provider),g=d===ck?t?.has(ck)??!1:t?.has(d)??!1;if(vN.has(i.modelID))return!n||i.modelID===nk;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return Sn(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Sn(i)}catch{return Sn(i)}return!1}if(c==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return Sn(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Sn(i)}catch{return Sn(i)}return!1}}function uk(e,t){return t.search.trim().length>0||e.providerID==="kortix"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function pk(e,t){if(!e||Kr.has(e.providerID)||he(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>he(i.modelID)>0))return e;let r=i=>he(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,o=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??Nr(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!o||o===e.modelID?e:{...e,modelID:o}}function dk(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?Ly(n):void 0}function gk(e){for(let t=(e?.length??0)-1;t>=0;t--){let n=e[t],{provider:r,model:s}=n.model??{};if(n.role==="user"&&r&&s)return{providerID:r,modelID:s}}}var CN=new Set(["explicit","repointed"]);function mk(e){let t=e.session?Gn(e.session):null,n=t?ei(t,e.gatewayEnabled):void 0;return(CN.has(String(e.session?.metadata?.opencode_model_source))?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(o=>!!o)}function fk(e){let{models:t,providers:n}=e,r=c=>ri(t,c),s=c=>c.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let _={providerID:m.id,modelID:f};if(r(_))return _}for(let _ of ti(Object.keys(m.models).map(y=>({id:y})))){let y={providerID:m.id,modelID:_.id};if(r(y))return y}}}})(),i=s(e.picks??[]),a=i??s([e.serverDefault,e.globalDefault,e.agentModel,o]);return{model:pk(a,t),explicit:i,fallback:o}}return xk(TN);})();
96
+ `),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length,i=r.length;for(;s>o&&i>o&&n[s-1]===r[i-1];)s--,i--;let a=[];for(let l=0;l<o;l++)a.push({type:"unchanged",text:n[l]});for(let l=o;l<s;l++)a.push({type:"removed",text:n[l]});for(let l=o;l<i;l++)a.push({type:"added",text:r[l]});for(let l=s;l<n.length;l++)a.push({type:"unchanged",text:n[l]});return a}function N$(e){let t=Is(e.input),n=t.map(([o,s])=>F$(o,s)),r=t.length&&n.every(Boolean)?n.flatMap(o=>o??[]):void 0;return{kind:"file-edit",path:Iy(e),diff:r}}var px=/^Found\s+(\d+)\s+match/i,B$=/^(\/[^:]+?):\s*/,ux=/Line\s+(\d+):/g;function K$(e){let t=e.trim(),n=t.match(px),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let o=[];for(let s of r.split(/\n\n+/)){let i=s.trim();if(!i)continue;let a=i.match(B$);if(!a)continue;let l=a[1],p=i.slice(a[0].length),d=[],g;for(ux.lastIndex=0;(g=ux.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,_=p.slice(d[m].contentStart,f).trim();o.push({path:l,line:d[m].line,content:_.endsWith(";")?_.slice(0,-1):_})}}return o}function q$(e){return e.trim().split(`
97
+ `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function G$(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=px.test(e.output.trim())?K$(e.output):q$(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function W$(e){let t=ne(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=ne(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function Cy(e){let t=hn(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function H$(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(Cy)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(Cy)};let n=hn(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(Cy)}:{kind:"todo",items:[]}}function V$(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=hn(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let l=hn(a),p=l&&ne(l.label);return p?[{label:p,description:l?ne(l.description):void 0}]:[]});return{question:ne(o.question)??"",header:ne(o.header),options:i}})}}function z$(e){let n=e.input&&Object.keys(e.input).length>0?lx(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Nr(e.outputParsed):lx(e.outputParsed):e.outputText!==void 0?r=Nr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function dx(e){switch(ae(e.name)){case"web_search":return I$(e);case"bash":return L$(e);case"read":return j$(e);case"write":return $$(e);case"edit":return N$(e);case"grep":case"glob":return G$(e);case"task":return W$(e);case"todowrite":return H$(e);case"question":return V$(e);default:return z$(e)}}var Y$=new Set(["AbortError","MessageAbortedError"]),J$=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],Q$=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function gx(e){let t=e.toLowerCase();return Q$.some(n=>t.includes(n))?!1:J$.some(n=>t.includes(n))}function X$(e){let t=e.data,n=t&&typeof t=="object"?t.message:void 0;return typeof n=="string"?n:typeof e.message=="string"?e.message:void 0}function Br(e){if(typeof e=="string")return gx(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&Y$.has(n))return!0;let r=X$(t);return typeof r=="string"?gx(r):!1}var mx=["user","runtime-disposed","orphan-finalized","wake"],Z$=["orphan-finalized","wake"];function e0(e){if(!e||typeof e!="object")return;let t=e.data;if(!t||typeof t!="object")return;let n=t.reason;if(!(typeof n!="string"||!n))return mx.includes(n)?n:void 0}var Kr="kortix-active-instance",fx=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function yx(e){return fx.some(t=>e===t||e.startsWith(`${t}/`))}function _n(e){let t=e.match(/^\/instances\/([^/]+)(?:\/(.*))?$/);if(!t)return null;let n=decodeURIComponent(t[1]),r=t[2]??"";return{instanceId:n,innerPath:r?`/${r}`:""}}function t0(e){let t=_n(e);return!!t&&t.innerPath===""}function n0(e){let t=_n(e);return!t||!t.innerPath?e:t.innerPath}function hx(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=_n(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return yx(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function _x(e){return e?_n(e)?.instanceId??null:null}function r0(){return typeof window>"u"?null:_x(window.location.pathname)||bx()}function bx(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Kr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function o0(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Kr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Kr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Kr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function s0(e,t){return t?hx(t,e):e}function i0(e){let t=_n(e);return t?t.innerPath||"/dashboard":e}function Gr(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e??"")}function Ey(e){let t=Gr(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let o of n)if(o)try{return JSON.parse(o)}catch{}return null}var a0=Ey;function Hs(e){let t=Ey(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var c0=Hs;function Px(e){return Hs(e)!==null}var l0=Px,u0=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],p0=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],d0=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function Sx(e){return d0.test(Gr(e))}function bn(e){let t=Gr(e);return t?Sx(t)||u0.some(n=>n.test(t)):!1}var g0=/server url not ready|sandbox is still loading/i;function m0(e){return g0.test(Gr(e))||bn(e)}var qr=class extends Error{constructor(t){let n=t?.trim();super(n&&bn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function xx(e){let t=Hs(e);if(t){let o=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),s=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${o} is preventing OpenCode from loading. ${a}`,detail:s?`${i?`${i}: `:""}${s}`:void 0}}let n=Gr(e);return bn(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var f0=xx;function My(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${st()}/p/${e.external_id}/${Ke.KORTIX_MASTER}`}function y0(e,t){return e.external_id?`${st()}/p/${e.external_id}/${t}`:null}async function h0(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function wx(e){let t=await tr();if(t)return{sandbox:t.sandbox,created:!1};let r=(await xt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await Rt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await nt(r.project_id,o.session_id))?.sandbox??null;return{sandbox:Bo(r,o,s),created:!0}}async function _0(){return(await tr().catch(()=>null))?.sandbox??null}async function b0(e){return{sandbox:(await wx(e)).sandbox}}async function P0(e){let t=er(e);if(!t)return null;try{let n=await nm(t);return n?Bo(await wt(n.project_id),n,null):(await tr(t))?.sandbox??null}catch{return null}}async function S0(e,t){throw await Ko(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function x0(e){let t=er(e);return(await tm().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function w0(){return null}async function k0(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Ko(e);if(!t)throw new Error("Project session sandbox not found");await Yn(t.projectId,t.sessionId)}async function v0(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Ko(e);if(!t)throw new Error("Project session sandbox not found");await Jn(t.projectId,t.sessionId)}async function A0(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function R0(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function Oy(e,t,n){let r=My(e),o=await j(`${le(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`Request failed (${o.status})`)}return await o.json()}async function C0(e,t){return Oy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function T0(e,t,n,r="member"){await Oy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function I0(e,t,n){await Oy(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var Dy="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function E0(e){throw F("getInvite",Dy)}async function M0(e){throw F("acceptInvite",Dy)}async function O0(e){throw F("declineInvite",Dy)}async function D0(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function L0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function j0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function $0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function U0(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function F0(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var kx=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function N0(e){return kx.includes(e)}async function B0(e){return{phase:"idle",progress:0,message:"Sandbox image updates are managed by project-session provisioning.",targetVersion:null,previousVersion:null,currentVersion:e?.version??null,error:null,startedAt:null,updatedAt:null}}async function K0(e){let t=e?`?channel=${e}`:"",r=await(await je(`${st()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let o=await vx(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function vx(e){let t=e?`?channel=${e}`:"";return(await(await je(`${st()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function q0(){return(await je(`${st()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function G0(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function W0(e){}async function H0(e){}async function V0(e){return{serverTypes:[],location:e||"hel1"}}async function z0(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function Y0(e){throw F("deleteInstance")}async function J0(e,t){}async function Q0(){throw F("claimComputer")}async function X0(e){return null}function Z0(e,t){throw F("getSandboxProvisionStreamUrl")}var Wr=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function Ax(e,t){let n=new Headers(e.headers);return n.set("Accept","application/json"),t&&n.set("Content-Type","application/json"),e.accessToken&&n.set("Authorization",`Bearer ${e.accessToken}`),n}async function Rx(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Cx(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function te(e,t,n){let r=n?.body!==void 0,o=await fetch(`${qe(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:Ax(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),s=await Rx(o);if(!o.ok)throw new Wr(Cx(o,s),o.status,s);return s}function eU(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString();return n?`?${n}`:""}function tU(e,t){return te(`/marketplace/items${eU(t)}`,e)}function nU(e){return te("/marketplace/marketplaces",e)}function rU(e,t){return te(`/marketplace/items/${encodeURIComponent(e)}`,t)}function oU(e,t,n){return te(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function sU(e,t){return te("/access/check-email",t,{method:"POST",body:{email:e}})}function iU(e,t){return te("/access/request-access",t,{method:"POST",body:e})}function aU(e){return te("/auth/logout",e,{method:"POST",body:{}})}function cU(e,t){return te(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function lU(e,t){return te("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function uU(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function pU(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function dU(e,t,n={}){return te(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function gU(e,t){return te(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function mU(e,t,n,r){return te(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function fU(e,t){return te(`/p/public-share/${encodeURIComponent(e)}`,t)}function yU(e,t,n){return te(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function hU(e){return te("/system/maintenance",e)}function _U(e,t){return te("/system/maintenance",t,{method:"PUT",body:e})}function bU(e){return te("/user-roles",e)}function PU(e,t){return te("/system/demo-request",t,{method:"POST",body:e})}async function SU(e,t,n){let r=await fetch(`${qe(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Ht(t)}`,{headers:Ax(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await Rx(r);throw new Wr(Cx(r,o),r.status,o)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function xU(e,t){throw F("openStressTestStream")}function wU(e,t){throw F("buildPublicTemplateUrl")}async function kU(e,t,n){throw F("getPublicTemplate")}var vU="kortix:connect-link:";function Ly(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let o=e.charCodeAt(r);t=Math.imul(t^o,16777619)>>>0,n=Math.imul(n^o,1540483477)>>>0}return`${vU}${t.toString(36)}${n.toString(36)}`}function AU(e,{storage:t}={}){let n=new Map,r=new Map,o=i=>{if(t)try{let a=t.getItem(Ly(i));if(!a)return;let l=JSON.parse(a);if(Date.parse(l.expires_at)<=Date.now()){t.removeItem(Ly(i));return}return l}catch{return}},s=(i,a)=>{if(t)try{t.setItem(Ly(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let l=o(i);return l&&r.set(i,l),l},load(i){let a=n.get(i);if(a)return a;let l=e(i).then(p=>(r.set(i,p),s(i,p),p),p=>{throw n.delete(i),p});return n.set(i,l),l}}}var Tx="Could not start the connect flow.";async function RU(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:Tx}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:Tx};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var Ix=3e3,Ex=5e3,Mx=5*6e4;function CU(e,t){let n=e===0?Ix:Ex;return t+n>Mx?null:n}function TU(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}async function IU(){let e=await c.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function EU(e={}){let t=await c.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function MU(e){let t=await c.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function OU(e){let t=await c.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function DU(){let e=await c.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var DJ="1";var LU="kortix.query-cache";function Dx(e){return!!e&&typeof e.then=="function"}function Ox(e){return Dx(e)?e:Promise.resolve()}function jU(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function $U(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=LU,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,_=Promise.resolve(),y=()=>{try{return Ox(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},k=(P,v)=>{if(!v)return 0;let T;try{T=JSON.parse(v)}catch{return y(),0}if(!T||T.v!==o||T.user!==n||!Array.isArray(T.queries)||p()-T.at>s)return y(),0;let L=0;for(let w of T.queries){if(!w||!Array.isArray(w.k)||w.d===void 0||typeof w.t!="number"||p()-w.t>s||!r(w.k))continue;let D=P.getQueryState(w.k);D&&D.data!==void 0&&D.dataUpdatedAt>=w.t||(P.setQueryData(w.k,w.d,{updatedAt:w.t}),P.invalidateQueries?.({queryKey:w.k,exact:!0,refetchType:"none"}),L+=1)}return L},R=P=>P.getQueryCache().getAll().filter(v=>v.state.data!==void 0&&r(v.queryKey)).map(v=>({k:v.queryKey,d:v.state.data,t:v.state.dataUpdatedAt})).sort((v,T)=>T.t-v.t),I=(P,v)=>{let T=[],L=0;for(let w of P){let D=JSON.stringify(w).length+1;L+D>v||(T.push(w),L+=D)}return T},b=async P=>{let v=I(R(P),i);for(;;){let T={v:o,user:n,at:p(),queries:v};try{await Ox(t.setItem(d,JSON.stringify(T)));return}catch{if(v.length===0)return;v=v.slice(0,Math.floor(v.length/2))}}},M=()=>{f!==null&&(clearTimeout(f),f=null)},h=()=>{M();let P=g;return!P||!m||(m=!1,_=_.then(()=>b(P)).catch(()=>{})),_},x=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,h()},a))};return{storageKey:d,restore(P){let v;try{v=t.getItem(d)}catch{return 0}return Dx(v)?v.then(T=>k(P,T)).catch(()=>0):k(P,v)},persist(P){g=P,m=!0;let v=P.getQueryCache().subscribe(T=>{T.type!=="updated"&&T.type!=="removed"&&T.type!=="added"||r(T.query.queryKey)&&x()});return()=>{v(),g===P&&(g=null,M())}},flush(){return h()},async clear(){M(),g=null,m=!1,await _,await y()}}}function UU(){let e;try{e=globalThis.localStorage}catch{e=void 0}if(!e)return null;let t=e;return{getItem:n=>{try{return t.getItem(n)}catch{return null}},setItem:(n,r)=>t.setItem(n,r),removeItem:n=>{try{t.removeItem(n)}catch{}}}}var Lx="/kortix/part/";function jx(e){return typeof e=="string"&&e.startsWith(Lx)}async function FU(e){if(!jx(e))throw new Error(`not an attachment part reference: ${e}`);let t=ze();if(!t)throw new Error("runtime url not bound");let n=await j(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function $x(e){try{let t=new URL(e);if(/^\/proxy\/\d+(?:\/|$)/.test(t.pathname))return`${t.origin}/v1/p/auth`;let n=t.pathname.indexOf("/p/");return n!==-1?`${t.origin}${t.pathname.slice(0,n)}/p/auth`:`${t.origin}/v1/p/auth`}catch{return null}}function NU(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let s=new Set;if(t)try{s.add(new URL(t).origin)}catch{}return typeof window<"u"&&s.add(window.location.origin),s.has(n.origin)}catch{return!1}}function jy(e,t){return NU(e,t)?(t?$x(t):null)??$x(e):null}function Hr(e){try{let{hostname:t}=new URL(e);return/^p\d+-[^.]+\./.test(t)||/^(?:dev|staging|prod|preview)-p\d+-[a-z0-9-]+\./i.test(t)}catch{return!1}}function BU(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var KU=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function qU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function GU(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let o=(t.slice(n+3).split("/")[0]??"").toLowerCase(),s=`${r}://${o}`.split("{port}").map(i=>i.split("{sandbox}").map(qU).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function WU(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Ux(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function HU(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:KU.test(n.hostname)?t.backendUrls.some(r=>{let o=WU(r);return o!==null&&Ux(o)===Ux(n)}):t.templates.some(r=>GU(n.origin,r))}async function Fx(e,t={}){if(!Hr(e))return!1;let n=C().backendUrl;n&&await it(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return HU(e,{templates:ob(),backendUrls:r})}async function Nx(e,t={}){let n=jy(e,t.serverUrl||C().backendUrl||void 0);if(!n)return!1;let r=await Ft();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function VU(e,t={}){if(Hr(e)){if(!await Fx(e,t)||!await Ft())return e;let r=await c.post("/p/ticket",{preview_url:e}),o=r.data;if(!r.success||!o||typeof o.ticket!="string"||!o.ticket)throw new Error("Preview authorization failed");let s=new URL(e);return s.searchParams.delete("token"),s.searchParams.set("preview_ticket",o.ticket),s.toString()}return await Nx(e,t),e}var zU=3e3;function Bx(e){return!Number.isFinite(e)||e<100||e>599?"unknown":e===502||e===503||e===504?"unreachable":e===401||e===403?"unknown":"reachable"}async function YU(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let o=setTimeout(r,t?.timeoutMs??3e3);try{let s=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return Bx(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function JU(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function QU(e,t){throw F("buildPresentationTemplatePdfUrl")}function XU(e,t){throw F("buildPresentationTemplateImageUrl")}function Kx(e,t){return`${JU(e)}/presentation/convert-to-${t}`}async function ZU(e,t,n,r){let o=Kx(t,e),s=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),l=!1;for(;;){let p=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let _=await p.blob();if(_.size===0)throw new Error("Downloaded file is empty");return _}if(p.status===202){if(l||(l=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((_,y)=>{let k=setTimeout(_,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(k),y(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let _=JSON.parse(m);f=String(_.error||_.detail||_.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function eF(e){return e.activityFresh||e.runtimeReady?"live":e.unreachable||e.stalled?"unreachable":e.sandbox==="stopped"||e.sandbox==="archived"||e.sandbox==="provisioning"||e.sandbox==="queued"||e.sandbox==="branching"?"waking":e.sandbox==="completed"?"unknown":e.sandbox==="failed"?"unreachable":e.sandbox==="running"?"connecting":"unknown"}function tF(e){return e==="unreachable"}function nF(e){return!e||e.status===0?"unknown":e.ok&&of(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var qx=1e4,rF={connection:"unknown",faultSinceMs:null};function oF(e,t,n,r=qx){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let o=e.faultSinceMs??n;return n-o>=r?{connection:t,faultSinceMs:o}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:o}}function Gx({optimistic:e,abort:t,inbox:n,server:r,stream:o,activity:s,nowMs:i}){let a=!!e&&i-e.atMs<Vs,l=!!t&&i-t.atMs<Js;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:l,abortFloor:l?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=zs,streamFresh:!!o&&i-o.atMs<=Pn,inboxFresh:!!n&&i-n.atMs<=Ys,activityFresh:!!s&&i-s.atMs<=Pn}}function Sn(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function $y(e,t,n){if(!t)return!1;let r=Sn(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=Sn(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function sF(e,t,n,r){let{activity:o,server:s}=e,{serverFresh:i,abortFloor:a,activityFresh:l}=t;return l&&(!n||o.atMs>n.atMs)&&o.atMs>=a?{state:"working",source:"stream",turnId:i?s.turns.find(d=>d.state==="active"&&!$y(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function iF(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,l=i?o.turns.filter(g=>!$y(g,n,o)):[],p=l.find(g=>g.state==="active")??l[0],d=!!s&&!(s.type==="idle"&&s.origin==="local");return p&&o.atMs>=a&&(!d||o.atMs>=s.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:Sn(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function aF(e,t,n){let{inbox:r,server:o,stream:s}=e,{inboxFresh:i,abortFloor:a,streamFresh:l,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...l&&s.type!=="idle"&&(!p||s.atMs>o.atMs)&&s.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&o.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function cF(e,t,n,r){let{server:o,stream:s,optimistic:i,nowMs:a}=e,{serverFresh:l,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:_}=t,y=l&&!n&&o.atMs>=p,k=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(y&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:Sn(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(k)return{state:s.type==="idle"?"idle":"working",source:"stream",turnId:null,since:s.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:_,since:i.atMs,serverOpenTurnToken:r};let R=o&&s?o.atMs>=s.atMs?{source:"server",atMs:o.atMs}:{source:"stream",atMs:s.atMs}:o?{source:"server",atMs:o.atMs}:s?{source:"stream",atMs:s.atMs}:{source:"server",atMs:a};return{state:"idle",source:R.source,turnId:null,since:R.atMs,serverOpenTurnToken:r}}function Wx(e){let t=Gx(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=sF(e,t,o,s);if(i)return i;let{result:a,openTurn:l}=iF(e,t,o,s);return a??aF(e,t,s)??cF(e,t,l,s)}var Vs=6e4,zs=45e3,Pn=45e3,Ys=1e4,lF=3e3,Js=15e3;function uF(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function pF(e){let t=0;for(let n of e)(n.state==="queued"||n.state==="delivering"||n.state==="waiting"&&n.reason!=="held")&&(t+=1);return t}function dF(e){return Wx(e)}function gF(e){let{optimistic:t,abort:n,inbox:r,server:o,stream:s,activity:i,nowMs:a}=e,l=[null,t?t.atMs+Vs:null,n?n.atMs+Js:null,r?r.atMs+Ys:null,o?o.atMs+zs:null,s?s.atMs+Pn:null,i?i.atMs+Pn:null],p=null;for(let d of l)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function Hx(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(s=>s.message_id===t),r=e.last_ended,o=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!o?.message||Br({name:o.name??void 0,message:o.message})?null:o}var mF="SandboxMemoryGuard";function fF(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=Hx(e,t);if(r?.message){if(r.name!==mF)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],l=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:l}}let o=e.recent_failures?.find(a=>a.message_id===t);if(!o)return null;let s=o.ended_at?Date.parse(o.ended_at):Number.NaN;return Number.isFinite(s)&&typeof e.atMs=="number"&&e.atMs-s<2500?null:{kind:"unexplained"}}var yF=6e4;function hF(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function _F(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var Vx=9e4;function bF(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+Vx}var PF=75e3,SF=2,xF=2e4;function Uy(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function wF(e){return e.filter(t=>t!=null).join("|")}function kF(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function vF(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Uy(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Uy(),settled:!0};let i=e.lastProgressAtMs,a=i===null,l=t.progress!==e.fingerprint,p=i===null||l?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!l&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<s)return g;let f=kF(e.attempts,o);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var AF={"retry-start":"retrying",restart:"restarting"};function RF(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${AF[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function CF(e){return e===1?"once":e===2?"twice":`${e} times`}function TF(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(o=>o.step==="restart").length,n=e.attempts.some(o=>o.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${CF(t)}`),`Tried: ${r.join(", then ")}.`}var IF={"needs-you":{label:"Needs you",tone:"actionable",description:"Waiting for your review"},starting:{label:"Starting",tone:"progress",description:"Its computer is starting"},running:{label:"Running",tone:"live",description:"Its computer is up"},done:{label:"Done",tone:"muted",description:"Finished"},stopped:{label:"Stopped",tone:"muted",description:"Asleep. Opening it wakes its computer"},failed:{label:"Failed",tone:"danger",description:"Its computer didn't start"},legacy:{label:"Legacy",tone:"muted",description:"Imported. Open it to restore"}};function zx(e){return!!(e.metadata??{}).legacy_migration}function EF(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return e.working?.state==="idle"?"done":"running";case"completed":case"stopped":return zx(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function MF(e){switch(e){case"waking":return{label:"Waking computer",tone:"progress"};case"connecting":return{label:"Connecting",tone:"progress"};case"unreachable":return{label:"Can't reach computer",tone:"danger"};default:return null}}var OF={unreachable:"Lost contact with this session's computer. Messages you send are queued until it reconnects.",unreachableMidTurn:"Lost contact with this session's computer while a turn is still open. Messages you send stay queued until it answers.",stalled:"Waking this session's computer is taking longer than usual. Messages you send are queued.",starting:"Starting this session's computer. Your message sends automatically.",idle:"This session's computer is asleep. Your next message wakes it up and is delivered.",waking:"Waking this session's computer. Messages you send are queued and go out automatically."};function DF(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function Qs(e){return e.runtime_sessions??e.opencode_sessions??[]}function Yx(e){let t=Qs(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function LF(e){let t=Yx(e);return t?Qs(e).filter(n=>(n.parent_id===t.id||!n.parent_id&&n.fork_source_id)&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function jF(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Qs(r).some(o=>o.id===t))??null)}var $F=new Set;function Jx(e){for(let t of[...$F])try{t(e)}catch{}}var tw={schema:ce,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var nw=e=>Object.values(e.ext??{}).find(t=>t.version===ke),rw=e=>!!e&&nw(e)!==void 0,ow=e=>{let t=nw(e);return t?t.native_id??null:e.thread_id};function sw(e){let t=e&&Object.values(e.threads).find(r=>r.parent_thread_id===null);if(!e||!t)return null;let n=(e.messages[t.thread_id]?.length??0)>0;return{runtimeSessionId:ow(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var Qx=new WeakMap;function iw(e,t){let n=ow(e),r=Qx.get(t);if(r&&r.native===n)return r.rows;let{rows:o}=zo({...tw,threads:[{...e,messages:[t]}]}),s=o.map(i=>({info:i.info,parts:i.parts}));return Qx.set(t,{native:n,rows:s}),s}var Fy=e=>e.info.time?.created;var UF=(e,t)=>(Fy(e)??-1/0)-(Fy(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var Xx=new WeakMap,Zx=new WeakMap,aw=e=>typeof e=="object"&&e!==null,FF=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,NF=e=>e.info.role==="user"&&e.parts.some(t=>aw(t)&&t.type==="compaction"),BF=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},ew=new WeakMap;function KF(e,t,n){let r=t.info,o=`${e}|${String(r.id)}|${String(r.time?.created)}`,s=!1,i=n.blocks.map((a,l)=>{let p=t.parts[l];if(!aw(p)||a.type==="compaction")return a;let d=`${o}|${l}|${a.id}`,g=ew.get(p);return g&&g.key===d?(s=!0,g.block):(ew.set(p,{key:d,block:a}),a)});return s?{...n,blocks:i}:n}function qF(e){let t=new Map,n=new Set;for(let r of e){if(!NF(r))continue;let o=e.find(s=>!n.has(s)&&BF(s,r));o&&(t.set(r,o),n.add(o))}return{paired:t,used:n}}function GF(e,t,n,r,o){let s=Xx.get(n);if(s&&s.sessionId===e&&s.native===t&&s.sum===r&&s.seq===o)return s;let a=Yo({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),l=KF(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:o,message:{...l,seq:o},lost:a.grade_counts};return Xx.set(n,p),p}function cw(e,t,n){let r=Zx.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let o=[...n].sort(UF),{paired:s,used:i}=qF(o),a={tool_input:0,cut_point:0,attachment:0},l=[];for(let m of o){if(i.has(m))continue;let f=GF(e,t,m,s.get(m),l.length+1);for(let _ of["tool_input","cut_point","attachment"])a[_]+=f.lost[_];l.push(f.message)}let p=FF(o.map(Fy).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=l.filter(m=>m.role==="user"&&m.kind==="turn"),g={...tw,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:ce,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:l[0]?.created_at||p,messages:l,ext:{opencode:{version:ke,native_id:t}}}]};return Zx.set(n,{sessionId:e,native:t,log:g}),g}var Ny=new WeakMap,xn=new WeakMap,lw=new WeakMap;function Xs(e){let t,n=xn.get(e);return n&&(t=WF(n).get(e.id)),t?(Ny.set(t,e),t):(e.type!=="harness"?t=Pm(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=lw.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},lw.set(e,t)),t&&Ny.set(t,e),t)}var Vr=e=>Ny.get(e),Ot=e=>e.flatMap(t=>Xs(t)??[]),uw=new WeakMap;function WF(e){let t=uw.get(e);return t||uw.set(e,t=new Map(ft(e)[0]?.parts.map(n=>[n.id,n]))),t}var pw=new Map;function ft(e){let t=pw.get(e.thread_id);return t||(t={schema:ce,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},pw.set(e.thread_id,t)),iw(t,e)}var HF="kortix-v1-import",By={schema:ce,v:1};function Zs(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var Ky=e=>e.type==="tool_call",VF=e=>e.status==="pending"||e.status==="running",qy=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function hw(e,t){let n=qy(e);return!VF(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var dw=new WeakMap;function _w(e,t){let n=dw.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),o={...By,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"kortix-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return dw.set(e,o),o}var gw=new WeakMap;function zF(e){let t=gw.get(e);return t||(t={...By,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},gw.set(e,t)),t}var mw=new WeakMap;function YF(e){let t=mw.get(e);return t||(t={...By,message_id:`${e.message_id}:continued`,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},mw.set(e,t)),t}var JF=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function QF(e,t){let n=[],r=new Map;for(let g of e){if(g.role!=="user"||g.kind==="context"||r.has(g.message_id))continue;let m={user:g,assistant:[],partial:!1};r.set(g.message_id,m),n.push(m)}let o=[],s=[],i=new Map,a=new Map,l=null,p=null;for(let g of e){if(g.role==="user"){let y=r.get(g.message_id);y&&!t.has(g.message_id)&&(l=y,i.has(y)||i.set(y,i.size),y.user.kind==="compaction"&&(p=y));continue}if(g.role!=="assistant"||JF(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??l;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let y=a.get(p);y||(y={user:YF(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,y)),f=y}if(f){f.assistant.push(g);continue}if(!g.reply_to){s.push(g);continue}let _=o[o.length-1];_&&_.user.message_id===g.reply_to?_.assistant.push(g):o.push({user:zF(g),assistant:[g],partial:!0})}if(s.length){let g=n[0]??o[0];g?g.assistant.unshift(...s):n.push({user:s[0],assistant:s.slice(1),partial:!1})}let d=n.filter(g=>!t.has(g.user.message_id)).flatMap(g=>{let m=a.get(g);return m?[g,m]:[g]});return[...o,...d,...[...t].flatMap(g=>r.get(g)??[])]}function XF(e,t){if(!t)return t;let n=t;for(let r of e){let o=r.continues;o&&(n===o.marker||n===o.prompt||t===o.prompt)&&(n=r.user.message_id)}return n}function bw(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=ft(n)[0]?.info?.error??n.error.message,o=be(r),s=Cr(r);return{code:n.error.code,message:o?.message||fe(r),...o&&{details:o},...s!==void 0&&{raw:s}}}function ZF(e,t,n){return e.length&&e.every(t)?Ws(e.flatMap(r=>ft(r).flatMap(o=>o.parts.map(s=>({part:s,message:o})))),n)??null:Gy(e,n)}function Gy(e,t){let n=e.flatMap(r=>{let o=r.usage;if(!o)return[];let s={type:"step-finish",cost:o.cost??0,tokens:{input:o.input,output:o.output,reasoning:o.reasoning??0,cache:{read:o.cache_read,write:o.cache_write}}};return[{part:s,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[s]}}]});return Ws(n,t)??null}function eN(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function tN(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&Ky(n)&&n.name==="bash"?n:null}function nN(e,t,n,r){if(!n.length)return[];let o=new Set(e.assistant.map(i=>i.message_id)),s=new Set;for(let i of n)i.spawned_by&&o.has(i.spawned_by.message_id)&&s.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:Ky(i)?Or(i):void 0;a&&r.has(a)&&s.add(a)}return[...s]}var rN=e=>e.assistant.some(t=>t.blocks.some(n=>Ky(n)&&ae(n.name)==="todowrite"&&gn(n))),oN=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function sN(e,t){let n=e.map(o=>bw(o)!==null),r=e.map((o,s)=>n[s]===!0&&t[s+1]===!0);return e.map((o,s)=>{if(r[s])return{continued:!0,retries:0};if(!n[s])return;let i=0;for(let a=s-1;a>=0&&r[a];a--)i+=1;return i>0?{continued:!1,retries:i}:void 0})}var fw=new WeakMap,iN=[];function Wy(e){let t=Zs(e.messages,n=>n.role==="assistant");return!!t&&sy(ft(t))}var yw=new WeakMap;function aN(e){let t=yw.get(e);if(!t){let n=e.messages.filter(r=>r.in_context||r.status==="streaming");t=n.length===e.messages.length?e:{...e,messages:n},yw.set(e,t)}return t}function ei(e,t={}){let n=t.hideOutOfContext?aN(e):e,r=new Set(t.held??iN),o=QF(n.messages,r),s=Zs(n.messages,y=>y.role==="assistant"),i=Wy(n),a=Py({turns:o.map(y=>({userMessage:{info:{id:y.user.message_id}},assistantMessages:y.assistant.map(k=>({info:{time:k.status==="streaming"?{}:{completed:1},error:k.error??void 0}}))})),hintMessageId:XF(o,t.liveMessageId),unrunTurnIds:r}),l=Zs(o,rN)??o[o.length-1],p=o.map(y=>!y.partial&&oN(y.user)),d=sN(o,p),g=rw(n),m=y=>g||y.producer.harness===HF,f=t.threads??[],_=new Set(f.map(y=>y.thread_id));return o.map((y,k)=>{let R=t.busy===!0&&a.workingTurnId===y.user.message_id,I=a.pendingTurnIds.includes(y.user.message_id),b=i&&y.assistant.includes(s),M=d[k],h=`${y.partial}|${R}|${I}|${y===l}|${b}|${M?(M.continued?"c":"")+M.retries:"-"}`,x=fw.get(y.user);if(x&&x.key===h&&x.pricing===t.pricing&&x.heads===t.threads&&x.assistant.length===y.assistant.length&&x.assistant.every((w,D)=>w===y.assistant[D]))return x.turn;let P=y.assistant.flatMap(w=>w.blocks);for(let w of y.assistant)for(let D of w.blocks)xn.set(D,w);let v=nN(y,P,f,_),T=y.assistant[y.assistant.length-1],L={internal:p[k],autoRetry:M,id:y.user.message_id,user:y.user,assistant:y.assistant,partial:y.partial,continues:y.continues??null,blocks:P,status:b?"streaming":T?T.status:y.user.kind==="compaction"?y.user.status:"pending",error:bw(y),cost:ZF([y.user,...y.assistant],m,t.pricing),compaction:eN(y.user),threads:v,plan:y===l,shell:tN(y),response:Zs(P,w=>w.type==="text"&&!!w.text.trim())??null,attachments:y.user.blocks.filter(w=>w.type==="attachment"&&(w.mime.startsWith("image/")||w.mime==="application/pdf")),live:R,queued:I,retrying:b};return fw.set(y.user,{assistant:y.assistant,key:h,pricing:t.pricing,heads:t.threads,turn:L}),L})}var Hy=e=>Vr(e);function ww(e,t={}){return hy(yy(Ot(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Vr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Hy)}:n.kind==="text"?{kind:n.kind,block:Vr(n.part)}:{kind:n.kind,block:Hy(n.part)})}var cN=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:Ot(e.blocks)}:{kind:e.kind,part:Xs(e.block)};function kw(e,t){let n=new Map(e.map(s=>[cN(s),s])),r=Ay([...n.keys()],t);if(!r)return null;let o=s=>s.map(i=>n.get(i));return{work:o(r.work),hoisted:o(r.hoisted),final:o(r.final)}}function lN(e){if(!ee(e)||!Sm(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=ey(e);return(n.answers??Ry(n.outputText??"",t.length)??[]).length>0}function vw(e){return fy(Ot(e),n=>yn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(lN)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:Vr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Hy),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(s=>s.id===n.key.slice(8)),o=r&&xn.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!o||o.status==="streaming"),durationMs:n.durationMs}})}function Aw(e,t){return xy(Ot(e.blocks).map(n=>({part:n})),t?.flatMap(ft))}function Rw(e){return Bs(Ot(e))}function Cw(e){return gy(Ot(e))}function Tw(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=Xs(n),o=xn.get(n);return!!r&&we(r)&&Ks(r)&&(!o||o.status==="streaming")}):!1}var Pw=new WeakMap;function Iw(e){if(!qy(e))return e;let t=Pw.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},Pw.set(e,t)}return t}function uN(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function Ew(e){let t=e.map(se),n=t[0],r=t.some(s=>s.state.status==="running"||s.state.status==="pending"),o=_y(t).map(uN);return lr({...n,state:{...n.state,status:r?"running":"completed",input:{items:o}}})}function Mw(e,t,n){let r=se(e),o=r.state;return lr({...r,state:{...o,status:"completed",...n!==void 0&&{input:n},metadata:{...o.metadata??{},answers:t}}})}function Ow(e){let t=ft(e).map(r=>Ds(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}var Sw=Object.freeze([]),xw=new WeakMap;function Dw(e){if(!e)return Sw;let t=xw.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(o=>o.type==="tool_call"&&gn(o)):[]);t=n.length?n:Sw,xw.set(e,t)}return t}function Lw(e,t={}){let n={cost:0,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of ei(e)){let o=Gy([r.user,...r.assistant],t.pricing);if(o){n.cost+=o.cost;for(let s of Object.keys(n.tokens))n.tokens[s]+=o.tokens[s]}}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let o=r.usage;(r.role==="assistant"||r.kind==="compaction")&&o&&o.input+o.output+(o.reasoning??0)+o.cache_read+o.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}var pN="prt_kortix_restore_g";function $w(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(pN))}function Uw(e,t){let n=new Map,r=[...e??[]].sort((o,s)=>o.from_seq-s.from_seq);for(let o=1;o<r.length;o++){let s=r[o],i=r[o-1].harness;if(s.harness===i)continue;let a=t.findIndex(l=>l.user.seq>=s.from_seq);a<0||a===0&&t[0].user.seq!==s.from_seq||n.set(t[a].id,{harness:s.harness,previous:i,version:s.version,at:s.at})}return n}var Vy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ze=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,dN=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function Fw(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=Vy(t)?t.restore:void 0;if(!Vy(n))return null;let r=Vy(n.dropped)?n.dropped:{},o=e.grade_counts,s=[{kind:"message",count:Ze(r.message)},{kind:"attachment",count:Ze(o?.attachment)},{kind:"text",count:Ze(r.text)+Ze(n.truncated)},{kind:"tool_input",count:Ze(o?.tool_input)},{kind:"tool_result",count:Ze(r.tool_result)},{kind:"cut_point",count:Ze(o?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,l])=>dN.has(a)?i:i+Ze(l),0)}];return{generation:Ze(n.generation),missing:s.filter(i=>i.count>0)}}var Nw=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function Bw(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let o of Nw(r))o.ref&&o.bytes!==void 0&&!t.has(o.ref)&&t.set(o.ref,o.bytes);return[...t].map(([n,r])=>({ref:n,bytes:r}))}var Kw=(e,t)=>{let n=e.ref===void 0?void 0:t.get(e.ref);if(n===void 0)return e;let{ref:r,bytes:o,...s}=e;return{...s,text:n}},gN=(e,t)=>e.map(n=>n.type==="text"?Kw(n,t):n),jw=new WeakMap;function mN(e,t){let n=jw.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(o=>Nw(o).some(s=>s.ref!==void 0&&t.has(s.ref)))?{...e,blocks:e.blocks.map(o=>o.type==="text"?Kw(o,t):o.type==="tool_call"&&o.result?{...o,result:{...o.result,content:gN(o.result.content,t)}}:o)}:e;return jw.set(e,{texts:t,out:r}),r}var ti=1024*1024;function qw(e){return e.reduce((t,n)=>t+n.bytes,0)>ti?"download":"inline"}function Gw(e){let t=new Set,n=0;for(let r of[...e].sort((o,s)=>o.bytes-s.bytes)){if(n+r.bytes>ti)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function Ww(e,t){if(t.size===0)return e;let n=e.messages.map(r=>mN(r,t));return n.every((r,o)=>r===e.messages[o])?e:{...e,messages:n}}function fN(e){return e==="TIMEOUT"||e==="request_deadline"}function yN(e){let t=Vw(e)?e.code:void 0;return typeof t=="string"?t:void 0}var Vw=e=>typeof e=="object"&&e!==null;function Hw(e){let t=e?.metadata;return!!Vw(t)&&t.warm===!0}var hN=5,_N=2e3,bN=e=>new Promise(t=>setTimeout(t,e));async function PN(e,{attempts:t=hN,delayMs:n=_N,sleep:r=bN}={}){for(let o=0;o<t;o++){o>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function SN(e,t){let n=new Map,r=new Set,o=new Set,s=new Set,i=0,a=(l,p,d)=>{if(r.has(l)||n.has(l))return Promise.resolve();r.add(l);let g=i,m=(async()=>{let f=null;try{let _=await e.ensure(l,p);if(g!==i)return;o.has(_.sessionId)?f=_.sessionId:n.set(l,_)}catch{}finally{g===i&&r.delete(l)}f&&d>0&&await a(l,f,d-1)})();return s.add(m),m.finally(()=>s.delete(m)),m};return{ensure:(l,p)=>a(l,p?.excludeSessionId,1),take:(l,p,{replenish:d})=>{let g=n.get(l);return g?(n.delete(l),o.add(g.sessionId),d&&a(l,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(l,p,d)=>{try{return await e.claim(l,d),!0}catch(g){return fN(yN(g))?PN(async()=>!Hw(await e.read(l,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:l=>{for(let[p,d]of n)if(d.sessionId===l)return n.delete(p),o.add(l),p;return null},revalidate:async l=>{let p=n.get(l);if(!p)return!1;try{if(Hw(await e.read(l,p.sessionId)))return!1}catch{return!1}return n.get(l)?.sessionId!==p.sessionId?!1:(n.delete(l),o.add(p.sessionId),!0)},held:l=>n.get(l)??null,reset:()=>{i+=1,n.clear(),r.clear(),o.clear()},settled:async()=>{for(;s.size>0;)await Promise.all([...s])}}}var xN=12e4,ni=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},wN=1e3,kN=15e3,zw=100,vN=50,AN=10;function Yw(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:o},s)=>{let i=new URLSearchParams({limit:String(r)});o&&i.set("before",o);let a=await e.getToken?.(),l=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...s?{signal:s}:{}});if(!l.ok)throw l.status===503?new qr(`session ${l.status}`):new S(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function Jw(e){return RN(Yw(e))}function Qw(e){return new zy({...e,loadPage:Yw(e)})}async function RN(e){let t=[],n=new Set,r;do{let i=await e({limit:zw,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let o=[],s=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])s.has(a.info.id)||(s.add(a.info.id),o.push(a));return o}var CN={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},zy=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??CN,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??xN,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed||t==="visible"&&this.streamReliable&&this.snapshot.freshness==="fresh"?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":this.snapshot.freshness}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof ni;if(!r&&Br(n))return;if(r||this.update({freshness:bn(n)?"loading":"error"}),n instanceof S&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(wN*2**this.retryAttempt,kN);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let o=this.scheduler.now();try{let s=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?vN:zw,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:s.messages.length,succeeded:!0}),s}catch(s){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:0,succeeded:!1}),s}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,o=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",o,{once:!0});let s,i=new Promise((l,p)=>{s=this.startTimer(()=>{let d=new ni(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(l){a=Promise.reject(l)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(s),n.removeEventListener("abort",o)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,o,s){let i=[...t.messages],a=new Set(this.knownUserMessageIds),l=new Set(o?[o]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<AN&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(l.has(p))throw new Error(`Session history cursor repeated: ${p}`);l.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw s?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,s?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let o,s=!1,i=()=>{s||(s=!0,this.cancelTimer(o),r())};o=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};var TN=5e3,Zw=40,OQ=5*6e4,IN=16,zr=new Map;function ek(e,t,n,r=Date.now()){let o=tk(e,t);for(zr.delete(o),zr.set(o,{envelope:n,atMs:r});zr.size>IN;){let s=zr.keys().next().value;if(s===void 0)break;zr.delete(s)}}var Xw=new Map;function tk(e,t){return`${e}/${t}`}function EN(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=TN}function nk(e,t,n=Date.now()){if(!e||!t)return null;let r=tk(e,t),o=Xw.get(r);return o?EN(o,n)?o.promise:(Xw.delete(r),null):null}function rk(e){let t=e.transcript;if(!t||t.known!==!0||t.requested!==!0)return null;let{known:n,requested:r,...o}=t;if(!o.available)return o;let s=e.session?.runtime_session_id??e.session?.opencode_session_id,i=o.runtime_session_id??o.opencode_session_id;return s&&i===s?o:null}var ok=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function MN(e,t){let n=(e[t.thread_id]??[]).filter(o=>o.message_id!==t.message_id),r=n.length;for(;r>0&&n[r-1].seq>t.seq;)r--;return n.splice(r,0,t),{...e,[t.thread_id]:n}}function sk(e,t,n){let r=e.messages,o=e.older,s=t.thread_id,i=s===null?void 0:r[s];if(s!==null){let p=t.messages[0]?.seq;(n!==void 0||!i?.length||!t.has_more||p!==void 0&&p<=i[0].seq)&&e.older[s]!==t.has_more&&(o={...o,[s]:t.has_more})}if(s!==null&&i){let p=t.has_more?t.messages[0]?.seq??1/0:-1/0,d=n??1/0,g=new Set(t.messages.map(f=>f.message_id)),m=i.filter(f=>f.seq<p||f.seq>=d||g.has(f.message_id)||e.revs[f.message_id]!==void 0);m.length!==i.length&&(r={...r,[s]:m})}for(let p of t.messages)!Ml(p)||e.revs[p.message_id]!==void 0||(r=MN(r,p));let a={...e.threads};for(let p of t.threads)Ol(p)&&(a[p.thread_id]=p);let l=t.generation>e.generation;return{...e,generation:Math.max(t.generation,e.generation),session:l?{...e.session,...t.session}:{...t.session,...e.session},threads:a,messages:r,older:o}}var ON=2e3;async function DN(e,t,n){let r=nk(e,t),o,s=r?await Promise.race([r,new Promise(i=>{o=setTimeout(i,n.snapshotWaitMs??ON,null)})]).finally(()=>clearTimeout(o)):null;return(s&&rk(s))??Hn(e,t,{limit:Zw,history:!0,signal:n.signal})}async function ak(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};if(e.sessionLog){let s=Gn?await t_(Gn,t,n):null,i=s&&sw(sk(ok,s));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await ik(t,n,r),log:s}}let o;try{o=await DN(t,n,{})}catch{return{envelope:null,empty:!1}}return ek(t,n,o),Yy(o)!==r?{envelope:o,empty:!1}:{envelope:o,empty:await ik(t,n,r)}}async function ik(e,t,n){try{let r=await Vn(e,t);return Jy({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function Yy(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function Jy(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function LN(e){throw F("buildTunnelEventStreamUrl")}function jN(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,onClose:l,signal:p}=e,d=new Map,g=null,m=!1,f="";function _(b,M){s?.(b,M);let h=d.get(b);if(h)for(let x of h)try{x(M)}catch{}}async function y(){if(m)return;let b=new AbortController;g=b,p&&(p.aborted?b.abort():p.addEventListener("abort",()=>b.abort(),{once:!0}));let M=b.signal;try{let h={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(h["Content-Type"]="application/json"),f&&(h["Last-Event-ID"]=f);let x=await fetch(t,{method:r,headers:h,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:M,credentials:"include"});if(!x.ok)throw new Error(`SSE connection failed: ${x.status} ${x.statusText}`);if(!x.body)throw new Error("SSE response has no body");i?.();let P=x.body.getReader(),v=new TextDecoder,T="",L="message",w=[],D=N=>{if(N===""){w.length>0&&_(L,w.join(`
98
+ `)),L="message",w=[];return}if(N.startsWith(":"))return;let z=N.indexOf(":"),G=z===-1?N:N.slice(0,z),K=z===-1?"":N.slice(z+1);K.startsWith(" ")&&(K=K.slice(1)),G==="event"?L=K.trim()||"message":G==="data"?w.push(K):G==="id"&&!K.includes("\0")&&(f=K)},Se=N=>{let z="";!N&&T.endsWith("\r")&&(z="\r",T=T.slice(0,-1));let G=T.split(/\r\n|\n|\r/);T=(G.pop()??"")+z;for(let K of G)D(K)};for(;!m;){let{done:N,value:z}=await P.read();if(N)break;T+=v.decode(z,{stream:!0}),Se(!1)}m||(T+=v.decode(),Se(!0),l?.())}catch(h){if(m||h instanceof DOMException&&h.name==="AbortError")return;a?.(h instanceof Error?h:new Error(String(h)))}}function k(){m=!0,g?.abort(),g=null,d.clear()}function R(b,M){let h=d.get(b)??new Set;h.add(M),d.set(b,h)}function I(b,M){d.get(b)?.delete(M)}return{connect:y,close:k,addEventListener:R,removeEventListener:I}}function $N(e,t){throw F("createTunnelEventStream")}var ck="/_kortix/viewer",ri=6e4,wn=new Map;function lk(){wn.clear(),Yr.clear()}async function UN(e,t){let n;try{n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}})}catch{return null}if(n.status===401||n.status===404||!n.ok)return null;let r=await n.json().catch(()=>null);return r&&typeof r.user_id=="string"?r:null}async function Qy(e={}){let t=e.path??ck,n=e.fetch??((s,i)=>fetch(s,i)),r=wn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=UN(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-ri:Date.now()+ri;return wn.set(t,{session:s,expiresAt:a}),s});return wn.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function uk(e={}){let t=e.path??ck;return Object.assign(async()=>(await Qy(e))?.access_token??null,{invalidate:n=>{let r=wn.get(t);r&&!r.inflight&&r.session?.access_token===n&&wn.delete(t)}})}var Yr=new Map;async function FN(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let s=await n.json().catch(()=>null);s?.error==="app_not_linked"&&console.warn(`[kortix] ${String(s.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let o=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return Yr.set(e,{token:r.token,refreshAt:Number.isFinite(o)?o-ri:Date.now()+ri}),r.token}catch{return null}}function Xy(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((o,s)=>fetch(o,s));return async(o={})=>{let s=Yr.get(n);if(s instanceof Promise)return s;if(s&&!o.forceRefreshToken&&s.refreshAt>Date.now())return s.token;let i=FN(n,r).then(a=>(a===null&&Yr.delete(n),a));return Yr.set(n,i),i}}function pk(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("kortixBinding needs the App origin: pass { origin } outside a browser.");return{url:`${le(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:Xy({audience:e,fetch:t.fetch})}}var yt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},Pe=e=>typeof e=="string"&&e.length>0?e:null;function dk(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function oi(e){if(!e||typeof e!="object")return null;let t=e,n=Pe(t.sub)??Pe(t.subject)??Pe(t.user_id)??Pe(t.userId);return n?{userId:n,email:Pe(t.email),name:Pe(t.name),picture:Pe(t.picture)??Pe(t.pictureUrl),groups:dk(t.groups),groupIds:dk(t.group_ids??t.groupIds),role:Pe(t.role),accountId:Pe(t.account_id)??Pe(t.accountId),projectId:Pe(t.project_id)??Pe(t.projectId)}:null}function mk(e,t={}){let n=oi(e);if(!n)throw new yt("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:o}=t;if(r&&!r.some(s=>n.groups.includes(s)||n.groupIds.includes(s)))throw new yt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(o&&!o.some(s=>n.role===s))throw new yt("forbidden",`Only ${o.join(" or ")||"no role"} members may do this.`);return n}var NN=60,Zy=new Map;function fk(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function gk(e){return JSON.parse(new TextDecoder().decode(fk(e)))}async function BN(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),o=e.slice(n+1),s=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(o),i=>i.charCodeAt(0))):decodeURIComponent(o);return JSON.parse(s)}if(/^https?:\/\//.test(e)){let n=Zy.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>Zy.delete(e)),Zy.set(e,n)),n}return JSON.parse(e)}async function yk(e,t={}){let n=b=>{throw new yt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??ot("KORTIX_AUTH_JWKS"),o=t.issuer??ot("KORTIX_AUTH_ISSUER"),s=t.audience??ot("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(s!==!1&&!s)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,l,p]=i,d,g;try{d=gk(a),g=gk(l)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await BN(r,t.fetch??((b,M)=>fetch(b,M)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(b=>b.kty==="EC"&&(d.kid===void 0||b.kid===d.kid));if(f.length===0)return n("unknown key");let _=new TextEncoder().encode(`${a}.${l}`),y;try{y=fk(p)}catch{return n("malformed")}let k=!1;for(let b of f)try{let{kid:M,alg:h,use:x,key_ops:P,...v}=b,T=await crypto.subtle.importKey("jwk",v,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},T,y,_)){k=!0;break}}catch{}if(!k)return n("bad signature");let R=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+NN<R)return n("expired");if(o&&g.iss!==o)return n("wrong issuer");if(s){let b=g.aud;if(!(b===s||Array.isArray(b)&&b.includes(s)))return n("wrong audience")}let I=oi(g);return I||n("no subject")}function eh(e){let t=e.agents.map(KN),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function KN(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.hidden===!0||e.enabled===!1}}function th(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Xo(n?{...r,mode:null}:r))}function hk(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let s=e.selectedAgent?.trim();return s?{selected:s,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=th(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(s=>s.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let o=e.defaultAgent?.trim();return o&&n.some(s=>s.name===o)?{selected:o,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var _k=eh;function bk(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function nh(e){return{providerID:"kortix",modelID:e}}function kn(e,t){return nh(e.startsWith("kortix/")?e.slice(7):e)}var rh=[{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"infer",env:["INFER_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]}];function oh(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function GN(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function Pk(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o);s?s.push(r):n.set(o,[r])}return n}function Jr(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function Sk(e){return e.reduce((t,n)=>{let r=oh(n)??0,o=oh(t)??0;return r!==o?r>o?n:t:Jr(n.id)>Jr(t.id)?n:t})}function sh(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of Pk(e,GN)){let a=[...Pk(s,p=>p.family||p.id).values()].map(Sk),l=a.filter(p=>{let d=oh(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[Sk(a)])o.add(p.id)}return o}function ih(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>Jr(r.id)>0)?n.filter(r=>Jr(r.id)>0):n}var WN={"amazon-bedrock":{methods:[{label:"Bearer token",envVars:["AWS_BEARER_TOKEN_BEDROCK","AWS_REGION"]}]},google:{methods:[{envVars:["GOOGLE_GENERATIVE_AI_API_KEY"]},{envVars:["GOOGLE_API_KEY"]},{envVars:["GEMINI_API_KEY"]}]}};function wk(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var HN=(()=>{let e=new Map;for(let{id:n,env:r}of rh)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let o=[...r].sort((s,i)=>s.length-i.length||s.localeCompare(i));t.set(n,r.find(s=>wk(s)===n)??o[0])}return t})();function kk(e){let t=WN[e.id];if(t)return t;let n=e.env??[],r=n.length===1?HN.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[wk(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}var VN=["low","medium","high"];function vk(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...VN]}:void 0,o=e.temperature===!0,s=e.limit?.output,i=typeof s=="number"&&s>0?{ceiling:s}:void 0;return{reasoningEffort:r,temperature:o,topP:o,maxOutputTokens:i}}var Ak=rh;var xk={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var si=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash-1017",transport:"openrouter",morphModelId:"morph-dsv41flash-1017",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"deepinfra/fp8":{inputPerMillion:.098,cachedInputPerMillion:.00294,outputPerMillion:.294},"deepinfra/fp8/priority":{inputPerMillion:.147,cachedInputPerMillion:.00441,outputPerMillion:.441},"inference-net/fp8":{inputPerMillion:.08,cachedInputPerMillion:.008,outputPerMillion:.5},"wafer/mxfp4":{inputPerMillion:.1,cachedInputPerMillion:.003,outputPerMillion:.5},cloudflare:{inputPerMillion:.1,cachedInputPerMillion:.003,outputPerMillion:.6}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["deepinfra/fp8","deepinfra/fp8/priority","inference-net/fp8","wafer/mxfp4","cloudflare"],...xk,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{fireworks:{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"deepinfra/fp4":{inputPerMillion:.075,cachedInputPerMillion:.015,outputPerMillion:.25},together:{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"parasail/fp4":{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"modal/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"crusoe/fp4":{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"inference-net/fp4":{inputPerMillion:.12,cachedInputPerMillion:.032,outputPerMillion:.388},makora:{inputPerMillion:.14,cachedInputPerMillion:.024,outputPerMillion:.47},"near-ai/fp8":{inputPerMillion:.08,cachedInputPerMillion:.012,outputPerMillion:.5},"open-inference/fp4":{inputPerMillion:.048,cachedInputPerMillion:.006,outputPerMillion:.16},primeintellect:{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"siliconflow/fp8":{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},venice:{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["fireworks","deepinfra/fp4","together","parasail/fp4","modal/nvfp4","crusoe/fp4","inference-net/fp4","makora","near-ai/fp8","open-inference/fp4","primeintellect","siliconflow/fp8","venice"],...xk,max_price:{prompt:.15,completion:.5}}}],oX=new Map(si.map(e=>[e.id,e]));var Rk=si.map(e=>e.id),Ck=(si.find(e=>e.tier==="flagship")??si[0]).id;var lX=Ak.map(e=>({id:e.id,authRequirement:kk(e)})),Tk=new Set(["kortix"]);function zN(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,o])=>{if(o.variants&&Object.keys(o.variants).length>0)return[r,o];let s=vk({id:r,name:o.name,reasoning:o.reasoning,reasoning_options:o.reasoning_options}).reasoningEffort?.values;return s?.length?[r,{...o,variants:Object.fromEntries(s.map(i=>[i,{}]))}]:[r,o]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function Ik(e){return e.modelPicker?zN(e.modelPicker):void 0}function YN(e){return"capabilities"in e&&e.capabilities!=null}function ii(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function Ek(e,t){if(!e)return[];let n=Array.isArray(e.all)?e.all:[],r=Array.isArray(e.connected)?e.connected:[],o=[];for(let s of n)if(r.includes(s.id)&&Tk.has(s.id))for(let[i,a]of Object.entries(s.models)){if(i==="auto"||i==="kortix/auto")continue;let l;if(YN(a)){let p=a.capabilities;l={reasoning:p.reasoning??!1,vision:p.input?p.input.image??!1:void 0,toolcall:p.toolcall??!1}}else{let p=a.modalities?.input;l={reasoning:a.reasoning??!1,vision:p?p.includes("image"):a.attachment,toolcall:a.tool_call??!1}}o.push({id:bk({providerID:s.id,modelID:i}),providerID:s.id,providerName:a.provider_name??s.name,modelID:i,modelName:(a.name||i).replace("(latest)","").trim(),variants:a.variants,capabilities:l,contextWindow:a.limit?.context,releaseDate:a.release_date,family:a.family,cost:a.cost?{input:a.cost.input??0,output:a.cost.output??0}:void 0,providerSource:s.source,provider:a.provider,reasoningOptions:a.reasoning_options,description:a.description,openWeights:a.open_weights,lastUpdated:a.last_updated,enabled:a.enabled,free:a.free===!0})}return o}function Mk(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var JN=new Set([Ck]),QN="kortix",Ok="codex",XN=new Set(Rk);function ZN(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function vn(e){return JN.has(e.modelID)}function eB(e){return sh(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Dk(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=eB(e.catalogModels),o=Mk(e.catalogModels),s=new Map;for(let i of e.pins??[])s.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,l=s.get(a);if(l==="hide")return!1;if(i.providerID===QN){let d=ZN(i.modelID,i.provider),g=d===Ok?t?.has(Ok)??!1:t?.has(d)??!1;if(XN.has(i.modelID))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return vn(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return vn(i)}catch{return vn(i)}return!1}if(l==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return vn(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return vn(i)}catch{return vn(i)}return!1}}function Lk(e,t){return t.search.trim().length>0||e.providerID==="kortix"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function jk(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault);return n?nh(n):void 0}function $k(e){for(let t=(e?.length??0)-1;t>=0;t--){let n=e[t],{provider:r,model:o}=n.model??{};if(n.role==="user"&&r&&o)return{providerID:r,modelID:o}}}var tB=new Set(["explicit","repointed","fallback"]);function Uk(e){let t=e?.metadata;if(t?.opencode_model_source!=="fallback")return;let{opencode_model:n,opencode_model_fallback_from:r,opencode_model_fallback_at:o}=t;if(typeof n!="string"||typeof r!="string"||typeof o!="number")return;let s=t.opencode_model_fallback_reason;return{model:kn(n),from:kn(r),reason:typeof s=="string"?s:"other",atMs:o}}function Fk(e,t){return!t||(e??-1)>=t.atMs}function Nk(e){let t=e.session?Qn(e.session):null,n=t?kn(t):void 0,r=e.session?.metadata;return(tB.has(String(r?.opencode_model_source))||r?.opencode_model_restored===!0?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(i=>!!i)}function Bk(e){let{models:t,providers:n}=e,r=l=>ii(t,l),o=l=>l.find(p=>!!p&&r(p)),s=(()=>{if(e.configModel){let l=e.configModel.split("/");if(l.length>=2){let[p,...d]=l,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let l of e.recent??[])if(r(l))return l;if(n){let l=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=l[m.id];if(f){let _={providerID:m.id,modelID:f};if(r(_))return _}for(let _ of ih(Object.keys(m.models).map(y=>({id:y})))){let y={providerID:m.id,modelID:_.id};if(r(y))return y}}}})(),i=o(e.picks??[]);return{model:i??o([e.serverDefault,e.globalDefault,e.agentModel,s]),explicit:i,fallback:s}}return zk(nB);})();