@xenosystem/agent-cli 0.5.181 → 0.5.183

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 (864) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/index.js +2452 -2452
  3. package/dist/metafile-esm.json +1 -1
  4. package/dist/sdk-build-identity.json +11 -11
  5. package/node_modules/@xeno-corporation/account/LICENSE +39 -0
  6. package/node_modules/@xeno-corporation/account/README.md +266 -0
  7. package/node_modules/@xeno-corporation/account/dist/chunk-FELZILY4.mjs +60 -0
  8. package/node_modules/@xeno-corporation/account/dist/chunk-FELZILY4.mjs.map +1 -0
  9. package/node_modules/@xeno-corporation/account/dist/client-CVtf6u7F.d.mts +2346 -0
  10. package/node_modules/@xeno-corporation/account/dist/client-CVtf6u7F.d.ts +2346 -0
  11. package/node_modules/@xeno-corporation/account/dist/index.d.mts +110 -0
  12. package/node_modules/@xeno-corporation/account/dist/index.d.ts +110 -0
  13. package/node_modules/@xeno-corporation/account/dist/index.js +4115 -0
  14. package/node_modules/@xeno-corporation/account/dist/index.js.map +1 -0
  15. package/node_modules/@xeno-corporation/account/dist/index.mjs +3967 -0
  16. package/node_modules/@xeno-corporation/account/dist/index.mjs.map +1 -0
  17. package/node_modules/@xeno-corporation/account/dist/node.d.mts +109 -0
  18. package/node_modules/@xeno-corporation/account/dist/node.d.ts +109 -0
  19. package/node_modules/@xeno-corporation/account/dist/node.js +1448 -0
  20. package/node_modules/@xeno-corporation/account/dist/node.js.map +1 -0
  21. package/node_modules/@xeno-corporation/account/dist/node.mjs +1374 -0
  22. package/node_modules/@xeno-corporation/account/dist/node.mjs.map +1 -0
  23. package/node_modules/@xeno-corporation/account/package.json +62 -0
  24. package/node_modules/zod/LICENSE +21 -0
  25. package/node_modules/zod/README.md +218 -0
  26. package/node_modules/zod/compile.cjs +96 -0
  27. package/node_modules/zod/compile.d.cts +1 -0
  28. package/node_modules/zod/compile.d.ts +1 -0
  29. package/node_modules/zod/compile.js +52 -0
  30. package/node_modules/zod/index.cjs +52 -0
  31. package/node_modules/zod/index.d.cts +3 -0
  32. package/node_modules/zod/index.d.ts +3 -0
  33. package/node_modules/zod/index.js +7 -0
  34. package/node_modules/zod/locales/index.cjs +36 -0
  35. package/node_modules/zod/locales/index.d.cts +1 -0
  36. package/node_modules/zod/locales/index.d.ts +1 -0
  37. package/node_modules/zod/locales/index.js +1 -0
  38. package/node_modules/zod/locales/package.json +7 -0
  39. package/node_modules/zod/mini/index.cjs +51 -0
  40. package/node_modules/zod/mini/index.d.cts +3 -0
  41. package/node_modules/zod/mini/index.d.ts +3 -0
  42. package/node_modules/zod/mini/index.js +3 -0
  43. package/node_modules/zod/mini/package.json +7 -0
  44. package/node_modules/zod/package.json +147 -0
  45. package/node_modules/zod/src/compile.ts +56 -0
  46. package/node_modules/zod/src/index.ts +7 -0
  47. package/node_modules/zod/src/locales/index.ts +1 -0
  48. package/node_modules/zod/src/mini/index.ts +3 -0
  49. package/node_modules/zod/src/v3/ZodError.ts +340 -0
  50. package/node_modules/zod/src/v3/benchmarks/datetime.ts +58 -0
  51. package/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts +80 -0
  52. package/node_modules/zod/src/v3/benchmarks/index.ts +59 -0
  53. package/node_modules/zod/src/v3/benchmarks/ipv4.ts +57 -0
  54. package/node_modules/zod/src/v3/benchmarks/object.ts +69 -0
  55. package/node_modules/zod/src/v3/benchmarks/primitives.ts +162 -0
  56. package/node_modules/zod/src/v3/benchmarks/realworld.ts +63 -0
  57. package/node_modules/zod/src/v3/benchmarks/string.ts +55 -0
  58. package/node_modules/zod/src/v3/benchmarks/union.ts +80 -0
  59. package/node_modules/zod/src/v3/errors.ts +13 -0
  60. package/node_modules/zod/src/v3/external.ts +6 -0
  61. package/node_modules/zod/src/v3/helpers/enumUtil.ts +17 -0
  62. package/node_modules/zod/src/v3/helpers/errorUtil.ts +8 -0
  63. package/node_modules/zod/src/v3/helpers/parseUtil.ts +176 -0
  64. package/node_modules/zod/src/v3/helpers/partialUtil.ts +34 -0
  65. package/node_modules/zod/src/v3/helpers/typeAliases.ts +2 -0
  66. package/node_modules/zod/src/v3/helpers/util.ts +224 -0
  67. package/node_modules/zod/src/v3/index.ts +4 -0
  68. package/node_modules/zod/src/v3/locales/en.ts +124 -0
  69. package/node_modules/zod/src/v3/standard-schema.ts +113 -0
  70. package/node_modules/zod/src/v3/tests/Mocker.ts +54 -0
  71. package/node_modules/zod/src/v3/tests/all-errors.test.ts +157 -0
  72. package/node_modules/zod/src/v3/tests/anyunknown.test.ts +28 -0
  73. package/node_modules/zod/src/v3/tests/array.test.ts +71 -0
  74. package/node_modules/zod/src/v3/tests/async-parsing.test.ts +388 -0
  75. package/node_modules/zod/src/v3/tests/async-refinements.test.ts +46 -0
  76. package/node_modules/zod/src/v3/tests/base.test.ts +29 -0
  77. package/node_modules/zod/src/v3/tests/bigint.test.ts +55 -0
  78. package/node_modules/zod/src/v3/tests/branded.test.ts +53 -0
  79. package/node_modules/zod/src/v3/tests/catch.test.ts +220 -0
  80. package/node_modules/zod/src/v3/tests/coerce.test.ts +133 -0
  81. package/node_modules/zod/src/v3/tests/complex.test.ts +70 -0
  82. package/node_modules/zod/src/v3/tests/custom.test.ts +31 -0
  83. package/node_modules/zod/src/v3/tests/date.test.ts +32 -0
  84. package/node_modules/zod/src/v3/tests/deepmasking.test.ts +186 -0
  85. package/node_modules/zod/src/v3/tests/default.test.ts +112 -0
  86. package/node_modules/zod/src/v3/tests/description.test.ts +33 -0
  87. package/node_modules/zod/src/v3/tests/discriminated-unions.test.ts +315 -0
  88. package/node_modules/zod/src/v3/tests/enum.test.ts +80 -0
  89. package/node_modules/zod/src/v3/tests/error.test.ts +586 -0
  90. package/node_modules/zod/src/v3/tests/firstparty.test.ts +87 -0
  91. package/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts +21 -0
  92. package/node_modules/zod/src/v3/tests/function.test.ts +261 -0
  93. package/node_modules/zod/src/v3/tests/generics.test.ts +48 -0
  94. package/node_modules/zod/src/v3/tests/instanceof.test.ts +37 -0
  95. package/node_modules/zod/src/v3/tests/intersection.test.ts +128 -0
  96. package/node_modules/zod/src/v3/tests/language-server.source.ts +76 -0
  97. package/node_modules/zod/src/v3/tests/language-server.test.ts +206 -0
  98. package/node_modules/zod/src/v3/tests/literal.test.ts +36 -0
  99. package/node_modules/zod/src/v3/tests/map.test.ts +110 -0
  100. package/node_modules/zod/src/v3/tests/masking.test.ts +4 -0
  101. package/node_modules/zod/src/v3/tests/mocker.test.ts +19 -0
  102. package/node_modules/zod/src/v3/tests/nan.test.ts +24 -0
  103. package/node_modules/zod/src/v3/tests/nativeEnum.test.ts +87 -0
  104. package/node_modules/zod/src/v3/tests/nullable.test.ts +42 -0
  105. package/node_modules/zod/src/v3/tests/number.test.ts +176 -0
  106. package/node_modules/zod/src/v3/tests/object-augmentation.test.ts +29 -0
  107. package/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts +29 -0
  108. package/node_modules/zod/src/v3/tests/object.test.ts +431 -0
  109. package/node_modules/zod/src/v3/tests/optional.test.ts +42 -0
  110. package/node_modules/zod/src/v3/tests/parseUtil.test.ts +23 -0
  111. package/node_modules/zod/src/v3/tests/parser.test.ts +41 -0
  112. package/node_modules/zod/src/v3/tests/partials.test.ts +243 -0
  113. package/node_modules/zod/src/v3/tests/pickomit.test.ts +111 -0
  114. package/node_modules/zod/src/v3/tests/pipeline.test.ts +29 -0
  115. package/node_modules/zod/src/v3/tests/preprocess.test.ts +186 -0
  116. package/node_modules/zod/src/v3/tests/primitive.test.ts +440 -0
  117. package/node_modules/zod/src/v3/tests/promise.test.ts +90 -0
  118. package/node_modules/zod/src/v3/tests/readonly.test.ts +114 -0
  119. package/node_modules/zod/src/v3/tests/record.test.ts +171 -0
  120. package/node_modules/zod/src/v3/tests/recursive.test.ts +197 -0
  121. package/node_modules/zod/src/v3/tests/refine.test.ts +313 -0
  122. package/node_modules/zod/src/v3/tests/safeparse.test.ts +27 -0
  123. package/node_modules/zod/src/v3/tests/set.test.ts +142 -0
  124. package/node_modules/zod/src/v3/tests/standard-schema.test.ts +83 -0
  125. package/node_modules/zod/src/v3/tests/string.test.ts +922 -0
  126. package/node_modules/zod/src/v3/tests/transformer.test.ts +233 -0
  127. package/node_modules/zod/src/v3/tests/tuple.test.ts +90 -0
  128. package/node_modules/zod/src/v3/tests/unions.test.ts +57 -0
  129. package/node_modules/zod/src/v3/tests/validations.test.ts +133 -0
  130. package/node_modules/zod/src/v3/tests/void.test.ts +15 -0
  131. package/node_modules/zod/src/v3/types.ts +5138 -0
  132. package/node_modules/zod/src/v4/classic/checks.ts +33 -0
  133. package/node_modules/zod/src/v4/classic/coerce.ts +27 -0
  134. package/node_modules/zod/src/v4/classic/compat.ts +78 -0
  135. package/node_modules/zod/src/v4/classic/deep-partial.ts +76 -0
  136. package/node_modules/zod/src/v4/classic/errors.ts +97 -0
  137. package/node_modules/zod/src/v4/classic/external.ts +57 -0
  138. package/node_modules/zod/src/v4/classic/from-json-schema.ts +944 -0
  139. package/node_modules/zod/src/v4/classic/in-out.ts +45 -0
  140. package/node_modules/zod/src/v4/classic/index.ts +5 -0
  141. package/node_modules/zod/src/v4/classic/iso.ts +20 -0
  142. package/node_modules/zod/src/v4/classic/parse.ts +88 -0
  143. package/node_modules/zod/src/v4/classic/schemas.ts +2937 -0
  144. package/node_modules/zod/src/v4/classic/tests/anyunknown.test.ts +26 -0
  145. package/node_modules/zod/src/v4/classic/tests/apply.test.ts +86 -0
  146. package/node_modules/zod/src/v4/classic/tests/array.test.ts +291 -0
  147. package/node_modules/zod/src/v4/classic/tests/assignability.test.ts +402 -0
  148. package/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts +381 -0
  149. package/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts +68 -0
  150. package/node_modules/zod/src/v4/classic/tests/base.test.ts +7 -0
  151. package/node_modules/zod/src/v4/classic/tests/bigint.test.ts +89 -0
  152. package/node_modules/zod/src/v4/classic/tests/brand.test.ts +106 -0
  153. package/node_modules/zod/src/v4/classic/tests/catch.test.ts +604 -0
  154. package/node_modules/zod/src/v4/classic/tests/coalesce.test.ts +20 -0
  155. package/node_modules/zod/src/v4/classic/tests/codec-examples.test.ts +572 -0
  156. package/node_modules/zod/src/v4/classic/tests/codec.test.ts +704 -0
  157. package/node_modules/zod/src/v4/classic/tests/coerce.test.ts +160 -0
  158. package/node_modules/zod/src/v4/classic/tests/continuability.test.ts +374 -0
  159. package/node_modules/zod/src/v4/classic/tests/credit-card.test.ts +76 -0
  160. package/node_modules/zod/src/v4/classic/tests/custom.test.ts +40 -0
  161. package/node_modules/zod/src/v4/classic/tests/cyclic-data.test.ts +985 -0
  162. package/node_modules/zod/src/v4/classic/tests/date.test.ts +92 -0
  163. package/node_modules/zod/src/v4/classic/tests/datetime.test.ts +316 -0
  164. package/node_modules/zod/src/v4/classic/tests/deep-partial.test.ts +380 -0
  165. package/node_modules/zod/src/v4/classic/tests/default-locale.test.ts +32 -0
  166. package/node_modules/zod/src/v4/classic/tests/default.test.ts +455 -0
  167. package/node_modules/zod/src/v4/classic/tests/describe-meta-checks.test.ts +27 -0
  168. package/node_modules/zod/src/v4/classic/tests/description.test.ts +32 -0
  169. package/node_modules/zod/src/v4/classic/tests/detached-methods.test.ts +221 -0
  170. package/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts +942 -0
  171. package/node_modules/zod/src/v4/classic/tests/enum.test.ts +305 -0
  172. package/node_modules/zod/src/v4/classic/tests/error-utils.test.ts +917 -0
  173. package/node_modules/zod/src/v4/classic/tests/error.test.ts +1108 -0
  174. package/node_modules/zod/src/v4/classic/tests/file.test.ts +96 -0
  175. package/node_modules/zod/src/v4/classic/tests/firstparty.test.ts +179 -0
  176. package/node_modules/zod/src/v4/classic/tests/fix-json-issue.test.ts +26 -0
  177. package/node_modules/zod/src/v4/classic/tests/from-json-schema.test.ts +1467 -0
  178. package/node_modules/zod/src/v4/classic/tests/function.test.ts +391 -0
  179. package/node_modules/zod/src/v4/classic/tests/generics.test.ts +72 -0
  180. package/node_modules/zod/src/v4/classic/tests/global-config.test.ts +32 -0
  181. package/node_modules/zod/src/v4/classic/tests/hash.test.ts +67 -0
  182. package/node_modules/zod/src/v4/classic/tests/iban.test.ts +81 -0
  183. package/node_modules/zod/src/v4/classic/tests/in-out.test.ts +159 -0
  184. package/node_modules/zod/src/v4/classic/tests/index.test.ts +958 -0
  185. package/node_modules/zod/src/v4/classic/tests/instance-footprint.test.ts +319 -0
  186. package/node_modules/zod/src/v4/classic/tests/instanceof.test.ts +127 -0
  187. package/node_modules/zod/src/v4/classic/tests/intersection.test.ts +334 -0
  188. package/node_modules/zod/src/v4/classic/tests/issue-schema.test.ts +215 -0
  189. package/node_modules/zod/src/v4/classic/tests/jitless-allows-eval.test.ts +39 -0
  190. package/node_modules/zod/src/v4/classic/tests/json.test.ts +109 -0
  191. package/node_modules/zod/src/v4/classic/tests/lazy.test.ts +262 -0
  192. package/node_modules/zod/src/v4/classic/tests/literal.test.ts +128 -0
  193. package/node_modules/zod/src/v4/classic/tests/locales_ka.test.ts +29 -0
  194. package/node_modules/zod/src/v4/classic/tests/locales_ro.test.ts +24 -0
  195. package/node_modules/zod/src/v4/classic/tests/map.test.ts +349 -0
  196. package/node_modules/zod/src/v4/classic/tests/nan.test.ts +21 -0
  197. package/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts +168 -0
  198. package/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts +101 -0
  199. package/node_modules/zod/src/v4/classic/tests/nullable.test.ts +22 -0
  200. package/node_modules/zod/src/v4/classic/tests/number.test.ts +401 -0
  201. package/node_modules/zod/src/v4/classic/tests/object.test.ts +1006 -0
  202. package/node_modules/zod/src/v4/classic/tests/optin-ladder.test.ts +235 -0
  203. package/node_modules/zod/src/v4/classic/tests/optional.test.ts +366 -0
  204. package/node_modules/zod/src/v4/classic/tests/partial.test.ts +497 -0
  205. package/node_modules/zod/src/v4/classic/tests/pickomit.test.ts +211 -0
  206. package/node_modules/zod/src/v4/classic/tests/pipe.test.ts +101 -0
  207. package/node_modules/zod/src/v4/classic/tests/prefault.test.ts +144 -0
  208. package/node_modules/zod/src/v4/classic/tests/preprocess-types.test.ts +44 -0
  209. package/node_modules/zod/src/v4/classic/tests/preprocess.test.ts +351 -0
  210. package/node_modules/zod/src/v4/classic/tests/primitive.test.ts +175 -0
  211. package/node_modules/zod/src/v4/classic/tests/promise.test.ts +81 -0
  212. package/node_modules/zod/src/v4/classic/tests/properties.test.ts +141 -0
  213. package/node_modules/zod/src/v4/classic/tests/prototypes.test.ts +23 -0
  214. package/node_modules/zod/src/v4/classic/tests/readonly.test.ts +184 -0
  215. package/node_modules/zod/src/v4/classic/tests/record.test.ts +885 -0
  216. package/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts +707 -0
  217. package/node_modules/zod/src/v4/classic/tests/redos.test.ts +68 -0
  218. package/node_modules/zod/src/v4/classic/tests/refine.test.ts +693 -0
  219. package/node_modules/zod/src/v4/classic/tests/registries.test.ts +243 -0
  220. package/node_modules/zod/src/v4/classic/tests/set.test.ts +196 -0
  221. package/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts +153 -0
  222. package/node_modules/zod/src/v4/classic/tests/string-formats.test.ts +125 -0
  223. package/node_modules/zod/src/v4/classic/tests/string.test.ts +1440 -0
  224. package/node_modules/zod/src/v4/classic/tests/stringbool.test.ts +124 -0
  225. package/node_modules/zod/src/v4/classic/tests/template-literal.test.ts +812 -0
  226. package/node_modules/zod/src/v4/classic/tests/to-json-schema-methods.test.ts +438 -0
  227. package/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts +4733 -0
  228. package/node_modules/zod/src/v4/classic/tests/transform.test.ts +378 -0
  229. package/node_modules/zod/src/v4/classic/tests/tuple.test.ts +511 -0
  230. package/node_modules/zod/src/v4/classic/tests/union.test.ts +310 -0
  231. package/node_modules/zod/src/v4/classic/tests/url.test.ts +13 -0
  232. package/node_modules/zod/src/v4/classic/tests/validate.test.ts +645 -0
  233. package/node_modules/zod/src/v4/classic/tests/validations.test.ts +283 -0
  234. package/node_modules/zod/src/v4/classic/tests/void.test.ts +12 -0
  235. package/node_modules/zod/src/v4/core/api.ts +1875 -0
  236. package/node_modules/zod/src/v4/core/checks.ts +1266 -0
  237. package/node_modules/zod/src/v4/core/compile.ts +2322 -0
  238. package/node_modules/zod/src/v4/core/core.ts +230 -0
  239. package/node_modules/zod/src/v4/core/doc.ts +52 -0
  240. package/node_modules/zod/src/v4/core/errors.ts +543 -0
  241. package/node_modules/zod/src/v4/core/index.ts +19 -0
  242. package/node_modules/zod/src/v4/core/json-schema-generator.ts +131 -0
  243. package/node_modules/zod/src/v4/core/json-schema-processors.ts +934 -0
  244. package/node_modules/zod/src/v4/core/json-schema.ts +148 -0
  245. package/node_modules/zod/src/v4/core/memoizer.ts +331 -0
  246. package/node_modules/zod/src/v4/core/parse.ts +309 -0
  247. package/node_modules/zod/src/v4/core/regexes.ts +217 -0
  248. package/node_modules/zod/src/v4/core/registries.ts +105 -0
  249. package/node_modules/zod/src/v4/core/schemas.ts +5226 -0
  250. package/node_modules/zod/src/v4/core/standard-schema.ts +159 -0
  251. package/node_modules/zod/src/v4/core/tests/cached.test.ts +54 -0
  252. package/node_modules/zod/src/v4/core/tests/compile-differential.test.ts +1004 -0
  253. package/node_modules/zod/src/v4/core/tests/compile-generative.test.ts +445 -0
  254. package/node_modules/zod/src/v4/core/tests/compile-global.test.ts +89 -0
  255. package/node_modules/zod/src/v4/core/tests/compile-off-by-default.test.ts +26 -0
  256. package/node_modules/zod/src/v4/core/tests/compile-stats.test.ts +34 -0
  257. package/node_modules/zod/src/v4/core/tests/compile.test.ts +2036 -0
  258. package/node_modules/zod/src/v4/core/tests/email-regex.test.ts +140 -0
  259. package/node_modules/zod/src/v4/core/tests/extend.test.ts +59 -0
  260. package/node_modules/zod/src/v4/core/tests/index.test.ts +46 -0
  261. package/node_modules/zod/src/v4/core/tests/locales/be.test.ts +124 -0
  262. package/node_modules/zod/src/v4/core/tests/locales/el.test.ts +214 -0
  263. package/node_modules/zod/src/v4/core/tests/locales/en.test.ts +22 -0
  264. package/node_modules/zod/src/v4/core/tests/locales/es.test.ts +180 -0
  265. package/node_modules/zod/src/v4/core/tests/locales/fr.test.ts +72 -0
  266. package/node_modules/zod/src/v4/core/tests/locales/he.test.ts +379 -0
  267. package/node_modules/zod/src/v4/core/tests/locales/hr.test.ts +163 -0
  268. package/node_modules/zod/src/v4/core/tests/locales/nl.test.ts +46 -0
  269. package/node_modules/zod/src/v4/core/tests/locales/parity.test.ts +42 -0
  270. package/node_modules/zod/src/v4/core/tests/locales/ru.test.ts +128 -0
  271. package/node_modules/zod/src/v4/core/tests/locales/tg.test.ts +85 -0
  272. package/node_modules/zod/src/v4/core/tests/locales/tk.test.ts +69 -0
  273. package/node_modules/zod/src/v4/core/tests/locales/tr.test.ts +69 -0
  274. package/node_modules/zod/src/v4/core/tests/locales/uz.test.ts +105 -0
  275. package/node_modules/zod/src/v4/core/tests/polyfill-collision.test.ts +46 -0
  276. package/node_modules/zod/src/v4/core/tests/record-constructor.test.ts +125 -0
  277. package/node_modules/zod/src/v4/core/tests/recursive-tuples.test.ts +45 -0
  278. package/node_modules/zod/src/v4/core/tests/treeshake.test.ts +51 -0
  279. package/node_modules/zod/src/v4/core/tests/url-no-canparse.test.ts +133 -0
  280. package/node_modules/zod/src/v4/core/to-json-schema.ts +857 -0
  281. package/node_modules/zod/src/v4/core/util.ts +1293 -0
  282. package/node_modules/zod/src/v4/core/versions.ts +5 -0
  283. package/node_modules/zod/src/v4/core/visit.ts +193 -0
  284. package/node_modules/zod/src/v4/core/zsf.ts +323 -0
  285. package/node_modules/zod/src/v4/index.ts +4 -0
  286. package/node_modules/zod/src/v4/locales/ar.ts +120 -0
  287. package/node_modules/zod/src/v4/locales/az.ts +116 -0
  288. package/node_modules/zod/src/v4/locales/be.ts +188 -0
  289. package/node_modules/zod/src/v4/locales/bg.ts +133 -0
  290. package/node_modules/zod/src/v4/locales/bn.ts +123 -0
  291. package/node_modules/zod/src/v4/locales/ca.ts +121 -0
  292. package/node_modules/zod/src/v4/locales/ckb.ts +140 -0
  293. package/node_modules/zod/src/v4/locales/cs.ts +123 -0
  294. package/node_modules/zod/src/v4/locales/da.ts +128 -0
  295. package/node_modules/zod/src/v4/locales/de.ts +121 -0
  296. package/node_modules/zod/src/v4/locales/el.ts +124 -0
  297. package/node_modules/zod/src/v4/locales/en.ts +136 -0
  298. package/node_modules/zod/src/v4/locales/eo.ts +123 -0
  299. package/node_modules/zod/src/v4/locales/es.ts +145 -0
  300. package/node_modules/zod/src/v4/locales/fa.ts +131 -0
  301. package/node_modules/zod/src/v4/locales/fi.ts +126 -0
  302. package/node_modules/zod/src/v4/locales/fr-CA.ts +121 -0
  303. package/node_modules/zod/src/v4/locales/fr.ts +139 -0
  304. package/node_modules/zod/src/v4/locales/gu.ts +123 -0
  305. package/node_modules/zod/src/v4/locales/he.ts +253 -0
  306. package/node_modules/zod/src/v4/locales/hi.ts +126 -0
  307. package/node_modules/zod/src/v4/locales/hr.ts +135 -0
  308. package/node_modules/zod/src/v4/locales/hu.ts +122 -0
  309. package/node_modules/zod/src/v4/locales/hy.ts +175 -0
  310. package/node_modules/zod/src/v4/locales/id.ts +120 -0
  311. package/node_modules/zod/src/v4/locales/index.ts +63 -0
  312. package/node_modules/zod/src/v4/locales/is.ts +124 -0
  313. package/node_modules/zod/src/v4/locales/it.ts +121 -0
  314. package/node_modules/zod/src/v4/locales/ja.ts +119 -0
  315. package/node_modules/zod/src/v4/locales/ka.ts +128 -0
  316. package/node_modules/zod/src/v4/locales/kh.ts +7 -0
  317. package/node_modules/zod/src/v4/locales/km.ts +124 -0
  318. package/node_modules/zod/src/v4/locales/kn.ts +126 -0
  319. package/node_modules/zod/src/v4/locales/ko.ts +126 -0
  320. package/node_modules/zod/src/v4/locales/lt.ts +243 -0
  321. package/node_modules/zod/src/v4/locales/mk.ts +123 -0
  322. package/node_modules/zod/src/v4/locales/ms.ts +120 -0
  323. package/node_modules/zod/src/v4/locales/ne.ts +128 -0
  324. package/node_modules/zod/src/v4/locales/nl.ts +126 -0
  325. package/node_modules/zod/src/v4/locales/nn.ts +121 -0
  326. package/node_modules/zod/src/v4/locales/no.ts +121 -0
  327. package/node_modules/zod/src/v4/locales/ota.ts +122 -0
  328. package/node_modules/zod/src/v4/locales/pl.ts +123 -0
  329. package/node_modules/zod/src/v4/locales/ps.ts +131 -0
  330. package/node_modules/zod/src/v4/locales/pt-BR.ts +161 -0
  331. package/node_modules/zod/src/v4/locales/pt.ts +159 -0
  332. package/node_modules/zod/src/v4/locales/ro.ts +132 -0
  333. package/node_modules/zod/src/v4/locales/ru.ts +188 -0
  334. package/node_modules/zod/src/v4/locales/sk.ts +123 -0
  335. package/node_modules/zod/src/v4/locales/sl.ts +123 -0
  336. package/node_modules/zod/src/v4/locales/sv.ts +124 -0
  337. package/node_modules/zod/src/v4/locales/ta.ts +123 -0
  338. package/node_modules/zod/src/v4/locales/tg.ts +135 -0
  339. package/node_modules/zod/src/v4/locales/th.ts +124 -0
  340. package/node_modules/zod/src/v4/locales/tk.ts +113 -0
  341. package/node_modules/zod/src/v4/locales/tr.ts +116 -0
  342. package/node_modules/zod/src/v4/locales/ua.ts +7 -0
  343. package/node_modules/zod/src/v4/locales/uk.ts +122 -0
  344. package/node_modules/zod/src/v4/locales/ur.ts +124 -0
  345. package/node_modules/zod/src/v4/locales/uz.ts +120 -0
  346. package/node_modules/zod/src/v4/locales/vi.ts +122 -0
  347. package/node_modules/zod/src/v4/locales/yo.ts +129 -0
  348. package/node_modules/zod/src/v4/locales/zh-CN.ts +121 -0
  349. package/node_modules/zod/src/v4/locales/zh-TW.ts +120 -0
  350. package/node_modules/zod/src/v4/mini/checks.ts +33 -0
  351. package/node_modules/zod/src/v4/mini/coerce.ts +27 -0
  352. package/node_modules/zod/src/v4/mini/deep-partial.ts +73 -0
  353. package/node_modules/zod/src/v4/mini/external.ts +52 -0
  354. package/node_modules/zod/src/v4/mini/in-out.ts +45 -0
  355. package/node_modules/zod/src/v4/mini/index.ts +3 -0
  356. package/node_modules/zod/src/v4/mini/iso.ts +66 -0
  357. package/node_modules/zod/src/v4/mini/parse.ts +16 -0
  358. package/node_modules/zod/src/v4/mini/schemas.ts +2051 -0
  359. package/node_modules/zod/src/v4/mini/tests/apply.test.ts +57 -0
  360. package/node_modules/zod/src/v4/mini/tests/assignability.test.ts +190 -0
  361. package/node_modules/zod/src/v4/mini/tests/brand.test.ts +94 -0
  362. package/node_modules/zod/src/v4/mini/tests/checks.test.ts +158 -0
  363. package/node_modules/zod/src/v4/mini/tests/codec.test.ts +582 -0
  364. package/node_modules/zod/src/v4/mini/tests/computed.test.ts +30 -0
  365. package/node_modules/zod/src/v4/mini/tests/cyclic-data.test.ts +84 -0
  366. package/node_modules/zod/src/v4/mini/tests/deep-partial.test.ts +54 -0
  367. package/node_modules/zod/src/v4/mini/tests/error.test.ts +41 -0
  368. package/node_modules/zod/src/v4/mini/tests/functions.test.ts +14 -0
  369. package/node_modules/zod/src/v4/mini/tests/index.test.ts +1146 -0
  370. package/node_modules/zod/src/v4/mini/tests/number.test.ts +109 -0
  371. package/node_modules/zod/src/v4/mini/tests/object.test.ts +292 -0
  372. package/node_modules/zod/src/v4/mini/tests/prototypes.test.ts +43 -0
  373. package/node_modules/zod/src/v4/mini/tests/recursive-types.test.ts +341 -0
  374. package/node_modules/zod/src/v4/mini/tests/standard-schema.test.ts +50 -0
  375. package/node_modules/zod/src/v4/mini/tests/string.test.ts +396 -0
  376. package/node_modules/zod/src/v4-mini/index.ts +3 -0
  377. package/node_modules/zod/v3/ZodError.cjs +167 -0
  378. package/node_modules/zod/v3/ZodError.d.cts +164 -0
  379. package/node_modules/zod/v3/ZodError.d.ts +164 -0
  380. package/node_modules/zod/v3/ZodError.js +143 -0
  381. package/node_modules/zod/v3/errors.cjs +36 -0
  382. package/node_modules/zod/v3/errors.d.cts +5 -0
  383. package/node_modules/zod/v3/errors.d.ts +5 -0
  384. package/node_modules/zod/v3/errors.js +9 -0
  385. package/node_modules/zod/v3/external.cjs +41 -0
  386. package/node_modules/zod/v3/external.d.cts +6 -0
  387. package/node_modules/zod/v3/external.d.ts +6 -0
  388. package/node_modules/zod/v3/external.js +6 -0
  389. package/node_modules/zod/v3/helpers/enumUtil.cjs +21 -0
  390. package/node_modules/zod/v3/helpers/enumUtil.d.cts +8 -0
  391. package/node_modules/zod/v3/helpers/enumUtil.d.ts +8 -0
  392. package/node_modules/zod/v3/helpers/enumUtil.js +1 -0
  393. package/node_modules/zod/v3/helpers/errorUtil.cjs +28 -0
  394. package/node_modules/zod/v3/helpers/errorUtil.d.cts +9 -0
  395. package/node_modules/zod/v3/helpers/errorUtil.d.ts +9 -0
  396. package/node_modules/zod/v3/helpers/errorUtil.js +6 -0
  397. package/node_modules/zod/v3/helpers/parseUtil.cjs +143 -0
  398. package/node_modules/zod/v3/helpers/parseUtil.d.cts +78 -0
  399. package/node_modules/zod/v3/helpers/parseUtil.d.ts +78 -0
  400. package/node_modules/zod/v3/helpers/parseUtil.js +109 -0
  401. package/node_modules/zod/v3/helpers/partialUtil.cjs +21 -0
  402. package/node_modules/zod/v3/helpers/partialUtil.d.cts +8 -0
  403. package/node_modules/zod/v3/helpers/partialUtil.d.ts +8 -0
  404. package/node_modules/zod/v3/helpers/partialUtil.js +1 -0
  405. package/node_modules/zod/v3/helpers/typeAliases.cjs +21 -0
  406. package/node_modules/zod/v3/helpers/typeAliases.d.cts +2 -0
  407. package/node_modules/zod/v3/helpers/typeAliases.d.ts +2 -0
  408. package/node_modules/zod/v3/helpers/typeAliases.js +1 -0
  409. package/node_modules/zod/v3/helpers/util.cjs +156 -0
  410. package/node_modules/zod/v3/helpers/util.d.cts +85 -0
  411. package/node_modules/zod/v3/helpers/util.d.ts +85 -0
  412. package/node_modules/zod/v3/helpers/util.js +133 -0
  413. package/node_modules/zod/v3/index.cjs +52 -0
  414. package/node_modules/zod/v3/index.d.cts +4 -0
  415. package/node_modules/zod/v3/index.d.ts +4 -0
  416. package/node_modules/zod/v3/index.js +4 -0
  417. package/node_modules/zod/v3/locales/en.cjs +112 -0
  418. package/node_modules/zod/v3/locales/en.d.cts +3 -0
  419. package/node_modules/zod/v3/locales/en.d.ts +3 -0
  420. package/node_modules/zod/v3/locales/en.js +109 -0
  421. package/node_modules/zod/v3/package.json +7 -0
  422. package/node_modules/zod/v3/standard-schema.cjs +21 -0
  423. package/node_modules/zod/v3/standard-schema.d.cts +102 -0
  424. package/node_modules/zod/v3/standard-schema.d.ts +102 -0
  425. package/node_modules/zod/v3/standard-schema.js +1 -0
  426. package/node_modules/zod/v3/types.cjs +3798 -0
  427. package/node_modules/zod/v3/types.d.cts +1034 -0
  428. package/node_modules/zod/v3/types.d.ts +1034 -0
  429. package/node_modules/zod/v3/types.js +3697 -0
  430. package/node_modules/zod/v4/classic/checks.cjs +53 -0
  431. package/node_modules/zod/v4/classic/checks.d.cts +1 -0
  432. package/node_modules/zod/v4/classic/checks.d.ts +1 -0
  433. package/node_modules/zod/v4/classic/checks.js +1 -0
  434. package/node_modules/zod/v4/classic/coerce.cjs +66 -0
  435. package/node_modules/zod/v4/classic/coerce.d.cts +17 -0
  436. package/node_modules/zod/v4/classic/coerce.d.ts +17 -0
  437. package/node_modules/zod/v4/classic/coerce.js +17 -0
  438. package/node_modules/zod/v4/classic/compat.cjs +80 -0
  439. package/node_modules/zod/v4/classic/compat.d.cts +48 -0
  440. package/node_modules/zod/v4/classic/compat.d.ts +48 -0
  441. package/node_modules/zod/v4/classic/compat.js +31 -0
  442. package/node_modules/zod/v4/classic/deep-partial.cjs +58 -0
  443. package/node_modules/zod/v4/classic/deep-partial.d.cts +14 -0
  444. package/node_modules/zod/v4/classic/deep-partial.d.ts +14 -0
  445. package/node_modules/zod/v4/classic/deep-partial.js +13 -0
  446. package/node_modules/zod/v4/classic/errors.cjs +102 -0
  447. package/node_modules/zod/v4/classic/errors.d.cts +29 -0
  448. package/node_modules/zod/v4/classic/errors.d.ts +29 -0
  449. package/node_modules/zod/v4/classic/errors.js +57 -0
  450. package/node_modules/zod/v4/classic/external.cjs +97 -0
  451. package/node_modules/zod/v4/classic/external.d.cts +19 -0
  452. package/node_modules/zod/v4/classic/external.d.ts +19 -0
  453. package/node_modules/zod/v4/classic/external.js +17 -0
  454. package/node_modules/zod/v4/classic/from-json-schema.cjs +926 -0
  455. package/node_modules/zod/v4/classic/from-json-schema.d.cts +12 -0
  456. package/node_modules/zod/v4/classic/from-json-schema.d.ts +12 -0
  457. package/node_modules/zod/v4/classic/from-json-schema.js +881 -0
  458. package/node_modules/zod/v4/classic/in-out.cjs +82 -0
  459. package/node_modules/zod/v4/classic/in-out.d.cts +8 -0
  460. package/node_modules/zod/v4/classic/in-out.d.ts +8 -0
  461. package/node_modules/zod/v4/classic/in-out.js +36 -0
  462. package/node_modules/zod/v4/classic/index.cjs +52 -0
  463. package/node_modules/zod/v4/classic/index.d.cts +3 -0
  464. package/node_modules/zod/v4/classic/index.d.ts +3 -0
  465. package/node_modules/zod/v4/classic/index.js +4 -0
  466. package/node_modules/zod/v4/classic/iso.cjs +68 -0
  467. package/node_modules/zod/v4/classic/iso.d.cts +7 -0
  468. package/node_modules/zod/v4/classic/iso.d.ts +7 -0
  469. package/node_modules/zod/v4/classic/iso.js +15 -0
  470. package/node_modules/zod/v4/classic/package.json +7 -0
  471. package/node_modules/zod/v4/classic/parse.cjs +63 -0
  472. package/node_modules/zod/v4/classic/parse.d.cts +44 -0
  473. package/node_modules/zod/v4/classic/parse.d.ts +44 -0
  474. package/node_modules/zod/v4/classic/parse.js +16 -0
  475. package/node_modules/zod/v4/classic/schemas.cjs +1676 -0
  476. package/node_modules/zod/v4/classic/schemas.d.cts +816 -0
  477. package/node_modules/zod/v4/classic/schemas.d.ts +816 -0
  478. package/node_modules/zod/v4/classic/schemas.js +1535 -0
  479. package/node_modules/zod/v4/core/api.cjs +1269 -0
  480. package/node_modules/zod/v4/core/api.d.cts +335 -0
  481. package/node_modules/zod/v4/core/api.d.ts +335 -0
  482. package/node_modules/zod/v4/core/api.js +1107 -0
  483. package/node_modules/zod/v4/core/checks.cjs +561 -0
  484. package/node_modules/zod/v4/core/checks.d.cts +294 -0
  485. package/node_modules/zod/v4/core/checks.d.ts +294 -0
  486. package/node_modules/zod/v4/core/checks.js +516 -0
  487. package/node_modules/zod/v4/core/compile.cjs +1916 -0
  488. package/node_modules/zod/v4/core/compile.d.cts +65 -0
  489. package/node_modules/zod/v4/core/compile.d.ts +65 -0
  490. package/node_modules/zod/v4/core/compile.js +1866 -0
  491. package/node_modules/zod/v4/core/core.cjs +167 -0
  492. package/node_modules/zod/v4/core/core.d.cts +82 -0
  493. package/node_modules/zod/v4/core/core.d.ts +82 -0
  494. package/node_modules/zod/v4/core/core.js +141 -0
  495. package/node_modules/zod/v4/core/doc.cjs +61 -0
  496. package/node_modules/zod/v4/core/doc.d.cts +16 -0
  497. package/node_modules/zod/v4/core/doc.d.ts +16 -0
  498. package/node_modules/zod/v4/core/doc.js +38 -0
  499. package/node_modules/zod/v4/core/errors.cjs +317 -0
  500. package/node_modules/zod/v4/core/errors.d.cts +225 -0
  501. package/node_modules/zod/v4/core/errors.d.ts +225 -0
  502. package/node_modules/zod/v4/core/errors.js +267 -0
  503. package/node_modules/zod/v4/core/index.cjs +70 -0
  504. package/node_modules/zod/v4/core/index.d.cts +19 -0
  505. package/node_modules/zod/v4/core/index.d.ts +19 -0
  506. package/node_modules/zod/v4/core/index.js +19 -0
  507. package/node_modules/zod/v4/core/json-schema-generator.cjs +122 -0
  508. package/node_modules/zod/v4/core/json-schema-generator.d.cts +65 -0
  509. package/node_modules/zod/v4/core/json-schema-generator.d.ts +65 -0
  510. package/node_modules/zod/v4/core/json-schema-generator.js +99 -0
  511. package/node_modules/zod/v4/core/json-schema-processors.cjs +929 -0
  512. package/node_modules/zod/v4/core/json-schema-processors.d.cts +65 -0
  513. package/node_modules/zod/v4/core/json-schema-processors.d.ts +65 -0
  514. package/node_modules/zod/v4/core/json-schema-processors.js +843 -0
  515. package/node_modules/zod/v4/core/json-schema.cjs +21 -0
  516. package/node_modules/zod/v4/core/json-schema.d.cts +89 -0
  517. package/node_modules/zod/v4/core/json-schema.d.ts +89 -0
  518. package/node_modules/zod/v4/core/json-schema.js +1 -0
  519. package/node_modules/zod/v4/core/memoizer.cjs +360 -0
  520. package/node_modules/zod/v4/core/memoizer.d.cts +15 -0
  521. package/node_modules/zod/v4/core/memoizer.d.ts +15 -0
  522. package/node_modules/zod/v4/core/memoizer.js +311 -0
  523. package/node_modules/zod/v4/core/package.json +7 -0
  524. package/node_modules/zod/v4/core/parse.cjs +233 -0
  525. package/node_modules/zod/v4/core/parse.d.cts +52 -0
  526. package/node_modules/zod/v4/core/parse.d.ts +52 -0
  527. package/node_modules/zod/v4/core/parse.js +175 -0
  528. package/node_modules/zod/v4/core/regexes.cjs +209 -0
  529. package/node_modules/zod/v4/core/regexes.d.cts +90 -0
  530. package/node_modules/zod/v4/core/regexes.d.ts +90 -0
  531. package/node_modules/zod/v4/core/regexes.js +156 -0
  532. package/node_modules/zod/v4/core/registries.cjs +75 -0
  533. package/node_modules/zod/v4/core/registries.d.cts +35 -0
  534. package/node_modules/zod/v4/core/registries.d.ts +35 -0
  535. package/node_modules/zod/v4/core/registries.js +51 -0
  536. package/node_modules/zod/v4/core/schemas.cjs +2699 -0
  537. package/node_modules/zod/v4/core/schemas.d.cts +1275 -0
  538. package/node_modules/zod/v4/core/schemas.d.ts +1275 -0
  539. package/node_modules/zod/v4/core/schemas.js +2636 -0
  540. package/node_modules/zod/v4/core/standard-schema.cjs +21 -0
  541. package/node_modules/zod/v4/core/standard-schema.d.cts +126 -0
  542. package/node_modules/zod/v4/core/standard-schema.d.ts +126 -0
  543. package/node_modules/zod/v4/core/standard-schema.js +1 -0
  544. package/node_modules/zod/v4/core/to-json-schema.cjs +681 -0
  545. package/node_modules/zod/v4/core/to-json-schema.d.cts +154 -0
  546. package/node_modules/zod/v4/core/to-json-schema.d.ts +154 -0
  547. package/node_modules/zod/v4/core/to-json-schema.js +651 -0
  548. package/node_modules/zod/v4/core/util.cjs +964 -0
  549. package/node_modules/zod/v4/core/util.d.cts +280 -0
  550. package/node_modules/zod/v4/core/util.d.ts +280 -0
  551. package/node_modules/zod/v4/core/util.js +873 -0
  552. package/node_modules/zod/v4/core/versions.cjs +27 -0
  553. package/node_modules/zod/v4/core/versions.d.cts +5 -0
  554. package/node_modules/zod/v4/core/versions.d.ts +5 -0
  555. package/node_modules/zod/v4/core/versions.js +5 -0
  556. package/node_modules/zod/v4/core/visit.cjs +214 -0
  557. package/node_modules/zod/v4/core/visit.d.cts +30 -0
  558. package/node_modules/zod/v4/core/visit.d.ts +30 -0
  559. package/node_modules/zod/v4/core/visit.js +169 -0
  560. package/node_modules/zod/v4/index.cjs +51 -0
  561. package/node_modules/zod/v4/index.d.cts +3 -0
  562. package/node_modules/zod/v4/index.d.ts +3 -0
  563. package/node_modules/zod/v4/index.js +4 -0
  564. package/node_modules/zod/v4/locales/ar.cjs +138 -0
  565. package/node_modules/zod/v4/locales/ar.d.cts +5 -0
  566. package/node_modules/zod/v4/locales/ar.d.ts +4 -0
  567. package/node_modules/zod/v4/locales/ar.js +111 -0
  568. package/node_modules/zod/v4/locales/az.cjs +137 -0
  569. package/node_modules/zod/v4/locales/az.d.cts +5 -0
  570. package/node_modules/zod/v4/locales/az.d.ts +4 -0
  571. package/node_modules/zod/v4/locales/az.js +110 -0
  572. package/node_modules/zod/v4/locales/be.cjs +195 -0
  573. package/node_modules/zod/v4/locales/be.d.cts +5 -0
  574. package/node_modules/zod/v4/locales/be.d.ts +4 -0
  575. package/node_modules/zod/v4/locales/be.js +168 -0
  576. package/node_modules/zod/v4/locales/bg.cjs +152 -0
  577. package/node_modules/zod/v4/locales/bg.d.cts +5 -0
  578. package/node_modules/zod/v4/locales/bg.d.ts +4 -0
  579. package/node_modules/zod/v4/locales/bg.js +125 -0
  580. package/node_modules/zod/v4/locales/bn.cjs +140 -0
  581. package/node_modules/zod/v4/locales/bn.d.cts +5 -0
  582. package/node_modules/zod/v4/locales/bn.d.ts +4 -0
  583. package/node_modules/zod/v4/locales/bn.js +113 -0
  584. package/node_modules/zod/v4/locales/ca.cjs +139 -0
  585. package/node_modules/zod/v4/locales/ca.d.cts +5 -0
  586. package/node_modules/zod/v4/locales/ca.d.ts +4 -0
  587. package/node_modules/zod/v4/locales/ca.js +112 -0
  588. package/node_modules/zod/v4/locales/ckb.cjs +160 -0
  589. package/node_modules/zod/v4/locales/ckb.d.cts +5 -0
  590. package/node_modules/zod/v4/locales/ckb.d.ts +4 -0
  591. package/node_modules/zod/v4/locales/ckb.js +133 -0
  592. package/node_modules/zod/v4/locales/cs.cjs +143 -0
  593. package/node_modules/zod/v4/locales/cs.d.cts +5 -0
  594. package/node_modules/zod/v4/locales/cs.d.ts +4 -0
  595. package/node_modules/zod/v4/locales/cs.js +116 -0
  596. package/node_modules/zod/v4/locales/da.cjs +147 -0
  597. package/node_modules/zod/v4/locales/da.d.cts +5 -0
  598. package/node_modules/zod/v4/locales/da.d.ts +4 -0
  599. package/node_modules/zod/v4/locales/da.js +120 -0
  600. package/node_modules/zod/v4/locales/de.cjs +140 -0
  601. package/node_modules/zod/v4/locales/de.d.cts +5 -0
  602. package/node_modules/zod/v4/locales/de.d.ts +4 -0
  603. package/node_modules/zod/v4/locales/de.js +113 -0
  604. package/node_modules/zod/v4/locales/el.cjs +139 -0
  605. package/node_modules/zod/v4/locales/el.d.cts +5 -0
  606. package/node_modules/zod/v4/locales/el.d.ts +4 -0
  607. package/node_modules/zod/v4/locales/el.js +112 -0
  608. package/node_modules/zod/v4/locales/en.cjs +152 -0
  609. package/node_modules/zod/v4/locales/en.d.cts +5 -0
  610. package/node_modules/zod/v4/locales/en.d.ts +4 -0
  611. package/node_modules/zod/v4/locales/en.js +125 -0
  612. package/node_modules/zod/v4/locales/eo.cjs +141 -0
  613. package/node_modules/zod/v4/locales/eo.d.cts +5 -0
  614. package/node_modules/zod/v4/locales/eo.d.ts +4 -0
  615. package/node_modules/zod/v4/locales/eo.js +114 -0
  616. package/node_modules/zod/v4/locales/es.cjs +163 -0
  617. package/node_modules/zod/v4/locales/es.d.cts +5 -0
  618. package/node_modules/zod/v4/locales/es.d.ts +4 -0
  619. package/node_modules/zod/v4/locales/es.js +136 -0
  620. package/node_modules/zod/v4/locales/fa.cjs +146 -0
  621. package/node_modules/zod/v4/locales/fa.d.cts +5 -0
  622. package/node_modules/zod/v4/locales/fa.d.ts +4 -0
  623. package/node_modules/zod/v4/locales/fa.js +119 -0
  624. package/node_modules/zod/v4/locales/fi.cjs +144 -0
  625. package/node_modules/zod/v4/locales/fi.d.cts +5 -0
  626. package/node_modules/zod/v4/locales/fi.d.ts +4 -0
  627. package/node_modules/zod/v4/locales/fi.js +117 -0
  628. package/node_modules/zod/v4/locales/fr-CA.cjs +139 -0
  629. package/node_modules/zod/v4/locales/fr-CA.d.cts +5 -0
  630. package/node_modules/zod/v4/locales/fr-CA.d.ts +4 -0
  631. package/node_modules/zod/v4/locales/fr-CA.js +112 -0
  632. package/node_modules/zod/v4/locales/fr.cjs +156 -0
  633. package/node_modules/zod/v4/locales/fr.d.cts +5 -0
  634. package/node_modules/zod/v4/locales/fr.d.ts +4 -0
  635. package/node_modules/zod/v4/locales/fr.js +129 -0
  636. package/node_modules/zod/v4/locales/gu.cjs +140 -0
  637. package/node_modules/zod/v4/locales/gu.d.cts +5 -0
  638. package/node_modules/zod/v4/locales/gu.d.ts +4 -0
  639. package/node_modules/zod/v4/locales/gu.js +113 -0
  640. package/node_modules/zod/v4/locales/he.cjs +248 -0
  641. package/node_modules/zod/v4/locales/he.d.cts +5 -0
  642. package/node_modules/zod/v4/locales/he.d.ts +4 -0
  643. package/node_modules/zod/v4/locales/he.js +221 -0
  644. package/node_modules/zod/v4/locales/hi.cjs +138 -0
  645. package/node_modules/zod/v4/locales/hi.d.cts +5 -0
  646. package/node_modules/zod/v4/locales/hi.d.ts +4 -0
  647. package/node_modules/zod/v4/locales/hi.js +111 -0
  648. package/node_modules/zod/v4/locales/hr.cjs +153 -0
  649. package/node_modules/zod/v4/locales/hr.d.cts +5 -0
  650. package/node_modules/zod/v4/locales/hr.d.ts +4 -0
  651. package/node_modules/zod/v4/locales/hr.js +126 -0
  652. package/node_modules/zod/v4/locales/hu.cjs +140 -0
  653. package/node_modules/zod/v4/locales/hu.d.cts +5 -0
  654. package/node_modules/zod/v4/locales/hu.d.ts +4 -0
  655. package/node_modules/zod/v4/locales/hu.js +113 -0
  656. package/node_modules/zod/v4/locales/hy.cjs +185 -0
  657. package/node_modules/zod/v4/locales/hy.d.cts +5 -0
  658. package/node_modules/zod/v4/locales/hy.d.ts +4 -0
  659. package/node_modules/zod/v4/locales/hy.js +158 -0
  660. package/node_modules/zod/v4/locales/id.cjs +138 -0
  661. package/node_modules/zod/v4/locales/id.d.cts +5 -0
  662. package/node_modules/zod/v4/locales/id.d.ts +4 -0
  663. package/node_modules/zod/v4/locales/id.js +111 -0
  664. package/node_modules/zod/v4/locales/index.cjs +152 -0
  665. package/node_modules/zod/v4/locales/index.d.cts +63 -0
  666. package/node_modules/zod/v4/locales/index.d.ts +63 -0
  667. package/node_modules/zod/v4/locales/index.js +63 -0
  668. package/node_modules/zod/v4/locales/is.cjs +141 -0
  669. package/node_modules/zod/v4/locales/is.d.cts +5 -0
  670. package/node_modules/zod/v4/locales/is.d.ts +4 -0
  671. package/node_modules/zod/v4/locales/is.js +114 -0
  672. package/node_modules/zod/v4/locales/it.cjs +140 -0
  673. package/node_modules/zod/v4/locales/it.d.cts +5 -0
  674. package/node_modules/zod/v4/locales/it.d.ts +4 -0
  675. package/node_modules/zod/v4/locales/it.js +113 -0
  676. package/node_modules/zod/v4/locales/ja.cjs +139 -0
  677. package/node_modules/zod/v4/locales/ja.d.cts +5 -0
  678. package/node_modules/zod/v4/locales/ja.d.ts +4 -0
  679. package/node_modules/zod/v4/locales/ja.js +112 -0
  680. package/node_modules/zod/v4/locales/ka.cjs +144 -0
  681. package/node_modules/zod/v4/locales/ka.d.cts +5 -0
  682. package/node_modules/zod/v4/locales/ka.d.ts +4 -0
  683. package/node_modules/zod/v4/locales/ka.js +117 -0
  684. package/node_modules/zod/v4/locales/kh.cjs +12 -0
  685. package/node_modules/zod/v4/locales/kh.d.cts +5 -0
  686. package/node_modules/zod/v4/locales/kh.d.ts +5 -0
  687. package/node_modules/zod/v4/locales/kh.js +5 -0
  688. package/node_modules/zod/v4/locales/km.cjs +142 -0
  689. package/node_modules/zod/v4/locales/km.d.cts +5 -0
  690. package/node_modules/zod/v4/locales/km.d.ts +4 -0
  691. package/node_modules/zod/v4/locales/km.js +115 -0
  692. package/node_modules/zod/v4/locales/kn.cjs +143 -0
  693. package/node_modules/zod/v4/locales/kn.d.cts +5 -0
  694. package/node_modules/zod/v4/locales/kn.d.ts +4 -0
  695. package/node_modules/zod/v4/locales/kn.js +116 -0
  696. package/node_modules/zod/v4/locales/ko.cjs +143 -0
  697. package/node_modules/zod/v4/locales/ko.d.cts +5 -0
  698. package/node_modules/zod/v4/locales/ko.d.ts +4 -0
  699. package/node_modules/zod/v4/locales/ko.js +116 -0
  700. package/node_modules/zod/v4/locales/lt.cjs +234 -0
  701. package/node_modules/zod/v4/locales/lt.d.cts +5 -0
  702. package/node_modules/zod/v4/locales/lt.d.ts +4 -0
  703. package/node_modules/zod/v4/locales/lt.js +207 -0
  704. package/node_modules/zod/v4/locales/mk.cjs +141 -0
  705. package/node_modules/zod/v4/locales/mk.d.cts +5 -0
  706. package/node_modules/zod/v4/locales/mk.d.ts +4 -0
  707. package/node_modules/zod/v4/locales/mk.js +114 -0
  708. package/node_modules/zod/v4/locales/ms.cjs +139 -0
  709. package/node_modules/zod/v4/locales/ms.d.cts +5 -0
  710. package/node_modules/zod/v4/locales/ms.d.ts +4 -0
  711. package/node_modules/zod/v4/locales/ms.js +112 -0
  712. package/node_modules/zod/v4/locales/ne.cjs +138 -0
  713. package/node_modules/zod/v4/locales/ne.d.cts +5 -0
  714. package/node_modules/zod/v4/locales/ne.d.ts +4 -0
  715. package/node_modules/zod/v4/locales/ne.js +111 -0
  716. package/node_modules/zod/v4/locales/nl.cjs +142 -0
  717. package/node_modules/zod/v4/locales/nl.d.cts +5 -0
  718. package/node_modules/zod/v4/locales/nl.d.ts +4 -0
  719. package/node_modules/zod/v4/locales/nl.js +115 -0
  720. package/node_modules/zod/v4/locales/nn.cjs +140 -0
  721. package/node_modules/zod/v4/locales/nn.d.cts +5 -0
  722. package/node_modules/zod/v4/locales/nn.d.ts +4 -0
  723. package/node_modules/zod/v4/locales/nn.js +113 -0
  724. package/node_modules/zod/v4/locales/no.cjs +140 -0
  725. package/node_modules/zod/v4/locales/no.d.cts +5 -0
  726. package/node_modules/zod/v4/locales/no.d.ts +4 -0
  727. package/node_modules/zod/v4/locales/no.js +113 -0
  728. package/node_modules/zod/v4/locales/ota.cjs +141 -0
  729. package/node_modules/zod/v4/locales/ota.d.cts +5 -0
  730. package/node_modules/zod/v4/locales/ota.d.ts +4 -0
  731. package/node_modules/zod/v4/locales/ota.js +114 -0
  732. package/node_modules/zod/v4/locales/package.json +7 -0
  733. package/node_modules/zod/v4/locales/pl.cjs +141 -0
  734. package/node_modules/zod/v4/locales/pl.d.cts +5 -0
  735. package/node_modules/zod/v4/locales/pl.d.ts +4 -0
  736. package/node_modules/zod/v4/locales/pl.js +114 -0
  737. package/node_modules/zod/v4/locales/ps.cjs +146 -0
  738. package/node_modules/zod/v4/locales/ps.d.cts +5 -0
  739. package/node_modules/zod/v4/locales/ps.d.ts +4 -0
  740. package/node_modules/zod/v4/locales/ps.js +119 -0
  741. package/node_modules/zod/v4/locales/pt-BR.cjs +170 -0
  742. package/node_modules/zod/v4/locales/pt-BR.d.cts +5 -0
  743. package/node_modules/zod/v4/locales/pt-BR.d.ts +4 -0
  744. package/node_modules/zod/v4/locales/pt-BR.js +143 -0
  745. package/node_modules/zod/v4/locales/pt.cjs +169 -0
  746. package/node_modules/zod/v4/locales/pt.d.cts +5 -0
  747. package/node_modules/zod/v4/locales/pt.d.ts +4 -0
  748. package/node_modules/zod/v4/locales/pt.js +142 -0
  749. package/node_modules/zod/v4/locales/ro.cjs +149 -0
  750. package/node_modules/zod/v4/locales/ro.d.cts +5 -0
  751. package/node_modules/zod/v4/locales/ro.d.ts +4 -0
  752. package/node_modules/zod/v4/locales/ro.js +122 -0
  753. package/node_modules/zod/v4/locales/ru.cjs +195 -0
  754. package/node_modules/zod/v4/locales/ru.d.cts +5 -0
  755. package/node_modules/zod/v4/locales/ru.d.ts +4 -0
  756. package/node_modules/zod/v4/locales/ru.js +168 -0
  757. package/node_modules/zod/v4/locales/sk.cjs +143 -0
  758. package/node_modules/zod/v4/locales/sk.d.cts +5 -0
  759. package/node_modules/zod/v4/locales/sk.d.ts +4 -0
  760. package/node_modules/zod/v4/locales/sk.js +116 -0
  761. package/node_modules/zod/v4/locales/sl.cjs +141 -0
  762. package/node_modules/zod/v4/locales/sl.d.cts +5 -0
  763. package/node_modules/zod/v4/locales/sl.d.ts +4 -0
  764. package/node_modules/zod/v4/locales/sl.js +114 -0
  765. package/node_modules/zod/v4/locales/sv.cjs +142 -0
  766. package/node_modules/zod/v4/locales/sv.d.cts +5 -0
  767. package/node_modules/zod/v4/locales/sv.d.ts +4 -0
  768. package/node_modules/zod/v4/locales/sv.js +115 -0
  769. package/node_modules/zod/v4/locales/ta.cjs +142 -0
  770. package/node_modules/zod/v4/locales/ta.d.cts +5 -0
  771. package/node_modules/zod/v4/locales/ta.d.ts +4 -0
  772. package/node_modules/zod/v4/locales/ta.js +115 -0
  773. package/node_modules/zod/v4/locales/tg.cjs +144 -0
  774. package/node_modules/zod/v4/locales/tg.d.cts +5 -0
  775. package/node_modules/zod/v4/locales/tg.d.ts +4 -0
  776. package/node_modules/zod/v4/locales/tg.js +117 -0
  777. package/node_modules/zod/v4/locales/th.cjs +142 -0
  778. package/node_modules/zod/v4/locales/th.d.cts +5 -0
  779. package/node_modules/zod/v4/locales/th.d.ts +4 -0
  780. package/node_modules/zod/v4/locales/th.js +115 -0
  781. package/node_modules/zod/v4/locales/tk.cjs +134 -0
  782. package/node_modules/zod/v4/locales/tk.d.cts +5 -0
  783. package/node_modules/zod/v4/locales/tk.d.ts +4 -0
  784. package/node_modules/zod/v4/locales/tk.js +107 -0
  785. package/node_modules/zod/v4/locales/tr.cjs +137 -0
  786. package/node_modules/zod/v4/locales/tr.d.cts +5 -0
  787. package/node_modules/zod/v4/locales/tr.d.ts +4 -0
  788. package/node_modules/zod/v4/locales/tr.js +110 -0
  789. package/node_modules/zod/v4/locales/ua.cjs +12 -0
  790. package/node_modules/zod/v4/locales/ua.d.cts +5 -0
  791. package/node_modules/zod/v4/locales/ua.d.ts +5 -0
  792. package/node_modules/zod/v4/locales/ua.js +5 -0
  793. package/node_modules/zod/v4/locales/uk.cjs +140 -0
  794. package/node_modules/zod/v4/locales/uk.d.cts +5 -0
  795. package/node_modules/zod/v4/locales/uk.d.ts +4 -0
  796. package/node_modules/zod/v4/locales/uk.js +113 -0
  797. package/node_modules/zod/v4/locales/ur.cjs +142 -0
  798. package/node_modules/zod/v4/locales/ur.d.cts +5 -0
  799. package/node_modules/zod/v4/locales/ur.d.ts +4 -0
  800. package/node_modules/zod/v4/locales/ur.js +115 -0
  801. package/node_modules/zod/v4/locales/uz.cjs +140 -0
  802. package/node_modules/zod/v4/locales/uz.d.cts +5 -0
  803. package/node_modules/zod/v4/locales/uz.d.ts +4 -0
  804. package/node_modules/zod/v4/locales/uz.js +113 -0
  805. package/node_modules/zod/v4/locales/vi.cjs +140 -0
  806. package/node_modules/zod/v4/locales/vi.d.cts +5 -0
  807. package/node_modules/zod/v4/locales/vi.d.ts +4 -0
  808. package/node_modules/zod/v4/locales/vi.js +113 -0
  809. package/node_modules/zod/v4/locales/yo.cjs +139 -0
  810. package/node_modules/zod/v4/locales/yo.d.cts +5 -0
  811. package/node_modules/zod/v4/locales/yo.d.ts +4 -0
  812. package/node_modules/zod/v4/locales/yo.js +112 -0
  813. package/node_modules/zod/v4/locales/zh-CN.cjs +141 -0
  814. package/node_modules/zod/v4/locales/zh-CN.d.cts +5 -0
  815. package/node_modules/zod/v4/locales/zh-CN.d.ts +4 -0
  816. package/node_modules/zod/v4/locales/zh-CN.js +114 -0
  817. package/node_modules/zod/v4/locales/zh-TW.cjs +139 -0
  818. package/node_modules/zod/v4/locales/zh-TW.d.cts +5 -0
  819. package/node_modules/zod/v4/locales/zh-TW.d.ts +4 -0
  820. package/node_modules/zod/v4/locales/zh-TW.js +112 -0
  821. package/node_modules/zod/v4/mini/checks.cjs +54 -0
  822. package/node_modules/zod/v4/mini/checks.d.cts +1 -0
  823. package/node_modules/zod/v4/mini/checks.d.ts +1 -0
  824. package/node_modules/zod/v4/mini/checks.js +1 -0
  825. package/node_modules/zod/v4/mini/coerce.cjs +71 -0
  826. package/node_modules/zod/v4/mini/coerce.d.cts +7 -0
  827. package/node_modules/zod/v4/mini/coerce.d.ts +7 -0
  828. package/node_modules/zod/v4/mini/coerce.js +22 -0
  829. package/node_modules/zod/v4/mini/deep-partial.cjs +58 -0
  830. package/node_modules/zod/v4/mini/deep-partial.d.cts +14 -0
  831. package/node_modules/zod/v4/mini/deep-partial.d.ts +14 -0
  832. package/node_modules/zod/v4/mini/deep-partial.js +13 -0
  833. package/node_modules/zod/v4/mini/external.cjs +95 -0
  834. package/node_modules/zod/v4/mini/external.d.cts +16 -0
  835. package/node_modules/zod/v4/mini/external.d.ts +16 -0
  836. package/node_modules/zod/v4/mini/external.js +16 -0
  837. package/node_modules/zod/v4/mini/in-out.cjs +82 -0
  838. package/node_modules/zod/v4/mini/in-out.d.cts +8 -0
  839. package/node_modules/zod/v4/mini/in-out.d.ts +8 -0
  840. package/node_modules/zod/v4/mini/in-out.js +36 -0
  841. package/node_modules/zod/v4/mini/index.cjs +51 -0
  842. package/node_modules/zod/v4/mini/index.d.cts +3 -0
  843. package/node_modules/zod/v4/mini/index.d.ts +3 -0
  844. package/node_modules/zod/v4/mini/index.js +3 -0
  845. package/node_modules/zod/v4/mini/iso.cjs +83 -0
  846. package/node_modules/zod/v4/mini/iso.d.cts +22 -0
  847. package/node_modules/zod/v4/mini/iso.d.ts +22 -0
  848. package/node_modules/zod/v4/mini/iso.js +34 -0
  849. package/node_modules/zod/v4/mini/package.json +7 -0
  850. package/node_modules/zod/v4/mini/parse.cjs +37 -0
  851. package/node_modules/zod/v4/mini/parse.d.cts +1 -0
  852. package/node_modules/zod/v4/mini/parse.d.ts +1 -0
  853. package/node_modules/zod/v4/mini/parse.js +1 -0
  854. package/node_modules/zod/v4/mini/schemas.cjs +1147 -0
  855. package/node_modules/zod/v4/mini/schemas.d.cts +480 -0
  856. package/node_modules/zod/v4/mini/schemas.d.ts +480 -0
  857. package/node_modules/zod/v4/mini/schemas.js +1002 -0
  858. package/node_modules/zod/v4/package.json +7 -0
  859. package/node_modules/zod/v4-mini/index.cjs +51 -0
  860. package/node_modules/zod/v4-mini/index.d.cts +3 -0
  861. package/node_modules/zod/v4-mini/index.d.ts +3 -0
  862. package/node_modules/zod/v4-mini/index.js +3 -0
  863. package/node_modules/zod/v4-mini/package.json +7 -0
  864. package/package.json +94 -94
@@ -0,0 +1,3967 @@
1
+ import {
2
+ AccountError,
3
+ __name,
4
+ codeForStatus,
5
+ normalizeDpopHtu
6
+ } from "./chunk-FELZILY4.mjs";
7
+
8
+ // src/types.ts
9
+ import { z } from "zod";
10
+ var MICRO_PER_CREDIT = 1e6;
11
+ var surfaceSchema = z.string().min(2).max(64).regex(/^xeno[_a-z0-9]+$/, "surface must look like xeno_post");
12
+ var accountSchema = z.object({
13
+ id: z.string().min(1),
14
+ email: z.string().email(),
15
+ username: z.string().nullable().default(null),
16
+ displayName: z.string().nullable().default(null),
17
+ avatarUrl: z.string().url().nullable().default(null),
18
+ emailVerified: z.boolean().default(false),
19
+ /** Linked app surfaces for this account (unified-account view). */
20
+ linkedSurfaces: z.array(surfaceSchema).default([])
21
+ });
22
+ var tokenSetSchema = z.object({
23
+ accessToken: z.string().min(1),
24
+ /** Opaque or JWT; the SDK treats it as opaque. */
25
+ tokenType: z.string().default("Bearer"),
26
+ expiresAt: z.coerce.date().nullable().default(null),
27
+ refreshToken: z.string().nullable().default(null),
28
+ /** OIDC ID token (authentication only — never sent to resource APIs). */
29
+ idToken: z.string().nullable().default(null),
30
+ scope: z.array(z.string()).default([]),
31
+ /** Session id claim, the join key for back-channel logout. */
32
+ sid: z.string().nullable().default(null),
33
+ /** Signature-verified claims; never populated by unverified decoding. */
34
+ accessClaims: z.record(z.string(), z.unknown()).nullable().default(null),
35
+ idClaims: z.record(z.string(), z.unknown()).nullable().default(null)
36
+ });
37
+ var oauthTokenResponseSchema = z.object({
38
+ access_token: z.string(),
39
+ token_type: z.string().default("Bearer"),
40
+ expires_in: z.number().optional(),
41
+ refresh_token: z.string().optional(),
42
+ id_token: z.string().optional(),
43
+ scope: z.string().optional()
44
+ });
45
+ var balanceSchema = z.object({
46
+ /** Settled balance. */
47
+ postedMicro: z.number().int(),
48
+ /** Settled minus active holds. */
49
+ pendingMicro: z.number().int(),
50
+ /** Most conservative spendable amount — gate approvals on this. */
51
+ availableMicro: z.number().int(),
52
+ currency: z.literal("credits").default("credits"),
53
+ asOf: z.coerce.date().default(() => /* @__PURE__ */ new Date(0))
54
+ });
55
+ var meterAggregationSchema = z.enum([
56
+ "sum",
57
+ "count",
58
+ "max",
59
+ "min",
60
+ "unique_count",
61
+ "latest"
62
+ ]);
63
+ var usageEventSchema = z.object({
64
+ surface: surfaceSchema,
65
+ /** Stable, producer-supplied dedup id. */
66
+ transactionId: z.string().min(8).max(255),
67
+ operation: z.string().min(1),
68
+ model: z.string().nullable().default(null),
69
+ provider: z.string().nullable().default(null),
70
+ /** Pre-computed cost in micro-credits, if the caller priced it. */
71
+ costMicro: z.number().int().nonnegative().nullable().default(null),
72
+ inputTokens: z.number().int().nonnegative().nullable().default(null),
73
+ outputTokens: z.number().int().nonnegative().nullable().default(null),
74
+ /** Arbitrary attribution dimensions (project, workspace, …). */
75
+ dimensions: z.record(z.string(), z.string()).default({}),
76
+ occurredAt: z.coerce.date().optional()
77
+ });
78
+ var usageResultSchema = z.object({
79
+ accepted: z.boolean(),
80
+ /** True when the event was a duplicate (idempotent no-op). */
81
+ duplicate: z.boolean().default(false),
82
+ costMicro: z.number().int().nonnegative(),
83
+ transactionId: z.string(),
84
+ balance: balanceSchema.nullable().default(null)
85
+ });
86
+ var holdRequestSchema = z.object({
87
+ surface: surfaceSchema,
88
+ /** Idempotency key for the hold itself. */
89
+ holdId: z.string().min(8).max(255),
90
+ amountMicro: z.number().int().positive(),
91
+ operation: z.string().min(1),
92
+ expiresInSeconds: z.number().int().positive().max(86400).default(900),
93
+ dimensions: z.record(z.string(), z.string()).default({})
94
+ });
95
+ var holdSchema = z.object({
96
+ holdId: z.string(),
97
+ state: z.enum([
98
+ "held",
99
+ "settled",
100
+ "voided",
101
+ "expired"
102
+ ]),
103
+ amountMicro: z.number().int().nonnegative(),
104
+ settledMicro: z.number().int().nonnegative().default(0),
105
+ balance: balanceSchema.nullable().default(null)
106
+ });
107
+ var authzCheckSchema = z.object({
108
+ /** e.g. `user:abc` or `agent:scout`. */
109
+ subject: z.string().min(1),
110
+ relation: z.string().min(1),
111
+ /** e.g. `workspace:acme` or `post:123`. */
112
+ object: z.string().min(1),
113
+ context: z.record(z.string(), z.unknown()).default({})
114
+ });
115
+ var authzResultSchema = z.object({
116
+ allowed: z.boolean(),
117
+ /** Optional reason/trace for debugging (never authoritative). */
118
+ reason: z.string().nullable().default(null)
119
+ });
120
+ function toMicro(credits) {
121
+ return Math.round(credits * MICRO_PER_CREDIT);
122
+ }
123
+ __name(toMicro, "toMicro");
124
+ function fromMicro(micro) {
125
+ return micro / MICRO_PER_CREDIT;
126
+ }
127
+ __name(fromMicro, "fromMicro");
128
+
129
+ // src/jwt-json.ts
130
+ function parseJwtObject(source) {
131
+ if (source.length > 16384) throw new SyntaxError("JWT JSON bound");
132
+ let offset = 0;
133
+ const whitespace = /* @__PURE__ */ __name(() => {
134
+ while (offset < source.length && /[ \t\r\n]/.test(source[offset] ?? "")) offset++;
135
+ }, "whitespace");
136
+ const invalid2 = /* @__PURE__ */ __name(() => {
137
+ throw new SyntaxError("Ambiguous JWT JSON");
138
+ }, "invalid");
139
+ const string = /* @__PURE__ */ __name(() => {
140
+ const start = offset++;
141
+ while (offset < source.length) {
142
+ const current = source[offset++];
143
+ if (current === '"') return JSON.parse(source.slice(start, offset));
144
+ if (current === "\\") offset++;
145
+ }
146
+ return invalid2();
147
+ }, "string");
148
+ const value = /* @__PURE__ */ __name((depth) => {
149
+ if (depth > 8) invalid2();
150
+ whitespace();
151
+ const opening = source[offset];
152
+ if (opening === '"') {
153
+ string();
154
+ return;
155
+ }
156
+ if (opening === "{" || opening === "[") {
157
+ const close = opening === "{" ? "}" : "]";
158
+ offset++;
159
+ whitespace();
160
+ if (source[offset] === close) {
161
+ offset++;
162
+ return;
163
+ }
164
+ const names = /* @__PURE__ */ new Set();
165
+ let count = 0;
166
+ while (offset < source.length) {
167
+ if (++count > 256) invalid2();
168
+ if (opening === "{") {
169
+ whitespace();
170
+ if (source[offset] !== '"') invalid2();
171
+ const key = string();
172
+ if (names.has(key) || key === "__proto__" || key === "constructor" || key === "prototype") invalid2();
173
+ names.add(key);
174
+ whitespace();
175
+ if (source[offset++] !== ":") invalid2();
176
+ }
177
+ value(depth + 1);
178
+ whitespace();
179
+ if (source[offset] === close) {
180
+ offset++;
181
+ return;
182
+ }
183
+ if (source[offset++] !== ",") invalid2();
184
+ }
185
+ return invalid2();
186
+ }
187
+ const literal = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(offset));
188
+ if (!literal) return invalid2();
189
+ offset += literal[0].length;
190
+ }, "value");
191
+ value(0);
192
+ whitespace();
193
+ if (offset !== source.length) invalid2();
194
+ const parsed = JSON.parse(source, (_key, item) => {
195
+ if (typeof item === "number" && !Number.isFinite(item)) invalid2();
196
+ return item;
197
+ });
198
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) invalid2();
199
+ return parsed;
200
+ }
201
+ __name(parseJwtObject, "parseJwtObject");
202
+
203
+ // src/http.ts
204
+ function authorizationArgs(auth) {
205
+ return typeof auth === "function" ? {
206
+ authorization: auth
207
+ } : typeof auth === "string" ? {
208
+ token: auth,
209
+ tokenType: "Bearer"
210
+ } : {
211
+ token: auth.token,
212
+ tokenType: auth.tokenType,
213
+ headers: auth.headers
214
+ };
215
+ }
216
+ __name(authorizationArgs, "authorizationArgs");
217
+ var Transport = class {
218
+ static {
219
+ __name(this, "Transport");
220
+ }
221
+ fetchImpl;
222
+ timeoutMs;
223
+ maxRetries;
224
+ userAgent;
225
+ maxResponseBytes;
226
+ constructor(opts = {}) {
227
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
228
+ this.timeoutMs = opts.timeoutMs ?? 8e3;
229
+ this.maxRetries = opts.maxRetries ?? 2;
230
+ this.userAgent = opts.userAgent ?? "xeno-account-client/0.1";
231
+ this.maxResponseBytes = opts.maxResponseBytes ?? 1024 * 1024;
232
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 12e4 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1 || this.maxResponseBytes > 8 * 1024 * 1024 || !Number.isSafeInteger(this.maxRetries) || this.maxRetries < 0 || this.maxRetries > 10) throw new TypeError("Account transport deadline and response bound are invalid");
233
+ }
234
+ /** Perform a request and return parsed JSON (or null for empty bodies). */
235
+ async request(args) {
236
+ let body = args.body;
237
+ const headers = {
238
+ ...args.headers
239
+ };
240
+ if (body !== void 0 && typeof body !== "string") {
241
+ try {
242
+ body = JSON.stringify(body);
243
+ } catch {
244
+ throw new AccountError({
245
+ code: "BAD_REQUEST",
246
+ message: "Account request body cannot be serialized"
247
+ });
248
+ }
249
+ headers["content-type"] = "application/json";
250
+ }
251
+ args = Object.freeze({
252
+ ...args,
253
+ body,
254
+ headers: Object.freeze(headers)
255
+ });
256
+ const isMutation = args.method !== "GET";
257
+ const staticProof = args.tokenType === "DPoP" || Object.keys(args.headers ?? {}).some((name) => name.toLowerCase() === "dpop");
258
+ const retrySafe = (!isMutation || Boolean(args.idempotencyKey)) && (!staticProof || Boolean(args.authorization));
259
+ const attempts = retrySafe ? this.maxRetries + 1 : 1;
260
+ let lastErr = null;
261
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
262
+ try {
263
+ return await this.once(args);
264
+ } catch (err) {
265
+ const ae = err instanceof AccountError ? err : new AccountError({
266
+ code: "UNREACHABLE",
267
+ message: "Account request failed before a verified response was received"
268
+ });
269
+ lastErr = ae;
270
+ if (!ae.retryable || attempt === attempts - 1) throw ae;
271
+ await sleep(backoffMs(attempt, ae.retryAfterMs), args.signal);
272
+ }
273
+ }
274
+ throw lastErr ?? new AccountError({
275
+ code: "PLATFORM_ERROR",
276
+ message: "request failed"
277
+ });
278
+ }
279
+ async once(args) {
280
+ const controller = new AbortController();
281
+ const callerAborted = /* @__PURE__ */ __name(() => controller.abort(), "callerAborted");
282
+ args.signal?.addEventListener("abort", callerAborted, {
283
+ once: true
284
+ });
285
+ if (args.signal?.aborted) callerAborted();
286
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
287
+ let res;
288
+ try {
289
+ if (args.signal?.aborted) throw cancellationError();
290
+ let auth;
291
+ if (args.authorization) {
292
+ try {
293
+ auth = await beforeAbort(args.authorization(args.method, args.url), controller.signal);
294
+ } catch (error) {
295
+ throw new AccountError({
296
+ code: error instanceof AccountError ? error.code : "UNREACHABLE",
297
+ message: "Account request authorization unavailable",
298
+ ...error instanceof AccountError ? {
299
+ httpStatus: error.httpStatus,
300
+ retryable: error.retryable
301
+ } : {}
302
+ });
303
+ }
304
+ if (!auth || typeof auth.token !== "string" || !auth.token || auth.token.length > 16384 || /[\r\n]/.test(auth.token) || ![
305
+ "Bearer",
306
+ "DPoP"
307
+ ].includes(auth.tokenType)) throw new AccountError({
308
+ code: "INVALID_TOKEN",
309
+ message: "Account request authorization invalid"
310
+ });
311
+ const proofHeaders = Object.entries(auth.headers ?? {}).filter(([name]) => name.toLowerCase() === "dpop");
312
+ if (auth.tokenType === "DPoP" && (proofHeaders.length !== 1 || typeof proofHeaders[0]?.[1] !== "string" || !proofHeaders[0][1] || proofHeaders[0][1].length > 16384 || /[\r\n]/.test(proofHeaders[0][1]))) throw new AccountError({
313
+ code: "INVALID_TOKEN",
314
+ message: "Account request proof invalid"
315
+ });
316
+ }
317
+ const supplied = Object.fromEntries(Object.entries(args.headers ?? {}).map(([key, value]) => [
318
+ key.toLowerCase(),
319
+ value
320
+ ]));
321
+ if (auth) {
322
+ delete supplied.authorization;
323
+ delete supplied.dpop;
324
+ }
325
+ const headers = {
326
+ accept: "application/json",
327
+ "user-agent": this.userAgent,
328
+ ...supplied,
329
+ ...Object.fromEntries(Object.entries(auth?.headers ?? {}).map(([key, value]) => [
330
+ key.toLowerCase(),
331
+ value
332
+ ]))
333
+ };
334
+ const token = auth?.token ?? args.token;
335
+ if (token) headers["authorization"] = `${auth?.tokenType ?? args.tokenType ?? "Bearer"} ${token}`;
336
+ if (args.idempotencyKey) headers["idempotency-key"] = args.idempotencyKey;
337
+ let payload;
338
+ if (typeof args.body === "string") {
339
+ payload = args.body;
340
+ } else if (args.body !== void 0) {
341
+ headers["content-type"] = "application/json";
342
+ try {
343
+ payload = JSON.stringify(args.body);
344
+ } catch {
345
+ throw new AccountError({
346
+ code: "BAD_REQUEST",
347
+ message: "Account request body cannot be serialized"
348
+ });
349
+ }
350
+ }
351
+ if (controller.signal.aborted) throw new Error("Account response deadline");
352
+ res = await fetchBeforeAbort(this.fetchImpl, args.url, {
353
+ method: args.method,
354
+ headers,
355
+ body: payload,
356
+ signal: controller.signal,
357
+ redirect: "error",
358
+ cache: "no-store",
359
+ credentials: "omit"
360
+ }, controller.signal);
361
+ if (!res.ok) {
362
+ const code = codeForStatus(res.status);
363
+ const oauthError = args.oauthErrorResponse ? await readOAuthError(res, controller.signal) : null;
364
+ throw new AccountError({
365
+ code,
366
+ message: `${args.method} ${safeUrl(args.url)} -> ${res.status}`,
367
+ httpStatus: res.status,
368
+ retryAfterMs: parseRetryAfter(res.headers.get("retry-after")),
369
+ oauthError
370
+ });
371
+ }
372
+ if (res.status === 204 || !res.body) return null;
373
+ const text2 = await readBoundedText(res, controller.signal, this.maxResponseBytes);
374
+ if (!text2) return null;
375
+ try {
376
+ return JSON.parse(text2);
377
+ } catch {
378
+ throw new AccountError({
379
+ code: "INVALID_RESPONSE",
380
+ message: `non-JSON response from ${safeUrl(args.url)}`
381
+ });
382
+ }
383
+ } catch (err) {
384
+ if (args.signal?.aborted) throw cancellationError();
385
+ if (err instanceof AccountError) throw err;
386
+ throw new AccountError({
387
+ code: "UNREACHABLE",
388
+ message: `request to ${safeUrl(args.url)} failed`,
389
+ retryable: true
390
+ });
391
+ } finally {
392
+ controller.abort();
393
+ args.signal?.removeEventListener("abort", callerAborted);
394
+ clearTimeout(timer);
395
+ if (res) cancelBody(res);
396
+ }
397
+ }
398
+ };
399
+ function cancelBody(response) {
400
+ void response.body?.cancel().catch(() => {
401
+ });
402
+ }
403
+ __name(cancelBody, "cancelBody");
404
+ function beforeAbort(pending, signal) {
405
+ return new Promise((resolve, reject) => {
406
+ const aborted = /* @__PURE__ */ __name(() => {
407
+ signal.removeEventListener("abort", aborted);
408
+ reject(new Error("Account response deadline"));
409
+ }, "aborted");
410
+ if (signal.aborted) {
411
+ void pending.catch(() => {
412
+ });
413
+ aborted();
414
+ return;
415
+ }
416
+ signal.addEventListener("abort", aborted, {
417
+ once: true
418
+ });
419
+ pending.then((value) => {
420
+ signal.removeEventListener("abort", aborted);
421
+ if (signal.aborted) aborted();
422
+ else resolve(value);
423
+ }, (error) => {
424
+ signal.removeEventListener("abort", aborted);
425
+ reject(error);
426
+ });
427
+ });
428
+ }
429
+ __name(beforeAbort, "beforeAbort");
430
+ function fetchBeforeAbort(fetchImpl, url, init, signal) {
431
+ const pending = Promise.resolve(fetchImpl(url, init));
432
+ void pending.then((response) => {
433
+ if (signal.aborted) cancelBody(response);
434
+ }, () => {
435
+ });
436
+ return beforeAbort(pending, signal);
437
+ }
438
+ __name(fetchBeforeAbort, "fetchBeforeAbort");
439
+ async function readBoundedText(response, signal, maxBytes) {
440
+ const reader = response.body?.getReader();
441
+ if (!reader) return "";
442
+ let complete = false;
443
+ try {
444
+ const decoder = new TextDecoder("utf-8", {
445
+ fatal: true
446
+ });
447
+ let text2 = "", size = 0;
448
+ while (true) {
449
+ const chunk = await beforeAbort(reader.read(), signal);
450
+ if (chunk.done) {
451
+ complete = true;
452
+ break;
453
+ }
454
+ size += chunk.value.byteLength;
455
+ if (size > maxBytes) throw new AccountError({
456
+ code: "INVALID_RESPONSE",
457
+ message: "Account response exceeds configured bound"
458
+ });
459
+ try {
460
+ text2 += decoder.decode(chunk.value, {
461
+ stream: true
462
+ });
463
+ } catch {
464
+ throw new AccountError({
465
+ code: "INVALID_RESPONSE",
466
+ message: "Account response is not valid UTF-8"
467
+ });
468
+ }
469
+ }
470
+ try {
471
+ return text2 + decoder.decode();
472
+ } catch {
473
+ throw new AccountError({
474
+ code: "INVALID_RESPONSE",
475
+ message: "Account response is not valid UTF-8"
476
+ });
477
+ }
478
+ } finally {
479
+ if (!complete) void reader.cancel().catch(() => {
480
+ });
481
+ reader.releaseLock();
482
+ }
483
+ }
484
+ __name(readBoundedText, "readBoundedText");
485
+ async function readOAuthError(response, signal) {
486
+ try {
487
+ const body = parseJwtObject(await readBoundedText(response, signal, 4096));
488
+ const code = body.error;
489
+ return typeof code === "string" && [
490
+ "invalid_grant",
491
+ "invalid_client",
492
+ "invalid_scope",
493
+ "invalid_request",
494
+ "unauthorized_client",
495
+ "unsupported_grant_type",
496
+ "authorization_pending",
497
+ "slow_down",
498
+ "access_denied",
499
+ "expired_token",
500
+ "use_dpop_nonce",
501
+ "invalid_dpop_proof"
502
+ ].includes(code) ? code : null;
503
+ } catch {
504
+ return null;
505
+ }
506
+ }
507
+ __name(readOAuthError, "readOAuthError");
508
+ function backoffMs(attempt, retryAfterMs) {
509
+ if (retryAfterMs && retryAfterMs > 0) return Math.min(retryAfterMs, 1e4);
510
+ return Math.min(200 * (2 ** attempt + (attempt === 0 ? 0 : 1)), 5e3);
511
+ }
512
+ __name(backoffMs, "backoffMs");
513
+ function parseRetryAfter(header) {
514
+ if (!header) return null;
515
+ const seconds = Number(header);
516
+ return Number.isFinite(seconds) ? seconds * 1e3 : null;
517
+ }
518
+ __name(parseRetryAfter, "parseRetryAfter");
519
+ function cancellationError() {
520
+ return new AccountError({
521
+ code: "BAD_REQUEST",
522
+ message: "Account request was cancelled; outcome may be unconfirmed",
523
+ retryable: false
524
+ });
525
+ }
526
+ __name(cancellationError, "cancellationError");
527
+ function sleep(ms, signal) {
528
+ return new Promise((resolve, reject) => {
529
+ const timer = setTimeout(done, ms);
530
+ function cleanup() {
531
+ clearTimeout(timer);
532
+ signal?.removeEventListener("abort", aborted);
533
+ }
534
+ __name(cleanup, "cleanup");
535
+ function done() {
536
+ cleanup();
537
+ resolve();
538
+ }
539
+ __name(done, "done");
540
+ function aborted() {
541
+ cleanup();
542
+ reject(cancellationError());
543
+ }
544
+ __name(aborted, "aborted");
545
+ signal?.addEventListener("abort", aborted, {
546
+ once: true
547
+ });
548
+ if (signal?.aborted) aborted();
549
+ });
550
+ }
551
+ __name(sleep, "sleep");
552
+ function safeUrl(url) {
553
+ try {
554
+ const u = new URL(url);
555
+ return u.origin;
556
+ } catch {
557
+ return "[invalid account URL]";
558
+ }
559
+ }
560
+ __name(safeUrl, "safeUrl");
561
+
562
+ // src/account.ts
563
+ var AccountClient = class {
564
+ static {
565
+ __name(this, "AccountClient");
566
+ }
567
+ base;
568
+ transport;
569
+ constructor(base2, transport) {
570
+ this.base = base2;
571
+ this.transport = transport;
572
+ }
573
+ /** Resolve a token to its account, or throw an AccountError. */
574
+ async me(auth) {
575
+ let raw;
576
+ try {
577
+ raw = await this.transport.request({
578
+ method: "GET",
579
+ url: `${this.base}/api/v2/me`,
580
+ ...authorizationArgs(auth)
581
+ });
582
+ } catch (err) {
583
+ const isDpop = typeof auth === "object" && auth.tokenType === "DPoP";
584
+ if (err instanceof AccountError && err.code === "NOT_FOUND" && !isDpop) {
585
+ raw = await this.transport.request({
586
+ method: "GET",
587
+ url: `${this.base}/api/auth/me`,
588
+ ...authorizationArgs(auth)
589
+ });
590
+ } else {
591
+ throw err;
592
+ }
593
+ }
594
+ const account = normalize(raw);
595
+ if (!account) {
596
+ throw new AccountError({
597
+ code: "INVALID_RESPONSE",
598
+ message: "/me returned an unrecognised shape"
599
+ });
600
+ }
601
+ return account;
602
+ }
603
+ };
604
+ function normalize(body) {
605
+ if (!body || typeof body !== "object") return null;
606
+ const root = body;
607
+ const user = root["user"] ?? root["data"] ?? root;
608
+ if (!user || typeof user !== "object") return null;
609
+ const id5 = str(user["id"]);
610
+ const email = str(user["email"]);
611
+ if (!id5 || !email) return null;
612
+ const linked2 = Array.isArray(user["linkedSurfaces"]) ? [
613
+ ...new Set(user["linkedSurfaces"].map(normalizeSurface).filter(isSurface))
614
+ ] : [];
615
+ const parsed = accountSchema.safeParse({
616
+ id: id5,
617
+ email,
618
+ username: str(user["username"]) ?? null,
619
+ displayName: str(user["display_name"]) ?? str(user["displayName"]) ?? null,
620
+ avatarUrl: str(user["avatar_url"]) ?? str(user["avatarUrl"]) ?? null,
621
+ emailVerified: Boolean(user["email_verified"] ?? user["emailVerified"] ?? false),
622
+ linkedSurfaces: linked2
623
+ });
624
+ return parsed.success ? parsed.data : null;
625
+ }
626
+ __name(normalize, "normalize");
627
+ function str(v) {
628
+ return typeof v === "string" && v.length > 0 ? v : void 0;
629
+ }
630
+ __name(str, "str");
631
+ function normalizeSurface(value) {
632
+ if (typeof value !== "string") return void 0;
633
+ const parsed = surfaceSchema.safeParse(value.trim().toLowerCase().replace(/-/g, "_"));
634
+ return parsed.success ? parsed.data : void 0;
635
+ }
636
+ __name(normalizeSurface, "normalizeSurface");
637
+ function isSurface(value) {
638
+ return value !== void 0;
639
+ }
640
+ __name(isSurface, "isSurface");
641
+
642
+ // src/ledger.ts
643
+ var LedgerClient = class {
644
+ static {
645
+ __name(this, "LedgerClient");
646
+ }
647
+ apiBase;
648
+ transport;
649
+ constructor(apiBase, transport) {
650
+ this.apiBase = apiBase;
651
+ this.transport = transport;
652
+ }
653
+ /** Posted / pending / available balance for the token's account. */
654
+ async getBalance(auth) {
655
+ const raw = await this.transport.request({
656
+ method: "GET",
657
+ url: `${this.apiBase}/api/v2/ledger/balance`,
658
+ ...authorizationArgs(auth)
659
+ });
660
+ return parse(balanceSchema, raw);
661
+ }
662
+ /**
663
+ * Record a usage event (the meter). Idempotent on `transactionId`; a duplicate
664
+ * returns `{ duplicate: true }` and does not charge again.
665
+ */
666
+ async recordUsage(auth, event) {
667
+ const e = usageEventSchema.parse(event);
668
+ const raw = await this.transport.request({
669
+ method: "POST",
670
+ url: `${this.apiBase}/api/v2/ledger/usage`,
671
+ ...authorizationArgs(auth),
672
+ body: e,
673
+ idempotencyKey: e.transactionId
674
+ });
675
+ return parse(usageResultSchema, raw);
676
+ }
677
+ /**
678
+ * Reserve credits for a per-use action (phase 1 of two-phase spend). Rejected
679
+ * with `INSUFFICIENT_CREDITS` if `available < amount`. Idempotent on `holdId`.
680
+ */
681
+ async hold(auth, req) {
682
+ const r = holdRequestSchema.parse(req);
683
+ const raw = await this.transport.request({
684
+ method: "POST",
685
+ url: `${this.apiBase}/api/v2/ledger/holds`,
686
+ ...authorizationArgs(auth),
687
+ body: r,
688
+ idempotencyKey: r.holdId
689
+ });
690
+ return parse(holdSchema, raw);
691
+ }
692
+ /**
693
+ * Settle a hold for the actual cost (phase 2). Posting less than the held
694
+ * amount auto-restores the remainder. Idempotent on `holdId`.
695
+ */
696
+ async settle(auth, holdId, actualCostMicro) {
697
+ const raw = await this.transport.request({
698
+ method: "POST",
699
+ url: `${this.apiBase}/api/v2/ledger/holds/${encodeURIComponent(holdId)}/settle`,
700
+ ...authorizationArgs(auth),
701
+ body: {
702
+ actualCostMicro
703
+ },
704
+ idempotencyKey: `${holdId}:settle`
705
+ });
706
+ return parse(holdSchema, raw);
707
+ }
708
+ /** Release a hold without charging (failure/cancel). Idempotent on `holdId`. */
709
+ async void(auth, holdId) {
710
+ const raw = await this.transport.request({
711
+ method: "POST",
712
+ url: `${this.apiBase}/api/v2/ledger/holds/${encodeURIComponent(holdId)}/void`,
713
+ ...authorizationArgs(auth),
714
+ body: {},
715
+ idempotencyKey: `${holdId}:void`
716
+ });
717
+ return parse(holdSchema, raw);
718
+ }
719
+ };
720
+ function parse(schema, raw) {
721
+ const r = schema.safeParse(raw);
722
+ if (!r.success || r.data === void 0) {
723
+ throw new AccountError({
724
+ code: "INVALID_RESPONSE",
725
+ message: "ledger returned an unrecognised shape"
726
+ });
727
+ }
728
+ return r.data;
729
+ }
730
+ __name(parse, "parse");
731
+
732
+ // src/authz.ts
733
+ var AuthzClient = class {
734
+ static {
735
+ __name(this, "AuthzClient");
736
+ }
737
+ apiBase;
738
+ transport;
739
+ constructor(apiBase, transport) {
740
+ this.apiBase = apiBase;
741
+ this.transport = transport;
742
+ }
743
+ async check(auth, check) {
744
+ const raw = await this.transport.request({
745
+ method: "POST",
746
+ url: `${this.apiBase}/api/v2/authz/check`,
747
+ ...authorizationArgs(auth),
748
+ body: check
749
+ });
750
+ const parsed = authzResultSchema.safeParse(raw);
751
+ if (!parsed.success) {
752
+ throw new AccountError({
753
+ code: "INVALID_RESPONSE",
754
+ message: "authz returned an unrecognised shape"
755
+ });
756
+ }
757
+ return parsed.data;
758
+ }
759
+ };
760
+
761
+ // src/workspaces.ts
762
+ import { z as z3 } from "zod";
763
+
764
+ // src/workspaceMembership.ts
765
+ import { z as z2 } from "zod";
766
+ var id = z2.string().uuid();
767
+ var timestamp = z2.string().datetime({
768
+ offset: true
769
+ });
770
+ var role = z2.enum([
771
+ "admin",
772
+ "member",
773
+ "viewer"
774
+ ]);
775
+ var membershipMutationSchema = z2.discriminatedUnion("action", [
776
+ z2.object({
777
+ action: z2.literal("invite.create"),
778
+ email: z2.string().email().max(320).regex(/^[^\x00-\x20\x7f]+$/),
779
+ role
780
+ }).strict(),
781
+ z2.object({
782
+ action: z2.literal("invite.revoke"),
783
+ inviteId: id
784
+ }).strict(),
785
+ z2.object({
786
+ action: z2.literal("invite.resend"),
787
+ inviteId: id
788
+ }).strict(),
789
+ z2.object({
790
+ action: z2.literal("member.role"),
791
+ memberId: id,
792
+ role
793
+ }).strict(),
794
+ z2.object({
795
+ action: z2.literal("member.remove"),
796
+ memberId: id
797
+ }).strict(),
798
+ z2.object({
799
+ action: z2.literal("owner.transfer"),
800
+ newOwnerId: id
801
+ }).strict()
802
+ ]);
803
+ var base = {
804
+ operation_id: id,
805
+ workspace_id: id,
806
+ actor_user_id: id,
807
+ client_id: z2.string().regex(/^[a-zA-Z0-9._-]{1,128}$/),
808
+ committed_at: timestamp
809
+ };
810
+ var invite = z2.object({
811
+ id,
812
+ workspace_id: id,
813
+ invited_email: z2.string().email(),
814
+ role,
815
+ status: z2.enum([
816
+ "pending",
817
+ "revoked"
818
+ ]),
819
+ expires_at: timestamp
820
+ }).strict();
821
+ var delivery = z2.object({
822
+ id,
823
+ state: z2.literal("queued")
824
+ }).strict();
825
+ var membershipCommittedSchema = z2.discriminatedUnion("action", [
826
+ z2.object({
827
+ ...base,
828
+ action: z2.literal("invite.create"),
829
+ result: z2.object({
830
+ invite,
831
+ delivery
832
+ }).strict()
833
+ }).strict(),
834
+ z2.object({
835
+ ...base,
836
+ action: z2.literal("invite.resend"),
837
+ result: z2.object({
838
+ invite,
839
+ delivery
840
+ }).strict()
841
+ }).strict(),
842
+ z2.object({
843
+ ...base,
844
+ action: z2.literal("invite.revoke"),
845
+ result: z2.object({
846
+ invite
847
+ }).strict()
848
+ }).strict(),
849
+ z2.object({
850
+ ...base,
851
+ action: z2.literal("member.role"),
852
+ result: z2.object({
853
+ memberId: id,
854
+ role
855
+ }).strict()
856
+ }).strict(),
857
+ z2.object({
858
+ ...base,
859
+ action: z2.literal("member.remove"),
860
+ result: z2.object({
861
+ memberId: id
862
+ }).strict()
863
+ }).strict(),
864
+ z2.object({
865
+ ...base,
866
+ action: z2.literal("owner.transfer"),
867
+ result: z2.object({
868
+ memberId: id,
869
+ previousOwnerId: id
870
+ }).strict()
871
+ }).strict()
872
+ ]);
873
+ var membershipRejectedSchema = z2.object({
874
+ ...base,
875
+ action: z2.enum([
876
+ "invite.create",
877
+ "invite.resend",
878
+ "invite.revoke",
879
+ "member.role",
880
+ "member.remove",
881
+ "owner.transfer"
882
+ ]),
883
+ rejection: z2.enum([
884
+ "invalid_membership_request",
885
+ "member_not_found",
886
+ "owner_transfer_required",
887
+ "owner_target_not_member",
888
+ "invite_not_found",
889
+ "invite_already_pending",
890
+ "already_member",
891
+ "seat_limit"
892
+ ])
893
+ }).strict();
894
+ var membershipAbandonedSchema = membershipRejectedSchema.omit({
895
+ rejection: true
896
+ }).extend({
897
+ abandoned: z2.literal(true),
898
+ request: membershipMutationSchema
899
+ }).strict();
900
+ var membershipOperationSchema = z2.union([
901
+ membershipCommittedSchema,
902
+ membershipRejectedSchema,
903
+ membershipAbandonedSchema
904
+ ]);
905
+ var membershipDeliverySchema = z2.object({
906
+ id,
907
+ state: z2.enum([
908
+ "queued",
909
+ "accepted",
910
+ "skipped",
911
+ "unknown"
912
+ ])
913
+ }).strict();
914
+ var WorkspaceMembershipMutationError = class extends AccountError {
915
+ static {
916
+ __name(this, "WorkspaceMembershipMutationError");
917
+ }
918
+ operationId;
919
+ outcome = "uncertain";
920
+ constructor(operationId) {
921
+ super({
922
+ code: "PLATFORM_ERROR",
923
+ message: "Workspace membership acknowledgement is uncertain. Read back the same operation.",
924
+ retryable: false
925
+ }), this.operationId = operationId;
926
+ }
927
+ };
928
+ function assertMembershipOperation(workspaceId, operationId, operation3, request) {
929
+ if (operation3.workspace_id.toLowerCase() !== workspaceId.toLowerCase() || operation3.operation_id.toLowerCase() !== operationId.toLowerCase() || request && operation3.action !== request.action) throw new Error("Foreign membership receipt");
930
+ if ("rejection" in operation3) return;
931
+ if ("abandoned" in operation3) {
932
+ if (operation3.request.action !== operation3.action || request && JSON.stringify(membershipMutationSchema.parse(request)) !== JSON.stringify(operation3.request)) throw new Error("Wrong abandoned membership intent");
933
+ return;
934
+ }
935
+ if (operation3.action.startsWith("invite.")) {
936
+ if (!("invite" in operation3.result) || operation3.result.invite.workspace_id !== operation3.workspace_id || operation3.result.invite.status !== (operation3.action === "invite.revoke" ? "revoked" : "pending")) throw new Error("Foreign invitation receipt");
937
+ if (request && "inviteId" in request && operation3.result.invite.id !== request.inviteId) throw new Error("Wrong invitation target");
938
+ if (request?.action === "invite.create" && (operation3.result.invite.invited_email !== request.email.toLowerCase() || operation3.result.invite.role !== request.role)) throw new Error("Wrong invitation intent");
939
+ } else if ("memberId" in operation3.result) {
940
+ if (request && "memberId" in request && operation3.result.memberId !== request.memberId) throw new Error("Wrong member target");
941
+ if (request?.action === "member.role" && (!("role" in operation3.result) || operation3.result.role !== request.role)) throw new Error("Wrong member role");
942
+ if (operation3.action === "owner.transfer" && (operation3.result.previousOwnerId !== operation3.actor_user_id || request?.action === "owner.transfer" && operation3.result.memberId !== request.newOwnerId)) throw new Error("Wrong owner target");
943
+ }
944
+ }
945
+ __name(assertMembershipOperation, "assertMembershipOperation");
946
+
947
+ // src/workspaces.ts
948
+ var workspaceRoleSchema = z3.enum([
949
+ "owner",
950
+ "admin",
951
+ "member",
952
+ "viewer"
953
+ ]);
954
+ var workspaceInviteRoleSchema = z3.enum([
955
+ "admin",
956
+ "member",
957
+ "viewer"
958
+ ]);
959
+ var id2 = z3.string().uuid();
960
+ var timestamp2 = z3.string().datetime({
961
+ offset: true
962
+ });
963
+ var workspaceSchema = z3.object({
964
+ id: id2,
965
+ owner_user_id: id2,
966
+ workspace_type: z3.enum([
967
+ "personal",
968
+ "team"
969
+ ]),
970
+ name: z3.string().min(1),
971
+ slug: z3.string().min(1),
972
+ status: z3.string().min(1),
973
+ created_at: timestamp2,
974
+ updated_at: timestamp2,
975
+ metadata: z3.record(z3.string(), z3.unknown()),
976
+ member_role: workspaceRoleSchema.optional(),
977
+ member_count: z3.number().int().nonnegative().optional()
978
+ });
979
+ var workspaceMemberSchema = z3.object({
980
+ id: id2,
981
+ user_id: id2,
982
+ member_role: workspaceRoleSchema,
983
+ member_status: z3.literal("active"),
984
+ created_at: timestamp2,
985
+ user: z3.object({
986
+ username: z3.string().nullable(),
987
+ email: z3.string().email(),
988
+ display_name: z3.string().nullable(),
989
+ avatar_url: z3.string().url().nullable()
990
+ }).optional()
991
+ });
992
+ var workspaceInviteSchema = z3.object({
993
+ id: id2,
994
+ workspace_id: id2,
995
+ invited_by_user_id: id2,
996
+ invited_user_id: id2.nullable(),
997
+ invited_email: z3.string().email(),
998
+ role: workspaceInviteRoleSchema,
999
+ status: z3.enum([
1000
+ "pending",
1001
+ "accepted",
1002
+ "declined",
1003
+ "revoked",
1004
+ "expired"
1005
+ ]),
1006
+ created_at: timestamp2,
1007
+ expires_at: timestamp2.nullable(),
1008
+ workspace_name: z3.string().optional(),
1009
+ invited_by_name: z3.string().nullable().optional()
1010
+ });
1011
+ var accountOperationIntentSchema = z3.discriminatedUnion("action", [
1012
+ z3.object({
1013
+ action: z3.literal("workspace.create"),
1014
+ name: z3.string().trim().min(1).max(128),
1015
+ type: z3.literal("team")
1016
+ }).strict(),
1017
+ z3.object({
1018
+ action: z3.literal("invite.accept"),
1019
+ inviteId: id2
1020
+ }).strict(),
1021
+ z3.object({
1022
+ action: z3.literal("invite.decline"),
1023
+ inviteId: id2
1024
+ }).strict()
1025
+ ]);
1026
+ var accountOperationSchema = z3.object({
1027
+ operation_id: id2,
1028
+ actor_user_id: id2,
1029
+ client_id: z3.string().regex(/^[a-zA-Z0-9._-]{1,128}$/),
1030
+ action: z3.enum([
1031
+ "workspace.create",
1032
+ "invite.accept",
1033
+ "invite.decline"
1034
+ ]),
1035
+ committed_at: timestamp2,
1036
+ result: z3.union([
1037
+ z3.object({
1038
+ workspace: workspaceSchema
1039
+ }).strict(),
1040
+ z3.object({
1041
+ invite: workspaceInviteSchema
1042
+ }).strict()
1043
+ ])
1044
+ }).strict();
1045
+ var AccountMutationError = class extends AccountError {
1046
+ static {
1047
+ __name(this, "AccountMutationError");
1048
+ }
1049
+ operationId;
1050
+ outcome = "uncertain";
1051
+ constructor(operationId) {
1052
+ super({
1053
+ code: "PLATFORM_ERROR",
1054
+ message: "Account mutation acknowledgement is uncertain. Read back the same operation.",
1055
+ retryable: false
1056
+ }), this.operationId = operationId;
1057
+ }
1058
+ };
1059
+ var workspaceKeyScopeSchema = z3.enum([
1060
+ "workspace:read",
1061
+ "workspace:members:read"
1062
+ ]);
1063
+ var keyScopes = z3.array(workspaceKeyScopeSchema).min(1).max(2).refine((values) => new Set(values).size === values.length);
1064
+ var workspaceKeySchema = z3.object({
1065
+ id: id2,
1066
+ workspace_id: id2,
1067
+ created_by_user_id: id2,
1068
+ name: z3.string().min(1).max(100),
1069
+ prefix: z3.string().regex(/^xeno-ws-v1_[0-9a-f]{13}$/),
1070
+ scopes: keyScopes,
1071
+ revision: z3.number().int().positive(),
1072
+ created_at: timestamp2,
1073
+ expires_at: timestamp2,
1074
+ revoked_at: timestamp2.nullable(),
1075
+ replaced_by: id2.nullable()
1076
+ });
1077
+ var workspaceKeyInputSchema = z3.object({
1078
+ name: z3.string().trim().min(1).max(100).regex(/^[^\x00-\x1f]+$/),
1079
+ scopes: keyScopes,
1080
+ expires_at: timestamp2.refine((value) => Date.parse(value) > Date.now() && Date.parse(value) <= Date.now() + 90 * 864e5)
1081
+ }).strict();
1082
+ var keySecretSchema = z3.string().regex(/^xeno-ws-v1_[0-9a-f]{64}$/);
1083
+ var committedKeyOperationSchema = z3.object({
1084
+ operation_id: id2,
1085
+ workspace_id: id2,
1086
+ actor_user_id: id2,
1087
+ client_id: z3.string().regex(/^[a-zA-Z0-9._-]{1,128}$/),
1088
+ action: z3.enum([
1089
+ "create",
1090
+ "rotate",
1091
+ "revoke"
1092
+ ]),
1093
+ key: workspaceKeySchema,
1094
+ previous_key_id: id2.nullable(),
1095
+ committed_at: timestamp2
1096
+ }).strict();
1097
+ var workspaceKeyRejectionSchema = z3.enum([
1098
+ "invalid_workspace_key_request",
1099
+ "invalid_workspace_key_revision",
1100
+ "workspace_key_not_found",
1101
+ "workspace_key_conflict"
1102
+ ]);
1103
+ var rejectedKeyOperationSchema = committedKeyOperationSchema.omit({
1104
+ key: true
1105
+ }).extend({
1106
+ rejection: workspaceKeyRejectionSchema
1107
+ }).strict();
1108
+ var abandonedKeyOperationSchema = committedKeyOperationSchema.omit({
1109
+ key: true
1110
+ }).extend({
1111
+ abandoned: z3.literal(true)
1112
+ }).strict();
1113
+ var workspaceKeyOperationSchema = z3.union([
1114
+ committedKeyOperationSchema,
1115
+ rejectedKeyOperationSchema,
1116
+ abandonedKeyOperationSchema
1117
+ ]);
1118
+ var keyOperationInput = workspaceKeyInputSchema.extend({
1119
+ expires_at: timestamp2
1120
+ });
1121
+ var keyMutationSchema = z3.discriminatedUnion("action", [
1122
+ z3.object({
1123
+ action: z3.literal("create"),
1124
+ input: keyOperationInput
1125
+ }).strict(),
1126
+ z3.object({
1127
+ action: z3.literal("rotate"),
1128
+ keyId: id2,
1129
+ expectedRevision: z3.number().int().positive(),
1130
+ input: keyOperationInput.partial().optional()
1131
+ }).strict(),
1132
+ z3.object({
1133
+ action: z3.literal("revoke"),
1134
+ keyId: id2,
1135
+ expectedRevision: z3.number().int().positive()
1136
+ }).strict()
1137
+ ]);
1138
+ var WorkspaceKeyMutationError = class extends AccountError {
1139
+ static {
1140
+ __name(this, "WorkspaceKeyMutationError");
1141
+ }
1142
+ operationId;
1143
+ outcome = "uncertain";
1144
+ constructor(operationId) {
1145
+ super({
1146
+ code: "PLATFORM_ERROR",
1147
+ message: "Workspace key mutation acknowledgement is uncertain. Read back the same operation.",
1148
+ retryable: false
1149
+ }), this.operationId = operationId;
1150
+ }
1151
+ };
1152
+ var workspaceKeyCursor = z3.string().regex(/^[a-z0-9_-]{1,512}$/i);
1153
+ var success = z3.object({
1154
+ success: z3.literal(true)
1155
+ });
1156
+ var membersResponse = success.extend({
1157
+ workspace: workspaceSchema,
1158
+ members: z3.array(workspaceMemberSchema)
1159
+ });
1160
+ var invitesResponse = success.extend({
1161
+ invites: z3.array(workspaceInviteSchema)
1162
+ });
1163
+ var WorkspaceClient = class {
1164
+ static {
1165
+ __name(this, "WorkspaceClient");
1166
+ }
1167
+ transport;
1168
+ authorize;
1169
+ base;
1170
+ constructor(base2, transport, authorize) {
1171
+ this.transport = transport;
1172
+ this.authorize = authorize;
1173
+ const origin = new URL(base2);
1174
+ if (origin.protocol !== "https:" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/") {
1175
+ throw new AccountError({
1176
+ code: "BAD_REQUEST",
1177
+ message: "Workspace API requires an HTTPS origin."
1178
+ });
1179
+ }
1180
+ this.base = origin.origin;
1181
+ }
1182
+ async call(method, path, scope, schema, body, idempotencyKey) {
1183
+ const url = `${this.base}/api${path}`;
1184
+ const raw = await this.transport.request({
1185
+ method,
1186
+ url,
1187
+ ...body === void 0 ? {} : {
1188
+ body
1189
+ },
1190
+ ...idempotencyKey ? {
1191
+ idempotencyKey
1192
+ } : {},
1193
+ authorization: /* @__PURE__ */ __name(async () => {
1194
+ const auth = await this.authorize(method, url, {
1195
+ scopes: [
1196
+ scope
1197
+ ],
1198
+ silent: true
1199
+ });
1200
+ if (!auth) throw new AccountError({
1201
+ code: "INVALID_TOKEN",
1202
+ message: "Sign in to manage workspaces."
1203
+ });
1204
+ return auth;
1205
+ }, "authorization")
1206
+ });
1207
+ const parsed = schema.safeParse(raw);
1208
+ if (!parsed.success) throw new AccountError({
1209
+ code: "INVALID_RESPONSE",
1210
+ message: "Invalid workspace response."
1211
+ });
1212
+ return parsed.data;
1213
+ }
1214
+ async list() {
1215
+ return (await this.call("GET", "/workspaces", "team:read", success.extend({
1216
+ workspaces: z3.array(workspaceSchema)
1217
+ }))).workspaces;
1218
+ }
1219
+ async keys(workspaceId, options = {}) {
1220
+ const input = z3.object({
1221
+ cursor: workspaceKeyCursor.optional(),
1222
+ limit: z3.number().int().min(1).max(200).optional()
1223
+ }).strict().parse(options);
1224
+ const query = new URLSearchParams();
1225
+ if (input.cursor !== void 0) query.set("cursor", input.cursor);
1226
+ if (input.limit !== void 0) query.set("limit", String(input.limit));
1227
+ const result = await this.call("GET", `/workspaces/${id2.parse(workspaceId)}/api-keys${query.size ? `?${query}` : ""}`, "team:manage", success.extend({
1228
+ keys: z3.array(workspaceKeySchema).max(200),
1229
+ next_cursor: workspaceKeyCursor.nullable()
1230
+ }));
1231
+ const { keys, next_cursor } = result;
1232
+ if (keys.some((key) => key.workspace_id.toLowerCase() !== workspaceId.toLowerCase())) throw new AccountError({
1233
+ code: "INVALID_RESPONSE",
1234
+ message: "Workspace key response belongs to another workspace."
1235
+ });
1236
+ return {
1237
+ keys,
1238
+ next_cursor
1239
+ };
1240
+ }
1241
+ async createKey(workspaceId, input) {
1242
+ const body = workspaceKeyInputSchema.parse(input);
1243
+ const response = await this.call("POST", `/workspaces/${id2.parse(workspaceId)}/api-keys`, "team:manage", success.extend({
1244
+ key: workspaceKeySchema,
1245
+ secret: keySecretSchema
1246
+ }), body);
1247
+ this.assertKeyReceipt(workspaceId, response.key);
1248
+ return {
1249
+ key: response.key,
1250
+ secret: response.secret
1251
+ };
1252
+ }
1253
+ async keyOperation(workspaceId, operationId) {
1254
+ const workspace = id2.parse(workspaceId), operation3 = id2.parse(operationId);
1255
+ const response = await this.call("GET", `/workspaces/${workspace}/api-keys/operations/${operation3}`, "team:manage", z3.discriminatedUnion("state", [
1256
+ z3.object({
1257
+ success: z3.literal(true),
1258
+ state: z3.literal("not-observed"),
1259
+ operation: z3.null()
1260
+ }).strict(),
1261
+ z3.object({
1262
+ success: z3.literal(true),
1263
+ state: z3.literal("committed"),
1264
+ operation: committedKeyOperationSchema
1265
+ }).strict(),
1266
+ z3.object({
1267
+ success: z3.literal(true),
1268
+ state: z3.literal("rejected"),
1269
+ operation: rejectedKeyOperationSchema
1270
+ }).strict(),
1271
+ z3.object({
1272
+ success: z3.literal(true),
1273
+ state: z3.literal("abandoned"),
1274
+ operation: abandonedKeyOperationSchema
1275
+ }).strict()
1276
+ ]));
1277
+ if (response.state === "not-observed") return {
1278
+ state: response.state,
1279
+ operation: null
1280
+ };
1281
+ this.assertOperation(workspace, operation3, response.operation);
1282
+ if (response.state === "abandoned") return {
1283
+ state: response.state,
1284
+ operation: response.operation
1285
+ };
1286
+ return response.state === "rejected" ? {
1287
+ state: response.state,
1288
+ operation: response.operation
1289
+ } : {
1290
+ state: response.state,
1291
+ operation: response.operation
1292
+ };
1293
+ }
1294
+ async mutateKey(workspaceId, operationId, request) {
1295
+ const workspace = id2.parse(workspaceId), operation3 = id2.parse(operationId), input = keyMutationSchema.parse(request);
1296
+ const path = `/workspaces/${workspace}/api-keys${input.action === "create" ? "" : `/${input.keyId}${input.action === "rotate" ? "/rotate" : ""}`}`;
1297
+ const body = {
1298
+ ...input.action === "revoke" ? {} : input.input,
1299
+ operation_id: operation3,
1300
+ ...input.action === "create" ? {} : {
1301
+ expected_revision: input.expectedRevision
1302
+ }
1303
+ };
1304
+ try {
1305
+ const response = await this.call(input.action === "revoke" ? "DELETE" : "POST", path, "team:manage", z3.object({
1306
+ success: z3.literal(true),
1307
+ key: workspaceKeySchema.optional(),
1308
+ operation: workspaceKeyOperationSchema,
1309
+ replayed: z3.boolean(),
1310
+ secret: keySecretSchema.optional()
1311
+ }).strict(), body);
1312
+ this.assertOperation(workspace, operation3, response.operation);
1313
+ if ("rejection" in response.operation || "abandoned" in response.operation) {
1314
+ if (response.key !== void 0 || response.secret !== void 0 || response.operation.action !== input.action || response.operation.previous_key_id?.toLowerCase() !== (input.action === "create" ? void 0 : input.keyId.toLowerCase())) throw new Error("Invalid rejection receipt");
1315
+ return {
1316
+ operation: response.operation,
1317
+ replayed: response.replayed
1318
+ };
1319
+ }
1320
+ if (!response.key) throw new Error("Missing key");
1321
+ if (response.operation.action !== input.action || JSON.stringify(response.key) !== JSON.stringify(response.operation.key) || response.operation.previous_key_id?.toLowerCase() !== (input.action === "create" ? void 0 : input.keyId.toLowerCase()) || (response.replayed || input.action === "revoke" ? response.secret !== void 0 : response.secret === void 0) || response.secret !== void 0 && !response.secret.startsWith(response.key.prefix)) throw new Error("Invalid receipt");
1322
+ if (input.action === "revoke") {
1323
+ if (response.key.id.toLowerCase() !== input.keyId.toLowerCase() || !response.key.revoked_at || response.key.revision !== input.expectedRevision + 1) throw new Error("Invalid revocation");
1324
+ } else {
1325
+ this.assertKeyReceipt(workspace, response.key);
1326
+ if (input.action === "rotate" && response.key.id.toLowerCase() === input.keyId.toLowerCase()) throw new Error("Invalid rotation");
1327
+ }
1328
+ return {
1329
+ operation: response.operation,
1330
+ replayed: response.replayed,
1331
+ ...response.secret === void 0 ? {} : {
1332
+ secret: response.secret
1333
+ }
1334
+ };
1335
+ } catch {
1336
+ throw new WorkspaceKeyMutationError(operation3);
1337
+ }
1338
+ }
1339
+ assertOperation(workspaceId, operationId, operation3) {
1340
+ if (operation3.workspace_id.toLowerCase() !== workspaceId.toLowerCase() || operation3.operation_id.toLowerCase() !== operationId.toLowerCase()) {
1341
+ throw new AccountError({
1342
+ code: "INVALID_RESPONSE",
1343
+ message: "Workspace operation response belongs to another authority."
1344
+ });
1345
+ }
1346
+ if ("rejection" in operation3 || "abandoned" in operation3) return;
1347
+ if (operation3.key.workspace_id.toLowerCase() !== workspaceId.toLowerCase() || operation3.key.created_by_user_id.toLowerCase() !== operation3.actor_user_id.toLowerCase() && operation3.action !== "revoke") throw new AccountError({
1348
+ code: "INVALID_RESPONSE",
1349
+ message: "Foreign key receipt."
1350
+ });
1351
+ if (operation3.action === "revoke" ? !operation3.key.revoked_at || operation3.key.revision < 2 || operation3.previous_key_id !== operation3.key.id : operation3.key.revoked_at !== null || operation3.key.replaced_by !== null || operation3.key.revision !== 1 || (operation3.action === "create" ? operation3.previous_key_id !== null : operation3.previous_key_id === null || operation3.previous_key_id === operation3.key.id)) {
1352
+ throw new AccountError({
1353
+ code: "INVALID_RESPONSE",
1354
+ message: "Invalid committed workspace key operation."
1355
+ });
1356
+ }
1357
+ }
1358
+ async rotateKey(workspaceId, keyId, expectedRevision, input = {}) {
1359
+ const body = {
1360
+ ...workspaceKeyInputSchema.partial().parse(input),
1361
+ expected_revision: z3.number().int().positive().parse(expectedRevision)
1362
+ };
1363
+ const response = await this.call("POST", `/workspaces/${id2.parse(workspaceId)}/api-keys/${id2.parse(keyId)}/rotate`, "team:manage", success.extend({
1364
+ key: workspaceKeySchema,
1365
+ secret: keySecretSchema
1366
+ }), body);
1367
+ this.assertKeyReceipt(workspaceId, response.key);
1368
+ if (response.key.id.toLowerCase() === keyId.toLowerCase()) throw new AccountError({
1369
+ code: "INVALID_RESPONSE",
1370
+ message: "Rotation did not acknowledge a new key identity."
1371
+ });
1372
+ return {
1373
+ key: response.key,
1374
+ secret: response.secret
1375
+ };
1376
+ }
1377
+ async revokeKey(workspaceId, keyId, expectedRevision) {
1378
+ const key = (await this.call("DELETE", `/workspaces/${id2.parse(workspaceId)}/api-keys/${id2.parse(keyId)}`, "team:manage", success.extend({
1379
+ key: workspaceKeySchema
1380
+ }), {
1381
+ expected_revision: z3.number().int().positive().parse(expectedRevision)
1382
+ })).key;
1383
+ if (key.workspace_id.toLowerCase() !== workspaceId.toLowerCase() || key.id.toLowerCase() !== keyId.toLowerCase() || !key.revoked_at || key.revision !== expectedRevision + 1) throw new AccountError({
1384
+ code: "INVALID_RESPONSE",
1385
+ message: "Revocation was not acknowledged for the requested key revision."
1386
+ });
1387
+ return key;
1388
+ }
1389
+ assertKeyReceipt(workspaceId, key) {
1390
+ if (key.workspace_id.toLowerCase() !== workspaceId.toLowerCase() || key.revoked_at || key.replaced_by || key.revision !== 1) throw new AccountError({
1391
+ code: "INVALID_RESPONSE",
1392
+ message: "Invalid workspace key creation receipt."
1393
+ });
1394
+ }
1395
+ async create(name, type = "team") {
1396
+ const body = z3.object({
1397
+ name: z3.string().trim().min(1).max(128),
1398
+ workspace_type: z3.enum([
1399
+ "personal",
1400
+ "team"
1401
+ ])
1402
+ }).parse({
1403
+ name,
1404
+ workspace_type: type
1405
+ });
1406
+ return (await this.call("POST", "/workspaces", "team:manage", success.extend({
1407
+ workspace: workspaceSchema
1408
+ }), body)).workspace;
1409
+ }
1410
+ async accountOperation(operationId) {
1411
+ const operation3 = id2.parse(operationId);
1412
+ const response = await this.call("GET", `/account-operations/${operation3}`, "team:manage", z3.discriminatedUnion("state", [
1413
+ z3.object({
1414
+ success: z3.literal(true),
1415
+ state: z3.literal("not-observed"),
1416
+ operation: z3.null()
1417
+ }).strict(),
1418
+ z3.object({
1419
+ success: z3.literal(true),
1420
+ state: z3.literal("committed"),
1421
+ operation: accountOperationSchema
1422
+ }).strict()
1423
+ ]));
1424
+ if (response.state === "not-observed") return response;
1425
+ if (response.operation.operation_id.toLowerCase() !== operation3.toLowerCase()) throw new AccountError({
1426
+ code: "INVALID_RESPONSE",
1427
+ message: "Account operation response belongs to another operation."
1428
+ });
1429
+ return {
1430
+ state: "committed",
1431
+ operation: response.operation
1432
+ };
1433
+ }
1434
+ async mutateAccount(operationId, request) {
1435
+ const operation3 = id2.parse(operationId), intent = accountOperationIntentSchema.parse(request);
1436
+ const path = intent.action === "workspace.create" ? "/workspaces" : `/workspace-invites/${intent.inviteId}/${intent.action === "invite.accept" ? "accept" : "decline"}`;
1437
+ const body = intent.action === "workspace.create" ? {
1438
+ operation_id: operation3,
1439
+ name: intent.name,
1440
+ workspace_type: intent.type
1441
+ } : {
1442
+ operation_id: operation3
1443
+ };
1444
+ try {
1445
+ const response = await this.call("POST", path, "team:manage", z3.object({
1446
+ success: z3.literal(true),
1447
+ operation: accountOperationSchema,
1448
+ replayed: z3.boolean(),
1449
+ workspace: workspaceSchema.optional()
1450
+ }).strict(), body, operation3);
1451
+ if (response.operation.operation_id.toLowerCase() !== operation3.toLowerCase() || response.operation.action !== intent.action) throw new Error("foreign operation");
1452
+ if (intent.action === "workspace.create" && (!("workspace" in response.operation.result) || JSON.stringify(response.workspace) !== JSON.stringify(response.operation.result.workspace))) throw new Error("foreign workspace");
1453
+ if (intent.action !== "workspace.create" && (!("invite" in response.operation.result) || response.operation.result.invite.id.toLowerCase() !== intent.inviteId.toLowerCase())) throw new Error("foreign invite");
1454
+ return {
1455
+ operation: response.operation,
1456
+ replayed: response.replayed
1457
+ };
1458
+ } catch {
1459
+ throw new AccountMutationError(operation3);
1460
+ }
1461
+ }
1462
+ async select(workspaceId) {
1463
+ await this.call("POST", `/workspaces/${id2.parse(workspaceId)}/select`, "team:read", success);
1464
+ }
1465
+ async members(workspaceId) {
1466
+ return this.call("GET", `/workspaces/${id2.parse(workspaceId)}/members`, "team:read", membersResponse);
1467
+ }
1468
+ async updateMember(workspaceId, memberId, role2) {
1469
+ await this.call("PATCH", `/workspaces/${id2.parse(workspaceId)}/members/${id2.parse(memberId)}`, "team:manage", success, {
1470
+ member_role: workspaceInviteRoleSchema.parse(role2)
1471
+ });
1472
+ }
1473
+ async membershipOperation(workspaceId, operationId) {
1474
+ const ws = id2.parse(workspaceId), op = id2.parse(operationId);
1475
+ const response = await this.call("GET", `/workspaces/${ws}/membership-operations/${op}`, "team:manage", z3.discriminatedUnion("state", [
1476
+ z3.object({
1477
+ success: z3.literal(true),
1478
+ state: z3.literal("not-observed"),
1479
+ operation: z3.null()
1480
+ }).strict(),
1481
+ z3.object({
1482
+ success: z3.literal(true),
1483
+ state: z3.literal("committed"),
1484
+ operation: membershipCommittedSchema,
1485
+ delivery: membershipDeliverySchema.optional()
1486
+ }).strict(),
1487
+ z3.object({
1488
+ success: z3.literal(true),
1489
+ state: z3.literal("rejected"),
1490
+ operation: membershipRejectedSchema
1491
+ }).strict(),
1492
+ z3.object({
1493
+ success: z3.literal(true),
1494
+ state: z3.literal("abandoned"),
1495
+ operation: membershipAbandonedSchema
1496
+ }).strict()
1497
+ ]));
1498
+ if (response.state === "not-observed") return {
1499
+ state: response.state,
1500
+ operation: null
1501
+ };
1502
+ assertMembershipOperation(ws, op, response.operation);
1503
+ if (response.state === "abandoned") return {
1504
+ state: response.state,
1505
+ operation: response.operation
1506
+ };
1507
+ if (response.state === "committed" && response.delivery && (!("delivery" in response.operation.result) || response.operation.result.delivery.id !== response.delivery.id)) throw new AccountError({
1508
+ code: "INVALID_RESPONSE",
1509
+ message: "Foreign invitation delivery state."
1510
+ });
1511
+ return response.state === "committed" ? {
1512
+ state: response.state,
1513
+ operation: response.operation,
1514
+ ...response.delivery ? {
1515
+ delivery: response.delivery
1516
+ } : {}
1517
+ } : {
1518
+ state: response.state,
1519
+ operation: response.operation
1520
+ };
1521
+ }
1522
+ async mutateMembership(workspaceId, operationId, request) {
1523
+ const ws = id2.parse(workspaceId), op = id2.parse(operationId), input = membershipMutationSchema.parse(request);
1524
+ const path = input.action === "invite.create" ? "/invites" : "inviteId" in input ? `/invites/${input.inviteId}${input.action === "invite.resend" ? "/resend" : ""}` : "memberId" in input ? `/members/${input.memberId}` : "/owner-transfer";
1525
+ const method = input.action === "member.role" ? "PATCH" : input.action === "invite.revoke" || input.action === "member.remove" ? "DELETE" : "POST";
1526
+ const body = {
1527
+ operation_id: op,
1528
+ ...input.action === "invite.create" ? {
1529
+ email: input.email,
1530
+ role: input.role
1531
+ } : input.action === "member.role" ? {
1532
+ member_role: input.role
1533
+ } : input.action === "owner.transfer" ? {
1534
+ new_owner_user_id: input.newOwnerId
1535
+ } : {}
1536
+ };
1537
+ try {
1538
+ const response = await this.call(method, `/workspaces/${ws}${path}`, "team:manage", z3.object({
1539
+ success: z3.literal(true),
1540
+ operation: membershipOperationSchema,
1541
+ replayed: z3.boolean()
1542
+ }).strict(), body);
1543
+ assertMembershipOperation(ws, op, response.operation, input);
1544
+ return {
1545
+ operation: response.operation,
1546
+ replayed: response.replayed
1547
+ };
1548
+ } catch {
1549
+ throw new WorkspaceMembershipMutationError(op);
1550
+ }
1551
+ }
1552
+ /** Explicit user-requested settlement only. A lost ACK remains uncertain; never
1553
+ * synthesize abandonment locally or automatically retry with a new ID. */
1554
+ async abandonMembershipOperation(workspaceId, operationId, request) {
1555
+ const ws = id2.parse(workspaceId), op = id2.parse(operationId), input = membershipMutationSchema.parse(request);
1556
+ try {
1557
+ const response = await this.call("POST", `/workspaces/${ws}/membership-operations/${op}/abandon`, "team:manage", z3.object({
1558
+ success: z3.literal(true),
1559
+ operation: membershipOperationSchema,
1560
+ replayed: z3.boolean()
1561
+ }).strict(), {
1562
+ request: input
1563
+ });
1564
+ assertMembershipOperation(ws, op, response.operation, input);
1565
+ return {
1566
+ operation: response.operation,
1567
+ replayed: response.replayed
1568
+ };
1569
+ } catch {
1570
+ throw new WorkspaceMembershipMutationError(op);
1571
+ }
1572
+ }
1573
+ async abandonKeyOperation(workspaceId, operationId, request) {
1574
+ const ws = id2.parse(workspaceId), op = id2.parse(operationId), input = keyMutationSchema.parse(request);
1575
+ const original = {
1576
+ action: input.action,
1577
+ ...input.action === "revoke" ? {} : input.input,
1578
+ ...input.action === "create" ? {} : {
1579
+ id: input.keyId,
1580
+ expected_revision: input.expectedRevision
1581
+ }
1582
+ };
1583
+ try {
1584
+ const response = await this.call("POST", `/workspaces/${ws}/api-keys/operations/${op}/abandon`, "team:manage", z3.object({
1585
+ success: z3.literal(true),
1586
+ operation: workspaceKeyOperationSchema,
1587
+ replayed: z3.boolean()
1588
+ }).strict(), {
1589
+ request: original
1590
+ });
1591
+ this.assertOperation(ws, op, response.operation);
1592
+ if (response.operation.action !== input.action || response.operation.previous_key_id?.toLowerCase() !== (input.action === "create" ? void 0 : input.keyId.toLowerCase())) throw new Error("Wrong key operation intent");
1593
+ return {
1594
+ operation: response.operation,
1595
+ replayed: response.replayed
1596
+ };
1597
+ } catch {
1598
+ throw new WorkspaceKeyMutationError(op);
1599
+ }
1600
+ }
1601
+ async removeMember(workspaceId, memberId) {
1602
+ await this.call("DELETE", `/workspaces/${id2.parse(workspaceId)}/members/${id2.parse(memberId)}`, "team:manage", success);
1603
+ }
1604
+ async transferOwnership(workspaceId, newOwnerUserId) {
1605
+ await this.call("POST", `/workspaces/${id2.parse(workspaceId)}/owner-transfer`, "team:manage", success, {
1606
+ new_owner_user_id: id2.parse(newOwnerUserId)
1607
+ });
1608
+ }
1609
+ async invites(workspaceId) {
1610
+ return (await this.call("GET", `/workspaces/${id2.parse(workspaceId)}/invites`, "team:read", invitesResponse)).invites;
1611
+ }
1612
+ async invite(workspaceId, email, role2 = "member") {
1613
+ const body = {
1614
+ email: z3.string().trim().email().parse(email),
1615
+ role: workspaceInviteRoleSchema.parse(role2)
1616
+ };
1617
+ return (await this.call("POST", `/workspaces/${id2.parse(workspaceId)}/invites`, "team:manage", success.extend({
1618
+ invite: workspaceInviteSchema
1619
+ }), body)).invite;
1620
+ }
1621
+ async revokeInvite(workspaceId, inviteId) {
1622
+ await this.call("DELETE", `/workspaces/${id2.parse(workspaceId)}/invites/${id2.parse(inviteId)}`, "team:manage", success);
1623
+ }
1624
+ async resendInvite(workspaceId, inviteId) {
1625
+ await this.call("POST", `/workspaces/${id2.parse(workspaceId)}/invites/${id2.parse(inviteId)}/resend`, "team:manage", success);
1626
+ }
1627
+ async pendingInvites() {
1628
+ return (await this.call("GET", "/workspace-invites", "team:read", invitesResponse)).invites;
1629
+ }
1630
+ async acceptInvite(inviteId) {
1631
+ await this.call("POST", `/workspace-invites/${id2.parse(inviteId)}/accept`, "team:manage", success);
1632
+ }
1633
+ async declineInvite(inviteId) {
1634
+ await this.call("POST", `/workspace-invites/${id2.parse(inviteId)}/decline`, "team:manage", success);
1635
+ }
1636
+ };
1637
+
1638
+ // src/workforce.ts
1639
+ import { z as z4 } from "zod";
1640
+ var uuid = z4.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i).transform((value) => value.toLowerCase());
1641
+ var timestamp3 = z4.string().datetime({
1642
+ offset: true
1643
+ });
1644
+ var identifier = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:/@+-]{0,127}$/);
1645
+ var hash = z4.string().regex(/^[a-f0-9]{64}$/);
1646
+ var revision = z4.string().max(19).regex(/^[1-9][0-9]*$/).refine((value) => BigInt(value) <= 9223372036854775807n);
1647
+ var text = /* @__PURE__ */ __name((max, empty = false) => z4.string().max(max).refine((value) => !value.includes("\0") && (empty || Boolean(value.trim())) && new TextEncoder().encode(value).length <= max), "text");
1648
+ var unique = /* @__PURE__ */ __name((items, key) => new Set(items.map(key)).size === items.length, "unique");
1649
+ var workforceOwnerSchema = z4.object({
1650
+ type: z4.enum([
1651
+ "user",
1652
+ "workspace"
1653
+ ]),
1654
+ id: uuid
1655
+ }).strict();
1656
+ var skill = z4.object({
1657
+ id: identifier,
1658
+ version: identifier,
1659
+ hash
1660
+ }).strict();
1661
+ var secretReference = z4.object({
1662
+ name: z4.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/),
1663
+ ref: uuid
1664
+ }).strict();
1665
+ var contentShape = {
1666
+ instructions: text(32768, true),
1667
+ skills: z4.array(skill).max(64).refine((items) => unique(items, (item) => item.id)),
1668
+ requestedCapabilities: z4.array(identifier).max(64).refine((items) => unique(items, (item) => item)),
1669
+ secretReferences: z4.array(secretReference).max(32).refine((items) => unique(items, (item) => item.name))
1670
+ };
1671
+ var provenance = z4.object({
1672
+ source: z4.enum([
1673
+ "authored",
1674
+ "imported"
1675
+ ]),
1676
+ sourceVersion: identifier.optional()
1677
+ }).strict();
1678
+ var license = z4.object({
1679
+ identifier
1680
+ }).strict();
1681
+ var workforceDefinitionSchema = z4.object({
1682
+ schemaVersion: z4.literal(1),
1683
+ ...contentShape,
1684
+ secretReferences: contentShape.secretReferences.optional(),
1685
+ provenance: provenance.optional(),
1686
+ license: license.optional()
1687
+ }).strict();
1688
+ var createBase = {
1689
+ operationId: uuid,
1690
+ owner: workforceOwnerSchema,
1691
+ // Equality precondition only: the server authenticates the actor and refuses
1692
+ // a changed account. This field never selects or grants an acting identity.
1693
+ expectedActorAccountId: uuid.optional(),
1694
+ name: text(200).transform((value) => value.trim()),
1695
+ description: text(4096, true).optional()
1696
+ };
1697
+ var workforceCreateResourceSchema = z4.discriminatedUnion("kind", [
1698
+ z4.object({
1699
+ ...createBase,
1700
+ kind: z4.literal("agent"),
1701
+ definition: workforceDefinitionSchema
1702
+ }).strict(),
1703
+ z4.object({
1704
+ ...createBase,
1705
+ kind: z4.literal("team")
1706
+ }).strict()
1707
+ ]);
1708
+ var workforceReadOperationSchema = z4.object({
1709
+ operationId: uuid,
1710
+ owner: workforceOwnerSchema,
1711
+ expectedActorAccountId: uuid.optional()
1712
+ }).strict();
1713
+ var catalogCursor = z4.string().min(1).max(2048).regex(/^[A-Za-z0-9_-]+$/);
1714
+ var workforceListOwnedResourcesSchema = z4.object({
1715
+ owner: workforceOwnerSchema,
1716
+ expectedActorAccountId: uuid,
1717
+ limit: z4.number().int().min(1).max(100).optional(),
1718
+ kind: z4.enum([
1719
+ "agent",
1720
+ "team"
1721
+ ]).optional(),
1722
+ status: z4.enum([
1723
+ "active",
1724
+ "archived"
1725
+ ]).optional(),
1726
+ cursor: catalogCursor.optional()
1727
+ }).strict();
1728
+ var resource = z4.object({
1729
+ id: uuid,
1730
+ kind: z4.enum([
1731
+ "agent",
1732
+ "team"
1733
+ ]),
1734
+ owner: workforceOwnerSchema,
1735
+ createdByUserId: uuid.nullable(),
1736
+ name: text(200),
1737
+ description: text(4096, true),
1738
+ status: z4.enum([
1739
+ "active",
1740
+ "archived"
1741
+ ]),
1742
+ revision,
1743
+ createdAt: timestamp3,
1744
+ updatedAt: timestamp3
1745
+ }).strict();
1746
+ var ownedCatalog = z4.object({
1747
+ success: z4.literal(true),
1748
+ schemaVersion: z4.literal(1),
1749
+ scope: z4.literal("owned"),
1750
+ owner: workforceOwnerSchema,
1751
+ items: z4.array(resource).max(100),
1752
+ nextCursor: catalogCursor.nullable()
1753
+ }).strict();
1754
+ var version = z4.object({
1755
+ resourceId: uuid,
1756
+ version: z4.number().int().positive(),
1757
+ schemaVersion: z4.literal(1),
1758
+ content: z4.object(contentShape).strict(),
1759
+ contentHash: hash,
1760
+ provenance: z4.union([
1761
+ provenance,
1762
+ z4.object({}).strict()
1763
+ ]),
1764
+ license: z4.union([
1765
+ license,
1766
+ z4.object({}).strict()
1767
+ ]),
1768
+ createdByUserId: uuid.nullable(),
1769
+ createdAt: timestamp3
1770
+ }).strict();
1771
+ var operation = z4.object({
1772
+ schemaVersion: z4.literal(1),
1773
+ operationId: uuid,
1774
+ action: z4.literal("agent.resource.create"),
1775
+ state: z4.literal("committed"),
1776
+ owner: workforceOwnerSchema,
1777
+ resourceId: uuid,
1778
+ resourceRevision: revision,
1779
+ agentVersion: z4.number().int().positive().nullable(),
1780
+ committedAt: timestamp3
1781
+ }).strict();
1782
+ var committed = z4.object({
1783
+ success: z4.literal(true),
1784
+ state: z4.literal("committed"),
1785
+ operation,
1786
+ resource: resource.nullable(),
1787
+ version: version.nullable(),
1788
+ replayed: z4.boolean(),
1789
+ resourceAccess: z4.discriminatedUnion("allowed", [
1790
+ z4.object({
1791
+ allowed: z4.literal(true)
1792
+ }).strict(),
1793
+ z4.object({
1794
+ allowed: z4.literal(false),
1795
+ reason: z4.literal("no_access")
1796
+ }).strict()
1797
+ ])
1798
+ }).strict();
1799
+ var notObserved = z4.object({
1800
+ success: z4.literal(true),
1801
+ state: z4.literal("not-observed"),
1802
+ operation: z4.null(),
1803
+ resource: z4.null(),
1804
+ version: z4.null(),
1805
+ replayed: z4.literal(false)
1806
+ }).strict();
1807
+ var WorkforceResourceMutationError = class extends AccountError {
1808
+ static {
1809
+ __name(this, "WorkforceResourceMutationError");
1810
+ }
1811
+ operationId;
1812
+ outcome = "uncertain";
1813
+ reason = "mutation_outcome_unverified";
1814
+ source = "client-observation";
1815
+ owner;
1816
+ constructor(operationId, owner, cause) {
1817
+ super({
1818
+ code: cause instanceof AccountError ? cause.code : "PLATFORM_ERROR",
1819
+ message: "Workforce creation acknowledgement is unverified. Read back the same operation before retrying.",
1820
+ httpStatus: cause instanceof AccountError ? cause.httpStatus : null,
1821
+ retryable: false
1822
+ }), this.operationId = operationId;
1823
+ this.name = "WorkforceResourceMutationError";
1824
+ this.owner = Object.freeze({
1825
+ ...owner
1826
+ });
1827
+ }
1828
+ };
1829
+ var sameOwner = /* @__PURE__ */ __name((left, right) => left.type === right.type && left.id === right.id, "sameOwner");
1830
+ var invalidResponse = /* @__PURE__ */ __name(() => new AccountError({
1831
+ code: "INVALID_RESPONSE",
1832
+ message: "Invalid workforce operation response."
1833
+ }), "invalidResponse");
1834
+ var invalidInput = /* @__PURE__ */ __name(() => new AccountError({
1835
+ code: "BAD_REQUEST",
1836
+ message: "Invalid workforce operation request."
1837
+ }), "invalidInput");
1838
+ function assertData(value, depth = 0, budget = {
1839
+ remaining: 4096
1840
+ }) {
1841
+ if (--budget.remaining < 0 || depth > 8) throw invalidInput();
1842
+ if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number") return;
1843
+ if (!value || typeof value !== "object") throw invalidInput();
1844
+ const array = Array.isArray(value);
1845
+ if (array ? Object.getPrototypeOf(value) !== Array.prototype : ![
1846
+ Object.prototype,
1847
+ null
1848
+ ].includes(Object.getPrototypeOf(value))) throw invalidInput();
1849
+ const keys = Reflect.ownKeys(value);
1850
+ if (keys.length > 4096 || array && keys.length !== value.length + 1) throw invalidInput();
1851
+ for (const key of keys) {
1852
+ if (array && key === "length") continue;
1853
+ if (typeof key !== "string" || array && !/^(0|[1-9][0-9]*)$/.test(key)) throw invalidInput();
1854
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1855
+ if (!descriptor.enumerable || !Object.hasOwn(descriptor, "value")) throw invalidInput();
1856
+ assertData(descriptor.value, depth + 1, budget);
1857
+ }
1858
+ }
1859
+ __name(assertData, "assertData");
1860
+ function parseInput(schema, value) {
1861
+ assertData(value);
1862
+ const parsed = schema.safeParse(value);
1863
+ if (!parsed.success) throw invalidInput();
1864
+ if (new TextEncoder().encode(JSON.stringify(parsed.data)).length > 256 * 1024) throw invalidInput();
1865
+ return parsed.data;
1866
+ }
1867
+ __name(parseInput, "parseInput");
1868
+ var WorkforceClient = class {
1869
+ static {
1870
+ __name(this, "WorkforceClient");
1871
+ }
1872
+ transport;
1873
+ authorize;
1874
+ base;
1875
+ constructor(base2, transport, authorize) {
1876
+ this.transport = transport;
1877
+ this.authorize = authorize;
1878
+ const origin = new URL(base2);
1879
+ if (origin.protocol !== "https:" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/") {
1880
+ throw new AccountError({
1881
+ code: "BAD_REQUEST",
1882
+ message: "Workforce API requires an HTTPS origin."
1883
+ });
1884
+ }
1885
+ this.base = origin.origin;
1886
+ }
1887
+ /** This catalog lists one explicitly owned scope only. It is not an aggregate
1888
+ * of assigned, shared or rented resources and contains no agent definitions. */
1889
+ async listOwnedResources(value) {
1890
+ const input = parseInput(workforceListOwnedResourcesSchema, value);
1891
+ const url = `${this.base}/api/workforce/resources/list`;
1892
+ const raw = await this.transport.request({
1893
+ method: "POST",
1894
+ url,
1895
+ body: input,
1896
+ authorization: /* @__PURE__ */ __name(async () => {
1897
+ const auth = await this.authorize("POST", url, {
1898
+ scopes: [
1899
+ "workforce:read"
1900
+ ],
1901
+ silent: true
1902
+ });
1903
+ if (!auth) throw new AccountError({
1904
+ code: "INVALID_TOKEN",
1905
+ message: "Sign in with workforce read access."
1906
+ });
1907
+ return auth;
1908
+ }, "authorization")
1909
+ });
1910
+ const parsed = ownedCatalog.safeParse(raw);
1911
+ if (!parsed.success) throw invalidResponse();
1912
+ const result = parsed.data;
1913
+ if (!sameOwner(result.owner, input.owner) || result.items.length > (input.limit ?? 50) || !unique(result.items, (item) => item.id) || result.items.some((item) => !sameOwner(item.owner, input.owner) || input.kind !== void 0 && item.kind !== input.kind || item.status !== (input.status ?? "active")) || result.nextCursor !== null && (result.items.length === 0 || result.nextCursor === input.cursor)) throw invalidResponse();
1914
+ return result;
1915
+ }
1916
+ validate(raw, input, creating) {
1917
+ const parsed = (creating ? committed : z4.union([
1918
+ committed,
1919
+ notObserved
1920
+ ])).safeParse(raw);
1921
+ if (!parsed.success) throw invalidResponse();
1922
+ const result = parsed.data;
1923
+ if (result.state === "not-observed") return result;
1924
+ const op = result.operation;
1925
+ if (op.operationId !== input.operationId || !sameOwner(op.owner, input.owner)) throw invalidResponse();
1926
+ if (!result.resourceAccess.allowed) {
1927
+ if (result.resource !== null || result.version !== null) throw invalidResponse();
1928
+ return result;
1929
+ }
1930
+ const r = result.resource, v = result.version;
1931
+ if (!r || r.id !== op.resourceId || !sameOwner(r.owner, input.owner) || BigInt(r.revision) < BigInt(op.resourceRevision)) throw invalidResponse();
1932
+ if (r.kind === "team" ? op.agentVersion !== null || v !== null : op.agentVersion === null || !v || v.resourceId !== r.id || v.version !== op.agentVersion) throw invalidResponse();
1933
+ return result;
1934
+ }
1935
+ async createResource(value) {
1936
+ const input = parseInput(workforceCreateResourceSchema, value);
1937
+ let authorizationCompleted = false;
1938
+ try {
1939
+ const url = `${this.base}/api/workforce/resources`;
1940
+ const raw = await this.transport.request({
1941
+ method: "POST",
1942
+ url,
1943
+ body: input,
1944
+ authorization: /* @__PURE__ */ __name(async () => {
1945
+ const auth = await this.authorize("POST", url, {
1946
+ scopes: [
1947
+ "workforce:manage"
1948
+ ],
1949
+ silent: true
1950
+ });
1951
+ if (!auth) throw new AccountError({
1952
+ code: "INVALID_TOKEN",
1953
+ message: "Sign in with workforce management access."
1954
+ });
1955
+ authorizationCompleted = true;
1956
+ return auth;
1957
+ }, "authorization")
1958
+ });
1959
+ const result = this.validate(raw, input, true);
1960
+ if (result.resource && result.resource.kind !== input.kind) throw invalidResponse();
1961
+ if (input.kind === "agent" !== (result.operation.agentVersion !== null)) throw invalidResponse();
1962
+ return result;
1963
+ } catch (error) {
1964
+ if (!authorizationCompleted) throw error;
1965
+ throw new WorkforceResourceMutationError(input.operationId, input.owner, error);
1966
+ }
1967
+ }
1968
+ async readOperation(value) {
1969
+ const input = parseInput(workforceReadOperationSchema, value);
1970
+ const url = `${this.base}/api/workforce/resource-operations/read`;
1971
+ const raw = await this.transport.request({
1972
+ method: "POST",
1973
+ url,
1974
+ body: input,
1975
+ authorization: /* @__PURE__ */ __name(async () => {
1976
+ const auth = await this.authorize("POST", url, {
1977
+ scopes: [
1978
+ "workforce:read"
1979
+ ],
1980
+ silent: true
1981
+ });
1982
+ if (!auth) throw new AccountError({
1983
+ code: "INVALID_TOKEN",
1984
+ message: "Sign in with workforce read access."
1985
+ });
1986
+ return auth;
1987
+ }, "authorization")
1988
+ });
1989
+ return this.validate(raw, input, false);
1990
+ }
1991
+ };
1992
+
1993
+ // src/notifications.ts
1994
+ import { z as z5 } from "zod";
1995
+ var id3 = z5.string().uuid();
1996
+ var localId = z5.string().regex(/^[a-z0-9_:-]{1,240}$/i);
1997
+ var timestamp4 = z5.string().datetime({
1998
+ offset: true
1999
+ });
2000
+ var revision2 = z5.union([
2001
+ z5.literal("0"),
2002
+ id3
2003
+ ]);
2004
+ var httpsUrl = z5.string().max(2048).url().refine((value) => {
2005
+ const parsed = new URL(value);
2006
+ return parsed.protocol === "https:" && !parsed.username && !parsed.password && !parsed.hash;
2007
+ }, "Notification destinations require credential-free HTTPS URLs");
2008
+ var notificationEventSchema = z5.enum([
2009
+ "agent.finished",
2010
+ "agent.failed",
2011
+ "agent.cancelled"
2012
+ ]);
2013
+ var notificationChannelSchema = z5.enum([
2014
+ "webhook",
2015
+ "slack",
2016
+ "discord"
2017
+ ]);
2018
+ var notificationScopeSchema = z5.object({
2019
+ workspaceId: localId,
2020
+ workspaceCreatedAt: timestamp4.transform((value) => new Date(value).toISOString()),
2021
+ teamId: localId.optional(),
2022
+ agentId: localId.optional()
2023
+ }).strict().refine((scope) => !scope.agentId || !!scope.teamId, "Agent requires owning team");
2024
+ var notificationRuleSchema = z5.object({
2025
+ id: z5.string().regex(/^[a-f0-9]{64}$/).optional(),
2026
+ event: notificationEventSchema,
2027
+ channel: notificationChannelSchema,
2028
+ destinationId: id3,
2029
+ enabled: z5.boolean()
2030
+ }).strict();
2031
+ var deliverySchema = z5.object({
2032
+ id: id3,
2033
+ destination_id: id3,
2034
+ event: notificationEventSchema,
2035
+ state: z5.enum([
2036
+ "queued",
2037
+ "leased",
2038
+ "delivered",
2039
+ "failed",
2040
+ "cancelled"
2041
+ ]),
2042
+ attempt: z5.number().int().nonnegative(),
2043
+ max_attempts: z5.number().int().positive(),
2044
+ status_code: z5.number().int().min(100).max(599).nullable().optional(),
2045
+ error_code: z5.string().max(128).nullable().optional(),
2046
+ created_at: timestamp4,
2047
+ delivered_at: timestamp4.nullable().optional(),
2048
+ next_retry_at: timestamp4.nullable().optional(),
2049
+ cancelled_at: timestamp4.nullable().optional()
2050
+ });
2051
+ var notificationSettingsDestinationSchema = z5.object({
2052
+ id: id3,
2053
+ label: z5.string().min(1).max(253).refine((value) => value === "Unavailable webhook" || /^[a-z0-9.:[\]-]+$/i.test(value)),
2054
+ channel: notificationChannelSchema,
2055
+ ready: z5.boolean(),
2056
+ enabled: z5.boolean(),
2057
+ updated_at: timestamp4
2058
+ }).strict().transform(({ updated_at, ...value }) => ({
2059
+ ...value,
2060
+ updatedAt: updated_at
2061
+ }));
2062
+ var notificationSettingsSchema = z5.object({
2063
+ success: z5.literal(true),
2064
+ channelVersion: z5.literal(2),
2065
+ revision: revision2,
2066
+ rules: z5.array(notificationRuleSchema).max(20),
2067
+ destinations: z5.array(notificationSettingsDestinationSchema),
2068
+ deliveries: z5.array(deliverySchema).max(50),
2069
+ channels: z5.array(z5.object({
2070
+ id: z5.enum([
2071
+ "webhook",
2072
+ "email",
2073
+ "slack",
2074
+ "discord"
2075
+ ]),
2076
+ available: z5.boolean()
2077
+ })),
2078
+ digestFrequencies: z5.tuple([
2079
+ z5.literal("realtime")
2080
+ ])
2081
+ });
2082
+ var eventInputSchema = z5.object({
2083
+ eventId: z5.string().regex(/^[a-f0-9]{64}$/),
2084
+ event: notificationEventSchema,
2085
+ occurredAt: timestamp4.transform((value) => new Date(value).toISOString()),
2086
+ scope: notificationScopeSchema,
2087
+ conversationId: localId,
2088
+ requestId: localId
2089
+ }).strict();
2090
+ var notificationDestinationActionSchema = z5.discriminatedUnion("action", [
2091
+ z5.object({
2092
+ action: z5.literal("create"),
2093
+ url: httpsUrl
2094
+ }).strict(),
2095
+ z5.object({
2096
+ action: z5.literal("update"),
2097
+ destination_id: id3,
2098
+ expected_updated_at: timestamp4,
2099
+ url: httpsUrl.optional(),
2100
+ enabled: z5.boolean().optional()
2101
+ }).strict().refine((value) => value.url !== void 0 || value.enabled !== void 0, "An update requires a changed field"),
2102
+ z5.object({
2103
+ action: z5.literal("delete"),
2104
+ destination_id: id3,
2105
+ expected_updated_at: timestamp4
2106
+ }).strict(),
2107
+ z5.object({
2108
+ action: z5.literal("delivery-control"),
2109
+ destination_id: id3,
2110
+ delivery_id: id3,
2111
+ operation: z5.enum([
2112
+ "retry",
2113
+ "cancel"
2114
+ ])
2115
+ }).strict()
2116
+ ]);
2117
+ var notificationDestinationSchema = z5.object({
2118
+ id: id3,
2119
+ label: z5.string().min(1).max(253),
2120
+ channel: z5.literal("webhook"),
2121
+ ready: z5.boolean(),
2122
+ enabled: z5.boolean(),
2123
+ updated_at: timestamp4
2124
+ }).strict();
2125
+ var notificationDeliveryOperationResultSchema = z5.object({
2126
+ id: id3,
2127
+ state: z5.string().min(1).max(64),
2128
+ attempt: z5.number().int().nonnegative(),
2129
+ max_attempts: z5.number().int().positive()
2130
+ }).strict();
2131
+ var notificationDestinationOperationSchema = z5.object({
2132
+ operation_id: id3,
2133
+ workspace_id: id3,
2134
+ actor_user_id: id3,
2135
+ client_id: z5.string().min(1).max(128),
2136
+ action: z5.enum([
2137
+ "create",
2138
+ "update",
2139
+ "delete",
2140
+ "delivery-control"
2141
+ ]),
2142
+ state: z5.enum([
2143
+ "prepared",
2144
+ "committed",
2145
+ "rejected"
2146
+ ]),
2147
+ prepared_at: timestamp4,
2148
+ committed_at: timestamp4.optional(),
2149
+ destination: notificationDestinationSchema.optional(),
2150
+ delivery: notificationDeliveryOperationResultSchema.optional(),
2151
+ rejection: z5.enum([
2152
+ "notification_destination_not_found",
2153
+ "notification_destination_generation_conflict",
2154
+ "notification_delivery_transition_unavailable"
2155
+ ]).optional()
2156
+ }).strict().superRefine((value, context) => {
2157
+ if (value.state === "rejected" && !value.rejection) context.addIssue({
2158
+ code: "custom",
2159
+ message: "Rejected operation requires a rejection."
2160
+ });
2161
+ if (value.state === "committed" && !value.committed_at) context.addIssue({
2162
+ code: "custom",
2163
+ message: "Committed operation requires a timestamp."
2164
+ });
2165
+ });
2166
+ var destinationOperationMutationResponseSchema = z5.object({
2167
+ state: z5.enum([
2168
+ "prepared",
2169
+ "committed",
2170
+ "rejected"
2171
+ ]),
2172
+ operation: notificationDestinationOperationSchema,
2173
+ replayed: z5.boolean()
2174
+ }).strict();
2175
+ var destinationOperationLookupResponseSchema = z5.union([
2176
+ z5.object({
2177
+ state: z5.literal("not-observed"),
2178
+ operation: z5.null()
2179
+ }).strict(),
2180
+ z5.object({
2181
+ state: z5.enum([
2182
+ "prepared",
2183
+ "committed",
2184
+ "rejected"
2185
+ ]),
2186
+ operation: notificationDestinationOperationSchema
2187
+ }).strict()
2188
+ ]);
2189
+ var destinationOperationExecuteResponseSchema = destinationOperationMutationResponseSchema.extend({
2190
+ secret: z5.string().regex(/^[a-f0-9]{64}$/).optional()
2191
+ }).strict();
2192
+ var NotificationsClient = class {
2193
+ static {
2194
+ __name(this, "NotificationsClient");
2195
+ }
2196
+ transport;
2197
+ authorize;
2198
+ origin;
2199
+ constructor(origin, transport, authorize) {
2200
+ this.transport = transport;
2201
+ this.authorize = authorize;
2202
+ const url = new URL(origin);
2203
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.pathname !== "/") throw new AccountError({
2204
+ code: "BAD_REQUEST",
2205
+ message: "Notifications API requires an HTTPS origin."
2206
+ });
2207
+ this.origin = url.origin;
2208
+ }
2209
+ async call(workspaceId, method, suffix, schema, body) {
2210
+ const url = `${this.origin}/api/workspaces/${id3.parse(workspaceId)}/notifications${suffix}`;
2211
+ const response = await this.transport.request({
2212
+ method,
2213
+ url,
2214
+ ...body === void 0 ? {} : {
2215
+ body
2216
+ },
2217
+ authorization: /* @__PURE__ */ __name(async () => {
2218
+ const value = await this.authorize(method, url, {
2219
+ scopes: [
2220
+ method === "GET" ? "team:read" : "team:manage"
2221
+ ],
2222
+ silent: true
2223
+ });
2224
+ if (!value) throw new AccountError({
2225
+ code: "INVALID_TOKEN",
2226
+ message: "Sign in to manage notifications."
2227
+ });
2228
+ return value;
2229
+ }, "authorization")
2230
+ });
2231
+ const parsed = schema.safeParse(response);
2232
+ if (!parsed.success) throw new AccountError({
2233
+ code: "INVALID_RESPONSE",
2234
+ message: "Invalid notification response."
2235
+ });
2236
+ return parsed.data;
2237
+ }
2238
+ read(workspaceId, scope) {
2239
+ return this.call(workspaceId, "GET", `/v2?scope=${encodeURIComponent(JSON.stringify(notificationScopeSchema.parse(scope)))}`, notificationSettingsSchema);
2240
+ }
2241
+ save(workspaceId, input) {
2242
+ const body = z5.object({
2243
+ scope: notificationScopeSchema,
2244
+ expectedRevision: revision2,
2245
+ rules: z5.array(notificationRuleSchema).max(20)
2246
+ }).strict().parse(input);
2247
+ return this.call(workspaceId, "POST", "/v2/settings", notificationSettingsSchema, body);
2248
+ }
2249
+ emit(workspaceId, input) {
2250
+ return this.call(workspaceId, "POST", "/events", z5.object({
2251
+ success: z5.literal(true),
2252
+ admitted: z5.literal(true),
2253
+ duplicate: z5.boolean()
2254
+ }), eventInputSchema.parse(input));
2255
+ }
2256
+ async prepareDestinationOperation(workspaceId, operationId, action) {
2257
+ const workspace = id3.parse(workspaceId), operation3 = id3.parse(operationId), request = notificationDestinationActionSchema.parse(action);
2258
+ const result = await this.call(workspace, "PUT", `/destination-operations/${operation3}`, destinationOperationMutationResponseSchema, request);
2259
+ if (result.operation.operation_id !== operation3 || result.operation.workspace_id !== workspace || result.operation.action !== request.action || result.operation.state !== result.state) throw new AccountError({
2260
+ code: "INVALID_RESPONSE",
2261
+ message: "Mismatched notification operation receipt."
2262
+ });
2263
+ return result;
2264
+ }
2265
+ async lookupDestinationOperation(workspaceId, operationId) {
2266
+ const workspace = id3.parse(workspaceId), operation3 = id3.parse(operationId);
2267
+ const result = await this.call(workspace, "GET", `/destination-operations/${operation3}`, destinationOperationLookupResponseSchema);
2268
+ if (result.operation && (result.operation.operation_id !== operation3 || result.operation.workspace_id !== workspace || result.operation.state !== result.state)) throw new AccountError({
2269
+ code: "INVALID_RESPONSE",
2270
+ message: "Mismatched notification operation receipt."
2271
+ });
2272
+ return result;
2273
+ }
2274
+ async executeDestinationOperation(workspaceId, operationId) {
2275
+ const workspace = id3.parse(workspaceId), operation3 = id3.parse(operationId);
2276
+ const result = await this.call(workspace, "POST", `/destination-operations/${operation3}`, destinationOperationExecuteResponseSchema);
2277
+ if (result.operation.operation_id !== operation3 || result.operation.workspace_id !== workspace || result.operation.state !== result.state || result.secret !== void 0 && (result.operation.action !== "create" || result.state !== "committed" || result.replayed)) throw new AccountError({
2278
+ code: "INVALID_RESPONSE",
2279
+ message: "Mismatched notification operation receipt."
2280
+ });
2281
+ return result;
2282
+ }
2283
+ };
2284
+
2285
+ // src/integrations.ts
2286
+ import { z as z6 } from "zod";
2287
+ var id4 = z6.string().uuid();
2288
+ var provider = z6.enum([
2289
+ "google",
2290
+ "github",
2291
+ "twitter"
2292
+ ]);
2293
+ var linked = z6.object({
2294
+ provider,
2295
+ email: z6.string().email().nullable(),
2296
+ username: z6.string().nullable(),
2297
+ created_at: z6.string().datetime({
2298
+ offset: true
2299
+ }).optional()
2300
+ }).passthrough();
2301
+ var integration = z6.object({
2302
+ provider,
2303
+ available: z6.boolean(),
2304
+ scopes: z6.array(z6.string().min(1)).max(16),
2305
+ linked: linked.nullable()
2306
+ }).strict();
2307
+ var operation2 = z6.object({
2308
+ operationId: id4,
2309
+ actorAccountId: id4.optional(),
2310
+ clientId: z6.string().optional(),
2311
+ provider: provider.optional(),
2312
+ scopes: z6.array(z6.string()).optional(),
2313
+ state: z6.enum([
2314
+ "not-observed",
2315
+ "waiting",
2316
+ "exchanging",
2317
+ "committed",
2318
+ "rejected",
2319
+ "cancelled"
2320
+ ]),
2321
+ authorizationUrl: z6.string().url().optional(),
2322
+ expiresAt: z6.string().datetime({
2323
+ offset: true
2324
+ }).optional(),
2325
+ linked: linked.optional(),
2326
+ rejection: z6.string().optional(),
2327
+ replayed: z6.boolean().optional()
2328
+ }).strict();
2329
+ var AccountIntegrationClient = class {
2330
+ static {
2331
+ __name(this, "AccountIntegrationClient");
2332
+ }
2333
+ transport;
2334
+ authorize;
2335
+ base;
2336
+ constructor(base2, transport, authorize) {
2337
+ this.transport = transport;
2338
+ this.authorize = authorize;
2339
+ this.base = new URL(base2).origin;
2340
+ }
2341
+ async call(method, path, schema, body, idempotencyKey) {
2342
+ const url = `${this.base}/api/account-integrations${path}`, raw = await this.transport.request({
2343
+ method,
2344
+ url,
2345
+ ...body === void 0 ? {} : {
2346
+ body
2347
+ },
2348
+ ...idempotencyKey ? {
2349
+ idempotencyKey
2350
+ } : {},
2351
+ authorization: /* @__PURE__ */ __name(async () => {
2352
+ const value = await this.authorize(method, url, {
2353
+ scopes: [
2354
+ "openid"
2355
+ ],
2356
+ silent: true
2357
+ });
2358
+ if (!value) throw new AccountError({
2359
+ code: "INVALID_TOKEN",
2360
+ message: "Sign in to manage account integrations."
2361
+ });
2362
+ return value;
2363
+ }, "authorization")
2364
+ });
2365
+ const parsed = schema.safeParse(raw);
2366
+ if (!parsed.success) throw new AccountError({
2367
+ code: "INVALID_RESPONSE",
2368
+ message: "Invalid account integration response."
2369
+ });
2370
+ return parsed.data;
2371
+ }
2372
+ async list() {
2373
+ return (await this.call("GET", "", z6.object({
2374
+ success: z6.literal(true),
2375
+ providers: z6.array(integration)
2376
+ }).strict())).providers;
2377
+ }
2378
+ async operation(operationId) {
2379
+ return (await this.call("GET", `/operations/${id4.parse(operationId)}`, z6.object({
2380
+ success: z6.literal(true),
2381
+ operation: operation2
2382
+ }).strict())).operation;
2383
+ }
2384
+ async start(operationId, value) {
2385
+ const operationIdValue = id4.parse(operationId), result = (await this.call("POST", `/${provider.parse(value)}/operations/${operationIdValue}/start`, z6.object({
2386
+ success: z6.literal(true),
2387
+ operation: operation2
2388
+ }).strict(), {}, operationIdValue)).operation;
2389
+ if (result.operationId !== operationIdValue || result.provider !== value || result.state !== "waiting" || !result.authorizationUrl) throw new AccountError({
2390
+ code: "INVALID_RESPONSE",
2391
+ message: "Invalid provider authorization operation."
2392
+ });
2393
+ const url = new URL(result.authorizationUrl);
2394
+ if (url.protocol !== "https:" || url.username || url.password) throw new AccountError({
2395
+ code: "INVALID_RESPONSE",
2396
+ message: "Untrusted provider authorization URL."
2397
+ });
2398
+ return result;
2399
+ }
2400
+ async cancel(operationId) {
2401
+ return (await this.call("POST", `/operations/${id4.parse(operationId)}/cancel`, z6.object({
2402
+ success: z6.literal(true),
2403
+ operation: operation2
2404
+ }).strict(), {})).operation;
2405
+ }
2406
+ };
2407
+
2408
+ // src/verification.ts
2409
+ var jwksCache = /* @__PURE__ */ new Map();
2410
+ function bytes(value) {
2411
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
2412
+ const bin = atob(normalized + "=".repeat((4 - normalized.length % 4) % 4));
2413
+ return Uint8Array.from(bin, (char) => char.charCodeAt(0));
2414
+ }
2415
+ __name(bytes, "bytes");
2416
+ function decode(token) {
2417
+ const parts = token.split(".");
2418
+ if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) throw invalid("malformed JWT");
2419
+ try {
2420
+ return {
2421
+ header: JSON.parse(new TextDecoder().decode(bytes(parts[0]))),
2422
+ payload: JSON.parse(new TextDecoder().decode(bytes(parts[1]))),
2423
+ signingInput: new TextEncoder().encode(`${parts[0]}.${parts[1]}`),
2424
+ signature: bytes(parts[2])
2425
+ };
2426
+ } catch {
2427
+ throw invalid("malformed JWT");
2428
+ }
2429
+ }
2430
+ __name(decode, "decode");
2431
+ function invalid(message) {
2432
+ return new AccountError({
2433
+ code: "INVALID_RESPONSE",
2434
+ message: `OIDC verification failed: ${message}`
2435
+ });
2436
+ }
2437
+ __name(invalid, "invalid");
2438
+ function audience(value, expected) {
2439
+ return value === expected || Array.isArray(value) && value.includes(expected);
2440
+ }
2441
+ __name(audience, "audience");
2442
+ async function fetchJwks(transport, issuer, jwksUrl, force = false) {
2443
+ const url = jwksUrl ?? `${issuer.replace(/\/+$/, "")}/api/oauth2/jwks`;
2444
+ const cached = jwksCache.get(url);
2445
+ if (!force && cached && cached.expiresAt > Date.now()) return cached.keys;
2446
+ const response = await transport.request({
2447
+ method: "GET",
2448
+ url
2449
+ });
2450
+ if (!Array.isArray(response.keys) || response.keys.length === 0) throw invalid("empty JWKS");
2451
+ jwksCache.set(url, {
2452
+ keys: response.keys,
2453
+ expiresAt: Date.now() + 5 * 6e4
2454
+ });
2455
+ return response.keys;
2456
+ }
2457
+ __name(fetchJwks, "fetchJwks");
2458
+ async function verifySignature(decoded, keys) {
2459
+ if (decoded.header.alg !== "ES256" || typeof decoded.header.kid !== "string") return "invalid";
2460
+ const jwk = keys.find((candidate) => candidate.kid === decoded.header.kid && candidate.kty === "EC" && candidate.crv === "P-256");
2461
+ if (!jwk) return "unknown-kid";
2462
+ try {
2463
+ const key = await globalThis.crypto.subtle.importKey("jwk", jwk, {
2464
+ name: "ECDSA",
2465
+ namedCurve: "P-256"
2466
+ }, false, [
2467
+ "verify"
2468
+ ]);
2469
+ return await globalThis.crypto.subtle.verify({
2470
+ name: "ECDSA",
2471
+ hash: "SHA-256"
2472
+ }, key, decoded.signature, decoded.signingInput) ? "valid" : "invalid";
2473
+ } catch {
2474
+ return "invalid";
2475
+ }
2476
+ }
2477
+ __name(verifySignature, "verifySignature");
2478
+ async function verifiedPayload(token, transport, issuer, jwksUrl) {
2479
+ const decoded = decode(token);
2480
+ let keys = await fetchJwks(transport, issuer, jwksUrl);
2481
+ let result = await verifySignature(decoded, keys);
2482
+ if (result === "unknown-kid") {
2483
+ keys = await fetchJwks(transport, issuer, jwksUrl, true);
2484
+ result = await verifySignature(decoded, keys);
2485
+ }
2486
+ if (result !== "valid") throw invalid("signature or algorithm");
2487
+ return decoded;
2488
+ }
2489
+ __name(verifiedPayload, "verifiedPayload");
2490
+ function temporal(payload, now) {
2491
+ if (!Number.isInteger(payload.exp) || Number(payload.exp) <= now) throw invalid("token expired");
2492
+ if (!Number.isInteger(payload.iat) || Number(payload.iat) > now + 60) throw invalid("invalid issued-at time");
2493
+ if (payload.nbf !== void 0 && (!Number.isInteger(payload.nbf) || Number(payload.nbf) > now + 60)) throw invalid("token not yet valid");
2494
+ }
2495
+ __name(temporal, "temporal");
2496
+ var XENO_ISSUER_PAIR = [
2497
+ "https://xenostudio.ai",
2498
+ "https://xenosystem.ai"
2499
+ ];
2500
+ function issuerAccepted(iss, configured) {
2501
+ if (typeof iss !== "string") return false;
2502
+ const want = configured.replace(/\/+$/, "");
2503
+ if (iss === configured || iss === want) return true;
2504
+ return XENO_ISSUER_PAIR.includes(want) && XENO_ISSUER_PAIR.includes(iss);
2505
+ }
2506
+ __name(issuerAccepted, "issuerAccepted");
2507
+ async function verifyAccessToken(args) {
2508
+ const decoded = await verifiedPayload(args.token, args.transport, args.issuer, args.jwksUrl);
2509
+ const p = decoded.payload;
2510
+ const now = Math.floor(Date.now() / 1e3);
2511
+ temporal(p, now);
2512
+ if (decoded.header.typ !== "at+jwt" || p.typ !== "at+jwt" || !issuerAccepted(p.iss, args.issuer) || !audience(p.aud, "xeno-api")) throw invalid("access-token profile");
2513
+ if (p.client_id !== args.clientId || p.azp !== args.clientId) throw invalid("client binding");
2514
+ if (typeof p.sub !== "string" || typeof p.sid !== "string" || !Number.isInteger(p.auth_epoch)) throw invalid("session claims");
2515
+ if (!p.cnf || typeof p.cnf !== "object" || p.cnf.jkt !== args.dpopJkt) throw invalid("DPoP binding");
2516
+ if (p.act !== void 0) {
2517
+ const act = p.act;
2518
+ if (act.client_id !== "xeno-hub" || typeof act.installation_id_hash !== "string" || !act.installation_id_hash) throw invalid("broker actor");
2519
+ }
2520
+ if (args.requireBrokerActor && p.act === void 0) throw invalid("missing broker actor");
2521
+ const held = new Set(String(p.scope ?? "").split(/\s+/).filter(Boolean));
2522
+ for (const scope of args.expectedScopes ?? []) if (!held.has(scope)) throw invalid(`missing scope ${scope}`);
2523
+ return p;
2524
+ }
2525
+ __name(verifyAccessToken, "verifyAccessToken");
2526
+ async function verifyIdToken(args) {
2527
+ const decoded = await verifiedPayload(args.token, args.transport, args.issuer, args.jwksUrl);
2528
+ const p = decoded.payload;
2529
+ temporal(p, Math.floor(Date.now() / 1e3));
2530
+ if (!issuerAccepted(p.iss, args.issuer) || !audience(p.aud, args.clientId) || typeof p.sub !== "string" || typeof p.sid !== "string" || !Number.isInteger(p.auth_time)) throw invalid("ID-token profile");
2531
+ if (args.expectedNonce !== void 0 && p.nonce !== args.expectedNonce) throw invalid("nonce mismatch");
2532
+ if (args.expectedSubject !== void 0 && p.sub !== args.expectedSubject) throw invalid("subject mismatch");
2533
+ return p;
2534
+ }
2535
+ __name(verifyIdToken, "verifyIdToken");
2536
+ async function verifyLogoutToken(args) {
2537
+ const decoded = await verifiedPayload(args.token, args.transport, args.issuer, args.jwksUrl);
2538
+ const p = decoded.payload;
2539
+ temporal(p, Math.floor(Date.now() / 1e3));
2540
+ const event = "http://schemas.openid.net/event/backchannel-logout";
2541
+ if (decoded.header.typ !== "logout+jwt" || !issuerAccepted(p.iss, args.issuer) || !audience(p.aud, args.clientId)) throw invalid("logout-token profile");
2542
+ if (typeof p.jti !== "string" || !p.jti || p.nonce !== void 0) throw invalid("logout-token claims");
2543
+ if (typeof p.sid !== "string" && typeof p.sub !== "string") throw invalid("logout subject");
2544
+ if (!p.events || typeof p.events !== "object" || !(event in p.events)) throw invalid("logout event");
2545
+ return p;
2546
+ }
2547
+ __name(verifyLogoutToken, "verifyLogoutToken");
2548
+
2549
+ // src/oidc.ts
2550
+ async function generatePkce() {
2551
+ const verifierBytes = new Uint8Array(32);
2552
+ globalThis.crypto.getRandomValues(verifierBytes);
2553
+ const verifier = base64url(verifierBytes);
2554
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
2555
+ return {
2556
+ verifier,
2557
+ challenge: base64url(new Uint8Array(digest))
2558
+ };
2559
+ }
2560
+ __name(generatePkce, "generatePkce");
2561
+ function generateState() {
2562
+ const b = new Uint8Array(24);
2563
+ globalThis.crypto.getRandomValues(b);
2564
+ return base64url(b);
2565
+ }
2566
+ __name(generateState, "generateState");
2567
+ function base64url(bytes2) {
2568
+ let bin = "";
2569
+ for (let i = 0; i < bytes2.length; i += 1) bin += String.fromCharCode(bytes2[i]);
2570
+ const b64 = typeof btoa === "function" ? btoa(bin) : Buffer.from(bytes2).toString("base64");
2571
+ return b64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
2572
+ }
2573
+ __name(base64url, "base64url");
2574
+ function endpoints(cfg) {
2575
+ const base2 = cfg.issuer.replace(/\/+$/, "");
2576
+ return {
2577
+ authorize: cfg.authorizeUrl ?? `${base2}/api/oauth2/authorize`,
2578
+ token: cfg.tokenUrl ?? `${base2}/api/oauth2/token`,
2579
+ device: cfg.deviceAuthorizationUrl ?? `${base2}/api/oauth2/device_authorization`
2580
+ };
2581
+ }
2582
+ __name(endpoints, "endpoints");
2583
+ var DEFAULT_SCOPES = [
2584
+ "openid",
2585
+ "profile",
2586
+ "email",
2587
+ "ledger"
2588
+ ];
2589
+ function buildAuthorizeUrl(cfg, args) {
2590
+ const redirectUri = args.redirectUri ?? cfg.redirectUri;
2591
+ if (!redirectUri) {
2592
+ throw new AccountError({
2593
+ code: "BAD_REQUEST",
2594
+ message: "redirectUri required for authorize"
2595
+ });
2596
+ }
2597
+ const url = new URL(endpoints(cfg).authorize);
2598
+ url.searchParams.set("response_type", "code");
2599
+ url.searchParams.set("client_id", cfg.clientId);
2600
+ url.searchParams.set("redirect_uri", redirectUri);
2601
+ url.searchParams.set("scope", (args.scopes ?? cfg.scopes ?? DEFAULT_SCOPES).join(" "));
2602
+ url.searchParams.set("state", args.state);
2603
+ url.searchParams.set("code_challenge", args.codeChallenge);
2604
+ url.searchParams.set("code_challenge_method", "S256");
2605
+ if (args.nonce) url.searchParams.set("nonce", args.nonce);
2606
+ if (args.prompt) url.searchParams.set("prompt", args.prompt);
2607
+ if (args.maxAge !== void 0) url.searchParams.set("max_age", String(args.maxAge));
2608
+ if (args.acrValues) url.searchParams.set("acr_values", args.acrValues);
2609
+ return url.toString();
2610
+ }
2611
+ __name(buildAuthorizeUrl, "buildAuthorizeUrl");
2612
+ async function exchangeCode(cfg, transport, args) {
2613
+ const redirectUri = args.redirectUri ?? cfg.redirectUri;
2614
+ if (!redirectUri) {
2615
+ throw new AccountError({
2616
+ code: "BAD_REQUEST",
2617
+ message: "redirectUri required for code exchange"
2618
+ });
2619
+ }
2620
+ const body = new URLSearchParams({
2621
+ grant_type: "authorization_code",
2622
+ code: args.code,
2623
+ redirect_uri: redirectUri,
2624
+ client_id: cfg.clientId,
2625
+ code_verifier: args.codeVerifier
2626
+ });
2627
+ if (cfg.clientSecret) body.set("client_secret", cfg.clientSecret);
2628
+ return postToken(cfg, transport, body, {
2629
+ requireIdToken: true,
2630
+ expectedNonce: args.expectedNonce,
2631
+ expectedScopes: args.expectedScopes,
2632
+ signal: args.signal
2633
+ });
2634
+ }
2635
+ __name(exchangeCode, "exchangeCode");
2636
+ async function refreshTokens(cfg, transport, refreshToken, rotationId) {
2637
+ const body = new URLSearchParams({
2638
+ grant_type: "refresh_token",
2639
+ refresh_token: refreshToken,
2640
+ client_id: cfg.clientId
2641
+ });
2642
+ if (cfg.clientSecret) body.set("client_secret", cfg.clientSecret);
2643
+ if (rotationId) body.set("rotation_id", rotationId);
2644
+ return postToken(cfg, transport, body);
2645
+ }
2646
+ __name(refreshTokens, "refreshTokens");
2647
+ async function startDeviceAuthorization(cfg, transport, scopes) {
2648
+ const body = new URLSearchParams({
2649
+ client_id: cfg.clientId,
2650
+ scope: (scopes ?? cfg.scopes ?? DEFAULT_SCOPES).join(" ")
2651
+ });
2652
+ const raw = await transport.request({
2653
+ method: "POST",
2654
+ url: endpoints(cfg).device,
2655
+ headers: {
2656
+ "content-type": "application/x-www-form-urlencoded"
2657
+ },
2658
+ body: body.toString()
2659
+ });
2660
+ const expiresIn = Number(raw["expires_in"] ?? 600);
2661
+ return {
2662
+ deviceCode: String(raw["device_code"] ?? ""),
2663
+ userCode: String(raw["user_code"] ?? ""),
2664
+ verificationUri: String(raw["verification_uri"] ?? ""),
2665
+ verificationUriComplete: typeof raw["verification_uri_complete"] === "string" ? raw["verification_uri_complete"] : null,
2666
+ expiresAt: new Date(Date.now() + expiresIn * 1e3),
2667
+ intervalSeconds: Number(raw["interval"] ?? 5)
2668
+ };
2669
+ }
2670
+ __name(startDeviceAuthorization, "startDeviceAuthorization");
2671
+ async function pollDeviceToken(cfg, transport, device, opts = {}) {
2672
+ const sleep2 = opts.sleep ?? ((ms) => new Promise((resolve) => {
2673
+ const signal = opts.signal;
2674
+ const timer = setTimeout(done, ms);
2675
+ function done() {
2676
+ clearTimeout(timer);
2677
+ signal?.removeEventListener("abort", done);
2678
+ resolve();
2679
+ }
2680
+ __name(done, "done");
2681
+ signal?.addEventListener("abort", done, {
2682
+ once: true
2683
+ });
2684
+ if (signal?.aborted) done();
2685
+ }));
2686
+ let intervalMs = device.intervalSeconds * 1e3;
2687
+ while (Date.now() < device.expiresAt.getTime()) {
2688
+ if (opts.signal?.aborted) {
2689
+ throw new AccountError({
2690
+ code: "BAD_REQUEST",
2691
+ message: "device authorization aborted"
2692
+ });
2693
+ }
2694
+ await sleep2(intervalMs);
2695
+ if (opts.signal?.aborted) {
2696
+ throw new AccountError({
2697
+ code: "BAD_REQUEST",
2698
+ message: "device authorization aborted"
2699
+ });
2700
+ }
2701
+ if (Date.now() >= device.expiresAt.getTime()) break;
2702
+ const body = new URLSearchParams({
2703
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
2704
+ device_code: device.deviceCode,
2705
+ client_id: cfg.clientId
2706
+ });
2707
+ try {
2708
+ const tokens = await postToken(cfg, transport, body, {
2709
+ requireIdToken: true,
2710
+ signal: opts.signal
2711
+ });
2712
+ if (opts.signal?.aborted) throw new AccountError({
2713
+ code: "BAD_REQUEST",
2714
+ message: "device authorization aborted"
2715
+ });
2716
+ return tokens;
2717
+ } catch (err) {
2718
+ if (!(err instanceof AccountError)) throw err;
2719
+ const oauthErr = err.oauthError;
2720
+ if (err.httpStatus === 400 && oauthErr === "authorization_pending") continue;
2721
+ if (err.httpStatus === 400 && oauthErr === "slow_down") {
2722
+ intervalMs += 5e3;
2723
+ continue;
2724
+ }
2725
+ throw err;
2726
+ }
2727
+ }
2728
+ throw new AccountError({
2729
+ code: "BAD_REQUEST",
2730
+ message: "device code expired before approval"
2731
+ });
2732
+ }
2733
+ __name(pollDeviceToken, "pollDeviceToken");
2734
+ async function postToken(cfg, transport, body, verify = {}) {
2735
+ const tokenUrl = endpoints(cfg).token;
2736
+ const dpop = await cfg.dpopSigner.createProof({
2737
+ method: "POST",
2738
+ url: tokenUrl
2739
+ });
2740
+ if (verify.signal?.aborted) throw new AccountError({
2741
+ code: "BAD_REQUEST",
2742
+ message: "Account sign-in was cancelled",
2743
+ retryable: false
2744
+ });
2745
+ const raw = await transport.request({
2746
+ method: "POST",
2747
+ url: tokenUrl,
2748
+ headers: {
2749
+ "content-type": "application/x-www-form-urlencoded",
2750
+ dpop
2751
+ },
2752
+ body: body.toString(),
2753
+ oauthErrorResponse: true,
2754
+ signal: verify.signal
2755
+ });
2756
+ const parsed = oauthTokenResponseSchema.safeParse(raw);
2757
+ if (!parsed.success) {
2758
+ throw new AccountError({
2759
+ code: "INVALID_RESPONSE",
2760
+ message: "token endpoint returned an unrecognised shape"
2761
+ });
2762
+ }
2763
+ const t = parsed.data;
2764
+ if (t.token_type.toLowerCase() !== "dpop") throw new AccountError({
2765
+ code: "INVALID_RESPONSE",
2766
+ message: "token endpoint did not issue a DPoP token"
2767
+ });
2768
+ if (verify.requireIdToken && !t.id_token) throw new AccountError({
2769
+ code: "INVALID_RESPONSE",
2770
+ message: "token endpoint omitted id_token"
2771
+ });
2772
+ const accessClaims = await verifyAccessToken({
2773
+ token: t.access_token,
2774
+ transport,
2775
+ issuer: cfg.issuer,
2776
+ clientId: cfg.clientId,
2777
+ dpopJkt: cfg.dpopSigner.jkt,
2778
+ jwksUrl: cfg.jwksUrl,
2779
+ expectedScopes: verify.expectedScopes
2780
+ });
2781
+ const idClaims = t.id_token ? await verifyIdToken({
2782
+ token: t.id_token,
2783
+ transport,
2784
+ issuer: cfg.issuer,
2785
+ clientId: cfg.clientId,
2786
+ jwksUrl: cfg.jwksUrl,
2787
+ expectedNonce: verify.expectedNonce,
2788
+ expectedSubject: accessClaims.sub
2789
+ }) : null;
2790
+ return tokenSetSchema.parse({
2791
+ accessToken: t.access_token,
2792
+ tokenType: t.token_type,
2793
+ expiresAt: t.expires_in ? new Date(Date.now() + t.expires_in * 1e3) : null,
2794
+ refreshToken: t.refresh_token ?? null,
2795
+ idToken: t.id_token ?? null,
2796
+ scope: t.scope ? t.scope.split(/\s+/).filter(Boolean) : [],
2797
+ sid: idClaims?.sid ?? accessClaims.sid,
2798
+ accessClaims,
2799
+ idClaims
2800
+ });
2801
+ }
2802
+ __name(postToken, "postToken");
2803
+
2804
+ // src/tokenStore.ts
2805
+ function memoryStore() {
2806
+ const m = /* @__PURE__ */ new Map();
2807
+ const locks = /* @__PURE__ */ new Map();
2808
+ return {
2809
+ async withExclusive(key, work) {
2810
+ const prior = locks.get(key) ?? Promise.resolve();
2811
+ let release;
2812
+ const held = new Promise((resolve) => {
2813
+ release = resolve;
2814
+ });
2815
+ const tail = prior.then(() => held);
2816
+ locks.set(key, tail);
2817
+ await prior;
2818
+ try {
2819
+ return await work();
2820
+ } finally {
2821
+ release();
2822
+ if (locks.get(key) === tail) locks.delete(key);
2823
+ }
2824
+ },
2825
+ async get(k) {
2826
+ return m.get(k) ?? null;
2827
+ },
2828
+ async set(k, v) {
2829
+ m.set(k, v);
2830
+ },
2831
+ async delete(k) {
2832
+ m.delete(k);
2833
+ }
2834
+ };
2835
+ }
2836
+ __name(memoryStore, "memoryStore");
2837
+ function keychainStore(kc) {
2838
+ return {
2839
+ ...kc.withExclusive ? {
2840
+ withExclusive: /* @__PURE__ */ __name((key, work) => kc.withExclusive(key, work), "withExclusive")
2841
+ } : {},
2842
+ async get(k) {
2843
+ return await kc.get(k) ?? null;
2844
+ },
2845
+ async set(k, v) {
2846
+ await kc.set(k, v);
2847
+ },
2848
+ async delete(k) {
2849
+ await kc.delete(k);
2850
+ }
2851
+ };
2852
+ }
2853
+ __name(keychainStore, "keychainStore");
2854
+
2855
+ // src/client.ts
2856
+ var XenoAccountClient = class {
2857
+ static {
2858
+ __name(this, "XenoAccountClient");
2859
+ }
2860
+ surface;
2861
+ account;
2862
+ ledger;
2863
+ authz;
2864
+ oidcConfig;
2865
+ issuer;
2866
+ authorities = {};
2867
+ transport;
2868
+ store;
2869
+ apiKey;
2870
+ broker;
2871
+ refreshStoreKey;
2872
+ refreshPendingKey;
2873
+ access = null;
2874
+ user = null;
2875
+ interactive;
2876
+ resolutionFlight = null;
2877
+ generation = 0;
2878
+ locallySignedOut = false;
2879
+ listeners = /* @__PURE__ */ new Set();
2880
+ constructor(cfg) {
2881
+ this.surface = surfaceSchema.parse(cfg.surface);
2882
+ this.transport = new Transport(cfg.transport);
2883
+ this.oidcConfig = {
2884
+ issuer: cfg.issuer,
2885
+ ...cfg.oidc
2886
+ };
2887
+ this.refreshStoreKey = `xeno.account/${this.oidcConfig.clientId}/refresh`;
2888
+ this.refreshPendingKey = `${this.refreshStoreKey}/pending`;
2889
+ this.account = new AccountClient(cfg.issuer, this.transport);
2890
+ this.ledger = new LedgerClient(cfg.apiBase, this.transport);
2891
+ this.authz = new AuthzClient(cfg.apiBase, this.transport);
2892
+ this.issuer = cfg.issuer;
2893
+ this.store = cfg.store ?? memoryStore();
2894
+ this.apiKey = cfg.apiKey ?? (typeof process !== "undefined" ? process.env?.XENO_API_KEY : void 0) ?? void 0;
2895
+ this.broker = cfg.broker;
2896
+ }
2897
+ // ─── Workspace, workforce, notification and integration authorities ───────
2898
+ //
2899
+ // They live on the issuer origin and authorise every request through `authorization()`, so each
2900
+ // attempt carries its own sender-constrained proof for its exact method and URL. Each is built on
2901
+ // first use: the workspace-line authorities refuse a non-HTTPS or path-bearing origin, and that
2902
+ // refusal belongs to the caller who uses them, not to every client constructed for local
2903
+ // development or for ledger-only use.
2904
+ get workspaces() {
2905
+ return this.authorities.workspaces ??= new WorkspaceClient(this.issuer, this.transport, (method, url, opts) => this.authorization(method, url, opts));
2906
+ }
2907
+ get workforce() {
2908
+ return this.authorities.workforce ??= new WorkforceClient(this.issuer, this.transport, (method, url, opts) => this.authorization(method, url, opts));
2909
+ }
2910
+ get notifications() {
2911
+ return this.authorities.notifications ??= new NotificationsClient(this.issuer, this.transport, (method, url, opts) => this.authorization(method, url, opts));
2912
+ }
2913
+ get integrations() {
2914
+ return this.authorities.integrations ??= new AccountIntegrationClient(this.issuer, this.transport, (method, url, opts) => this.authorization(method, url, opts));
2915
+ }
2916
+ // ─── Session workhorse (priority chain, XENO AUTH §5) ───────────────────
2917
+ /**
2918
+ * Return a valid Bearer for the gate, walking the chain:
2919
+ * 1 in-memory access token → 2 explicit override (apiKey/XENO_API_KEY) →
2920
+ * 3 [broker — host-wired] → 4 this product's own refresh token →
2921
+ * 5 interactive sign-in (host-provided; skipped when `silent`) → null.
2922
+ */
2923
+ async getAccessToken(opts = {}) {
2924
+ const generation = this.generation;
2925
+ const scopes = opts.scopes ? [
2926
+ ...opts.scopes
2927
+ ] : void 0;
2928
+ if (this.access && this.access.expiresAtMs - 6e4 > Date.now() && containsScopes(this.access.scopes, scopes)) {
2929
+ const held = this.access;
2930
+ if (await this.cacheCurrent(held) && this.generation === generation) return held.token;
2931
+ }
2932
+ if (this.apiKey) return this.apiKey;
2933
+ if (this.locallySignedOut && opts.silent) return null;
2934
+ if (!this.resolutionFlight) {
2935
+ const flight = this.resolveSession({
2936
+ scopes,
2937
+ silent: opts.silent
2938
+ }, generation);
2939
+ this.resolutionFlight = flight;
2940
+ void flight.finally(() => {
2941
+ if (this.resolutionFlight === flight) this.resolutionFlight = null;
2942
+ }).catch(() => {
2943
+ });
2944
+ }
2945
+ await this.resolutionFlight;
2946
+ if (this.generation !== generation || !this.access) return null;
2947
+ if (!await this.cacheCurrent(this.access) || this.generation !== generation || !this.access) return null;
2948
+ if (!containsScopes(this.access.scopes, scopes)) throw new AccountError({
2949
+ code: "INVALID_TOKEN",
2950
+ message: "Current account session lacks required scope",
2951
+ retryable: false
2952
+ });
2953
+ if (this.access.expiresAtMs <= Date.now()) return null;
2954
+ return this.access.token;
2955
+ }
2956
+ async resolveSession(opts, generation) {
2957
+ if (this.locallySignedOut) {
2958
+ if (!opts.silent && this.interactive) await this.resolveInteractive(opts.scopes, generation);
2959
+ return;
2960
+ }
2961
+ const pending = await this.storeRead(this.refreshPendingKey) ?? await this.legacyRefreshMarker();
2962
+ if (this.generation !== generation) return;
2963
+ const interruptedRotation = abandonedRotation(pending);
2964
+ if (pending && !interruptedRotation && !/^ready:v1:[A-Za-z0-9_-]{32}$/.test(pending)) {
2965
+ if (!opts.silent && this.interactive) {
2966
+ await this.resolveInteractive(opts.scopes, generation);
2967
+ return;
2968
+ }
2969
+ if (pending === "signed-out:v1") {
2970
+ this.setUnauthenticated();
2971
+ if (!await this.storeRead(this.refreshStoreKey)) return;
2972
+ } else {
2973
+ throw new AccountError({
2974
+ code: "CONFLICT",
2975
+ message: "Previous account transition is unconfirmed; explicit sign-in recovery required",
2976
+ retryable: false
2977
+ });
2978
+ }
2979
+ if (pending === "signed-out:v1") throw transitionConflict();
2980
+ }
2981
+ if (this.broker) {
2982
+ try {
2983
+ const brokerToken = await this.broker.getToken({
2984
+ clientId: this.oidcConfig.clientId,
2985
+ scopes: opts.scopes ?? this.oidcConfig.scopes ?? [],
2986
+ resource: "https://api.xenostudio.ai",
2987
+ childDpopJkt: this.oidcConfig.dpopSigner.jkt
2988
+ });
2989
+ if (brokerToken) {
2990
+ const claims = await verifyAccessToken({
2991
+ token: brokerToken.accessToken,
2992
+ transport: this.transport,
2993
+ issuer: this.oidcConfig.issuer,
2994
+ clientId: this.oidcConfig.clientId,
2995
+ dpopJkt: this.oidcConfig.dpopSigner.jkt,
2996
+ jwksUrl: this.oidcConfig.jwksUrl,
2997
+ expectedScopes: opts.scopes,
2998
+ requireBrokerActor: true
2999
+ });
3000
+ if (brokerToken.refreshToken) throw new AccountError({
3001
+ code: "INVALID_RESPONSE",
3002
+ message: "Broker cannot transfer refresh credentials",
3003
+ retryable: false
3004
+ });
3005
+ await this.applyTokenSet({
3006
+ ...brokerToken,
3007
+ accessClaims: claims,
3008
+ idClaims: null
3009
+ }, generation, pending, true);
3010
+ return;
3011
+ }
3012
+ } catch {
3013
+ }
3014
+ }
3015
+ if (this.generation !== generation) return;
3016
+ const rotationId = interruptedRotation ?? generateState();
3017
+ const transition = rotationMarker(rotationId);
3018
+ const rt = await this.exclusiveStore(async () => {
3019
+ if (this.generation !== generation) return null;
3020
+ if (await this.store.get(this.refreshPendingKey) !== pending) throw transitionConflict();
3021
+ const value = await this.store.get(this.refreshStoreKey);
3022
+ if (value) await this.store.set(this.refreshPendingKey, transition);
3023
+ return value;
3024
+ });
3025
+ if (this.generation !== generation) return;
3026
+ if (interruptedRotation && !rt) throw transitionConflict();
3027
+ if (rt) {
3028
+ try {
3029
+ const tokens = await this.refresh(rt, rotationId);
3030
+ if (!tokens.refreshToken) throw new AccountError({
3031
+ code: "INVALID_RESPONSE",
3032
+ message: "Rotating refresh response omitted successor credential",
3033
+ retryable: false
3034
+ });
3035
+ await this.applyTokenSet(tokens, generation, transition);
3036
+ return;
3037
+ } catch (error) {
3038
+ if (this.generation !== generation) return;
3039
+ if (!(error instanceof AccountError && error.httpStatus === 400 && error.oauthError === "invalid_grant")) {
3040
+ throw new AccountError({
3041
+ code: error instanceof AccountError ? error.code : "UNREACHABLE",
3042
+ message: "Account refresh outcome is unconfirmed; explicit recovery required",
3043
+ retryable: false,
3044
+ ...error instanceof AccountError ? {
3045
+ httpStatus: error.httpStatus
3046
+ } : {}
3047
+ });
3048
+ }
3049
+ await this.exclusiveStore(async () => {
3050
+ if (this.generation !== generation) return;
3051
+ if (await this.store.get(this.refreshPendingKey) !== transition) throw transitionConflict();
3052
+ await this.store.delete(this.refreshStoreKey);
3053
+ await this.store.set(this.refreshPendingKey, "signed-out:v1");
3054
+ });
3055
+ if (this.generation !== generation) return;
3056
+ this.setUnauthenticated();
3057
+ }
3058
+ }
3059
+ if (!opts.silent && this.interactive) {
3060
+ await this.resolveInteractive(opts.scopes, generation);
3061
+ }
3062
+ return;
3063
+ }
3064
+ /** Register the host's interactive sign-in (loopback PKCE / device grant). */
3065
+ setInteractiveSignIn(fn) {
3066
+ this.interactive = fn;
3067
+ }
3068
+ isAuthenticated() {
3069
+ return !!this.access && this.access.expiresAtMs > Date.now();
3070
+ }
3071
+ currentUser() {
3072
+ return this.user;
3073
+ }
3074
+ /** Subscribe to login/refresh/logout/backchannel. Returns an unsubscribe fn. */
3075
+ onAuthChanged(cb) {
3076
+ this.listeners.add(cb);
3077
+ return () => this.listeners.delete(cb);
3078
+ }
3079
+ /** Local wipe only, used after durable host-side invalidation/reconciliation. */
3080
+ async signOutLocal() {
3081
+ this.generation++;
3082
+ this.locallySignedOut = true;
3083
+ this.resolutionFlight = null;
3084
+ this.setUnauthenticated();
3085
+ await this.exclusiveStore(async () => {
3086
+ await this.store.set(this.refreshPendingKey, "signed-out:v1");
3087
+ await this.store.delete(this.refreshStoreKey);
3088
+ });
3089
+ }
3090
+ /** Revoke this subject-owned session, then always clear local state. */
3091
+ async signOut() {
3092
+ const original = this.access;
3093
+ const local = this.signOutLocal();
3094
+ void local.catch(() => {
3095
+ });
3096
+ let serverRevoked = false;
3097
+ try {
3098
+ if (original?.tokenType === "DPoP") {
3099
+ const url = `${this.oidcConfig.issuer.replace(/\/+$/, "")}/api/oauth2/end_session`;
3100
+ const dpop = await this.createProof({
3101
+ method: "POST",
3102
+ url,
3103
+ accessToken: original.token
3104
+ });
3105
+ await this.transport.request({
3106
+ method: "POST",
3107
+ url,
3108
+ token: original.token,
3109
+ tokenType: "DPoP",
3110
+ headers: {
3111
+ dpop
3112
+ },
3113
+ idempotencyKey: `logout:${original.sid ?? "current"}`
3114
+ });
3115
+ serverRevoked = true;
3116
+ }
3117
+ } finally {
3118
+ await local;
3119
+ }
3120
+ return {
3121
+ serverRevoked
3122
+ };
3123
+ }
3124
+ /** Step-up protected, subject-keyed global logout. Only authorized clients can call it. */
3125
+ async signOutEverywhere() {
3126
+ if (!this.access || this.access.tokenType !== "DPoP") throw new Error("fresh DPoP session required");
3127
+ const original = this.access, generation = this.generation;
3128
+ const url = `${this.oidcConfig.issuer.replace(/\/+$/, "")}/api/oauth2/logout_everywhere`;
3129
+ const dpop = await this.createProof({
3130
+ method: "POST",
3131
+ url,
3132
+ accessToken: original.token
3133
+ });
3134
+ if (this.generation !== generation || this.access !== original) throw new AccountError({
3135
+ code: "CONFLICT",
3136
+ message: "Account session changed before global revocation",
3137
+ retryable: false
3138
+ });
3139
+ await this.transport.request({
3140
+ method: "POST",
3141
+ url,
3142
+ token: original.token,
3143
+ tokenType: "DPoP",
3144
+ headers: {
3145
+ dpop
3146
+ },
3147
+ idempotencyKey: `logout-all:${original.sid ?? "current"}`
3148
+ });
3149
+ try {
3150
+ await this.broker?.logout?.();
3151
+ } finally {
3152
+ if (this.generation === generation) {
3153
+ this.generation++;
3154
+ this.locallySignedOut = true;
3155
+ this.resolutionFlight = null;
3156
+ this.setUnauthenticated();
3157
+ await this.exclusiveStore(async () => {
3158
+ if (await this.store.get(this.refreshPendingKey) !== original.storeTransition) return;
3159
+ await this.store.set(this.refreshPendingKey, "signed-out:v1");
3160
+ await this.store.delete(this.refreshStoreKey);
3161
+ });
3162
+ }
3163
+ }
3164
+ }
3165
+ setUnauthenticated() {
3166
+ this.access = null;
3167
+ this.user = null;
3168
+ this.emit(null);
3169
+ }
3170
+ emit(a) {
3171
+ for (const cb of [
3172
+ ...this.listeners
3173
+ ]) {
3174
+ try {
3175
+ cb(a);
3176
+ } catch {
3177
+ }
3178
+ }
3179
+ }
3180
+ /**
3181
+ * The 0.2.0 workforce builds (shipped vendored, never published) marked an in-flight refresh at
3182
+ * `<refresh key>-uncertain` and never named the rotation. An install upgrading with that marker
3183
+ * present may hold a token the origin already rotated, so sending it would be a replay — the
3184
+ * zero-grace reuse that revokes the whole family. It is therefore an unconfirmed transition like any
3185
+ * other v1 marker: refused silently, recoverable only by explicit sign-in (which writes this
3186
+ * version's own marker, after which the legacy one is never consulted again).
3187
+ */
3188
+ async legacyRefreshMarker() {
3189
+ return await this.storeRead(`${this.refreshStoreKey}-uncertain`) ? "legacy-refresh-uncertain:v1" : null;
3190
+ }
3191
+ async storeRead(key) {
3192
+ try {
3193
+ return await this.store.get(key);
3194
+ } catch {
3195
+ throw new AccountError({
3196
+ code: "UNREACHABLE",
3197
+ message: "Secure account store is unavailable",
3198
+ retryable: false
3199
+ });
3200
+ }
3201
+ }
3202
+ async cacheCurrent(held) {
3203
+ const transition = await this.storeRead(this.refreshPendingKey);
3204
+ if (this.access === held && transition === held.storeTransition) return true;
3205
+ if (this.access === held) this.setUnauthenticated();
3206
+ return false;
3207
+ }
3208
+ async exclusiveStore(work) {
3209
+ if (!this.store.withExclusive) throw new AccountError({
3210
+ code: "UNREACHABLE",
3211
+ message: "Secure account store exclusion is unavailable",
3212
+ retryable: false
3213
+ });
3214
+ try {
3215
+ return await this.store.withExclusive(this.refreshStoreKey, work);
3216
+ } catch (error) {
3217
+ if (error instanceof AccountError) throw error;
3218
+ throw new AccountError({
3219
+ code: "UNREACHABLE",
3220
+ message: "Secure account state commit is unavailable",
3221
+ retryable: false
3222
+ });
3223
+ }
3224
+ }
3225
+ async reserveSignIn(generation) {
3226
+ const transition = `sign-in:v1:${generateState()}`;
3227
+ await this.exclusiveStore(async () => {
3228
+ if (this.generation !== generation) throw transitionConflict();
3229
+ await this.store.set(this.refreshPendingKey, transition);
3230
+ });
3231
+ return transition;
3232
+ }
3233
+ async resolveInteractive(scopes, generation) {
3234
+ const transition = await this.reserveSignIn(generation);
3235
+ await this.applyTokenSet(await this.interactive(scopes), generation, transition);
3236
+ }
3237
+ /** Cache the access token, persist the rotated refresh token, update the user. */
3238
+ async applyTokenSet(ts, generation, transition, preserveRefresh = false, signal) {
3239
+ if (this.generation !== generation) return;
3240
+ const claims = await verifyAccessToken({
3241
+ token: ts.accessToken,
3242
+ transport: this.transport,
3243
+ issuer: this.oidcConfig.issuer,
3244
+ clientId: this.oidcConfig.clientId,
3245
+ dpopJkt: this.oidcConfig.dpopSigner.jkt,
3246
+ jwksUrl: this.oidcConfig.jwksUrl
3247
+ });
3248
+ const idClaims = ts.idToken ? await verifyIdToken({
3249
+ token: ts.idToken,
3250
+ transport: this.transport,
3251
+ issuer: this.oidcConfig.issuer,
3252
+ clientId: this.oidcConfig.clientId,
3253
+ jwksUrl: this.oidcConfig.jwksUrl,
3254
+ expectedSubject: claims.sub
3255
+ }) : null;
3256
+ if (idClaims && idClaims.sid !== claims.sid) throw new AccountError({
3257
+ code: "INVALID_RESPONSE",
3258
+ message: "ID and access session binding differ",
3259
+ retryable: false
3260
+ });
3261
+ if (ts.tokenType.toLowerCase() !== "dpop") throw new AccountError({
3262
+ code: "INVALID_RESPONSE",
3263
+ message: "Canonical session requires DPoP token type",
3264
+ retryable: false
3265
+ });
3266
+ if (this.generation !== generation) return;
3267
+ const expMs = Math.min(claims.exp * 1e3, ts.expiresAt?.getTime() ?? claims.exp * 1e3);
3268
+ const storeTransition = `ready:v1:${generateState()}`;
3269
+ await this.exclusiveStore(async () => {
3270
+ if (this.generation !== generation) return;
3271
+ if (await this.store.get(this.refreshPendingKey) !== transition) throw transitionConflict();
3272
+ if (ts.refreshToken) {
3273
+ await this.store.set(this.refreshStoreKey, ts.refreshToken);
3274
+ } else if (!preserveRefresh) await this.store.delete(this.refreshStoreKey);
3275
+ if (this.generation !== generation || signal?.aborted) throw transitionConflict();
3276
+ await this.store.set(this.refreshPendingKey, storeTransition);
3277
+ if (signal?.aborted) {
3278
+ if (await this.store.get(this.refreshPendingKey) === storeTransition) {
3279
+ await this.store.set(this.refreshPendingKey, "signed-out:v1");
3280
+ await this.store.delete(this.refreshStoreKey);
3281
+ }
3282
+ throw transitionConflict();
3283
+ }
3284
+ });
3285
+ if (this.generation !== generation) {
3286
+ if (signal?.aborted) await this.cancelCommittedSignIn(storeTransition);
3287
+ return;
3288
+ }
3289
+ this.access = {
3290
+ token: ts.accessToken,
3291
+ tokenType: ts.tokenType.toLowerCase() === "dpop" ? "DPoP" : "Bearer",
3292
+ expiresAtMs: expMs,
3293
+ scopes: claims.scope.split(/\s+/).filter(Boolean),
3294
+ sid: claims.sid,
3295
+ storeTransition
3296
+ };
3297
+ this.locallySignedOut = false;
3298
+ if (idClaims) {
3299
+ const u = accountFromVerifiedClaims(idClaims);
3300
+ if (u) this.user = u;
3301
+ } else if (this.user?.id !== claims.sub) this.user = null;
3302
+ this.emit(this.user);
3303
+ return storeTransition;
3304
+ }
3305
+ async cancelCommittedSignIn(transition) {
3306
+ await this.exclusiveStore(async () => {
3307
+ if (await this.store.get(this.refreshPendingKey) !== transition) return;
3308
+ await this.store.set(this.refreshPendingKey, "signed-out:v1");
3309
+ await this.store.delete(this.refreshStoreKey);
3310
+ });
3311
+ }
3312
+ // ─── OIDC sign-in (Authorization Code + PKCE) ───────────────────────────
3313
+ /**
3314
+ * Begin "Continue with XENO". Returns the authorize URL to redirect to, plus
3315
+ * the `{ state, verifier }` the caller MUST persist (encrypted) to complete
3316
+ * the flow in {@link completeSignIn}.
3317
+ */
3318
+ async beginSignIn(args = {}) {
3319
+ const state = generateState();
3320
+ const nonce = generateState();
3321
+ const pkce = await generatePkce();
3322
+ const url = buildAuthorizeUrl(this.oidcConfig, {
3323
+ state,
3324
+ codeChallenge: pkce.challenge,
3325
+ redirectUri: args.redirectUri,
3326
+ scopes: args.scopes,
3327
+ nonce,
3328
+ ...args.fresh ? {
3329
+ prompt: "login",
3330
+ maxAge: 60,
3331
+ acrValues: "urn:xeno:acr:fresh"
3332
+ } : {}
3333
+ });
3334
+ return {
3335
+ url,
3336
+ state,
3337
+ nonce,
3338
+ pkce
3339
+ };
3340
+ }
3341
+ /** Complete the code flow: exchange `code` (with the saved verifier) for tokens,
3342
+ * then cache the access token + persist the refresh token + set the user. */
3343
+ async completeSignIn(args) {
3344
+ const generation = ++this.generation;
3345
+ this.resolutionFlight = null;
3346
+ const invalidate = this.bindSignInCancellation(generation, args.signal);
3347
+ try {
3348
+ if (args.signal?.aborted) throw transitionConflict();
3349
+ const transition = await this.reserveSignIn(generation);
3350
+ if (args.signal?.aborted || this.generation !== generation) throw transitionConflict();
3351
+ const ts = await exchangeCode(this.oidcConfig, this.transport, args);
3352
+ const committed2 = await this.applyTokenSet(ts, generation, transition, false, args.signal);
3353
+ if (this.generation !== generation || args.signal?.aborted) {
3354
+ if (committed2 && args.signal?.aborted) await this.cancelCommittedSignIn(committed2);
3355
+ throw transitionConflict();
3356
+ }
3357
+ return ts;
3358
+ } catch (error) {
3359
+ if (args.signal?.aborted) throw transitionConflict();
3360
+ throw error;
3361
+ } finally {
3362
+ invalidate();
3363
+ }
3364
+ }
3365
+ bindSignInCancellation(generation, signal) {
3366
+ const cancelled = /* @__PURE__ */ __name(() => {
3367
+ if (this.generation !== generation) return;
3368
+ this.generation++;
3369
+ this.resolutionFlight = null;
3370
+ this.setUnauthenticated();
3371
+ }, "cancelled");
3372
+ signal?.addEventListener("abort", cancelled, {
3373
+ once: true
3374
+ });
3375
+ if (signal?.aborted) cancelled();
3376
+ return () => signal?.removeEventListener("abort", cancelled);
3377
+ }
3378
+ /** Headers for one sender-constrained resource request. */
3379
+ async authorization(method, url, opts = {}) {
3380
+ const generation = this.generation;
3381
+ const token = await this.getAccessToken(opts);
3382
+ if (!token || this.generation !== generation) return null;
3383
+ if (this.apiKey && token === this.apiKey) return {
3384
+ token,
3385
+ tokenType: "Bearer"
3386
+ };
3387
+ if (!this.access || this.access.token !== token || this.access.tokenType !== "DPoP") return {
3388
+ token,
3389
+ tokenType: "Bearer"
3390
+ };
3391
+ const dpop = await this.createProof({
3392
+ method,
3393
+ url,
3394
+ accessToken: token
3395
+ });
3396
+ if (this.generation !== generation || this.access?.token !== token || this.access.expiresAtMs <= Date.now()) return null;
3397
+ if (!await this.cacheCurrent(this.access) || this.generation !== generation || this.access?.token !== token) return null;
3398
+ return {
3399
+ token,
3400
+ tokenType: "DPoP",
3401
+ headers: {
3402
+ dpop
3403
+ }
3404
+ };
3405
+ }
3406
+ /** Verify and sender-constrain a previously persisted access token. Server
3407
+ * consumers use this for encrypted per-workspace sessions without placing
3408
+ * those tokens into the process-global client cache. */
3409
+ async authorizationForToken(token, method, url, expectedScopes) {
3410
+ await verifyAccessToken({
3411
+ token,
3412
+ transport: this.transport,
3413
+ issuer: this.oidcConfig.issuer,
3414
+ clientId: this.oidcConfig.clientId,
3415
+ dpopJkt: this.oidcConfig.dpopSigner.jkt,
3416
+ jwksUrl: this.oidcConfig.jwksUrl,
3417
+ expectedScopes
3418
+ });
3419
+ const dpop = await this.createProof({
3420
+ method,
3421
+ url,
3422
+ accessToken: token
3423
+ });
3424
+ return {
3425
+ token,
3426
+ tokenType: "DPoP",
3427
+ headers: {
3428
+ dpop
3429
+ }
3430
+ };
3431
+ }
3432
+ /** Verify a provider-originated Back-Channel Logout Token. */
3433
+ verifyBackchannelLogout(token) {
3434
+ return verifyLogoutToken({
3435
+ token,
3436
+ transport: this.transport,
3437
+ issuer: this.oidcConfig.issuer,
3438
+ clientId: this.oidcConfig.clientId,
3439
+ jwksUrl: this.oidcConfig.jwksUrl
3440
+ });
3441
+ }
3442
+ async createProof(args) {
3443
+ try {
3444
+ return await this.oidcConfig.dpopSigner.createProof(args);
3445
+ } catch {
3446
+ throw new AccountError({
3447
+ code: "UNREACHABLE",
3448
+ message: "Host account request signing is unavailable",
3449
+ retryable: false
3450
+ });
3451
+ }
3452
+ }
3453
+ /** Rotate tokens. Persist the returned refreshToken; a failure means re-auth. */
3454
+ refresh(refreshToken, rotationId) {
3455
+ return refreshTokens(this.oidcConfig, this.transport, refreshToken, rotationId);
3456
+ }
3457
+ // ─── Device grant (CLI / headless) ──────────────────────────────────────
3458
+ startDeviceLogin(scopes) {
3459
+ return startDeviceAuthorization(this.oidcConfig, this.transport, scopes);
3460
+ }
3461
+ async awaitDeviceLogin(device, opts) {
3462
+ const generation = ++this.generation;
3463
+ this.resolutionFlight = null;
3464
+ const invalidate = this.bindSignInCancellation(generation, opts?.signal);
3465
+ try {
3466
+ if (opts?.signal?.aborted) throw transitionConflict();
3467
+ const transition = await this.reserveSignIn(generation);
3468
+ if (opts?.signal?.aborted || this.generation !== generation) throw transitionConflict();
3469
+ const ts = await pollDeviceToken(this.oidcConfig, this.transport, device, opts);
3470
+ const committed2 = await this.applyTokenSet(ts, generation, transition, false, opts?.signal);
3471
+ if (this.generation !== generation || opts?.signal?.aborted) {
3472
+ if (committed2 && opts?.signal?.aborted) await this.cancelCommittedSignIn(committed2);
3473
+ throw transitionConflict();
3474
+ }
3475
+ return ts;
3476
+ } catch (error) {
3477
+ if (opts?.signal?.aborted) throw transitionConflict();
3478
+ throw error;
3479
+ } finally {
3480
+ invalidate();
3481
+ }
3482
+ }
3483
+ };
3484
+ function accountFromVerifiedClaims(p) {
3485
+ if (!p.sub) return null;
3486
+ return {
3487
+ id: p.sub,
3488
+ email: p.email ?? "",
3489
+ username: p.preferred_username ?? null,
3490
+ displayName: p.name ?? null,
3491
+ avatarUrl: p.picture ?? null,
3492
+ emailVerified: p.email_verified === true,
3493
+ linkedSurfaces: []
3494
+ };
3495
+ }
3496
+ __name(accountFromVerifiedClaims, "accountFromVerifiedClaims");
3497
+ function containsScopes(held, requested) {
3498
+ if (!requested?.length) return true;
3499
+ const set = new Set(held);
3500
+ return requested.every((scope) => set.has(scope));
3501
+ }
3502
+ __name(containsScopes, "containsScopes");
3503
+ var ROTATION_IN_FLIGHT_MS = 3e4;
3504
+ function rotationMarker(rotationId) {
3505
+ const pid = typeof process !== "undefined" && typeof process.pid === "number" ? process.pid : 0;
3506
+ return `refresh:v2:${rotationId}:${pid}:${Date.now()}`;
3507
+ }
3508
+ __name(rotationMarker, "rotationMarker");
3509
+ function abandonedRotation(marker, now = Date.now()) {
3510
+ const match = marker?.match(/^refresh:v2:([A-Za-z0-9_-]{32}):(\d{1,10}):(\d{1,15})$/);
3511
+ if (!match) return void 0;
3512
+ const pid = Number(match[2]), started = Number(match[3]);
3513
+ if (now - started > ROTATION_IN_FLIGHT_MS) return match[1];
3514
+ return pid > 0 && !processAlive(pid) ? match[1] : void 0;
3515
+ }
3516
+ __name(abandonedRotation, "abandonedRotation");
3517
+ function processAlive(pid) {
3518
+ if (typeof process === "undefined" || typeof process.kill !== "function") return true;
3519
+ try {
3520
+ process.kill(pid, 0);
3521
+ return true;
3522
+ } catch (error) {
3523
+ return error.code === "EPERM";
3524
+ }
3525
+ }
3526
+ __name(processAlive, "processAlive");
3527
+ function transitionConflict() {
3528
+ return new AccountError({
3529
+ code: "CONFLICT",
3530
+ message: "Account credential transition changed; explicit recovery required",
3531
+ retryable: false
3532
+ });
3533
+ }
3534
+ __name(transitionConflict, "transitionConflict");
3535
+
3536
+ // src/bff.ts
3537
+ var BffSessionClient = class {
3538
+ static {
3539
+ __name(this, "BffSessionClient");
3540
+ }
3541
+ baseUrl;
3542
+ fetchImpl;
3543
+ csrf;
3544
+ constructor(baseUrl = "/api/session", fetchImpl = globalThis.fetch, csrf) {
3545
+ this.baseUrl = baseUrl;
3546
+ this.fetchImpl = fetchImpl;
3547
+ this.csrf = csrf;
3548
+ }
3549
+ loginUrl(returnUrl) {
3550
+ if (!returnUrl.startsWith("/") || returnUrl.startsWith("//")) throw new AccountError({
3551
+ code: "BAD_REQUEST",
3552
+ message: "returnUrl must be same-origin"
3553
+ });
3554
+ return `${this.baseUrl}/login/start?return_url=${encodeURIComponent(returnUrl)}`;
3555
+ }
3556
+ session() {
3557
+ return this.request("GET", "/session");
3558
+ }
3559
+ refresh(idempotencyKey) {
3560
+ return this.request("POST", "/refresh", idempotencyKey);
3561
+ }
3562
+ async logout() {
3563
+ await this.request("POST", "/logout");
3564
+ }
3565
+ async request(method, path, idempotencyKey) {
3566
+ const headers = {
3567
+ accept: "application/json"
3568
+ };
3569
+ if (method === "POST") {
3570
+ const csrf = this.csrf();
3571
+ if (!csrf) throw new AccountError({
3572
+ code: "BAD_REQUEST",
3573
+ message: "missing BFF CSRF value"
3574
+ });
3575
+ headers["x-xeno-csrf"] = csrf;
3576
+ if (idempotencyKey) headers["idempotency-key"] = idempotencyKey;
3577
+ }
3578
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
3579
+ method,
3580
+ credentials: "include",
3581
+ headers
3582
+ });
3583
+ if (!response.ok) throw new AccountError({
3584
+ code: response.status === 401 ? "INVALID_TOKEN" : "PLATFORM_ERROR",
3585
+ message: `BFF session request failed: ${response.status}`,
3586
+ httpStatus: response.status
3587
+ });
3588
+ if (response.status === 204) return void 0;
3589
+ return response.json();
3590
+ }
3591
+ };
3592
+
3593
+ // src/redaction.ts
3594
+ var TOKEN_RE = /(eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,})|([A-Za-z0-9_-]{40,})/g;
3595
+ function redact(input) {
3596
+ const s = typeof input === "string" ? input : safeStringify(input);
3597
+ return s.replace(TOKEN_RE, (m) => `${m.slice(0, 6)}\u2026[redacted:${m.length}]`);
3598
+ }
3599
+ __name(redact, "redact");
3600
+ function safeStringify(v) {
3601
+ try {
3602
+ return JSON.stringify(v) ?? String(v);
3603
+ } catch {
3604
+ return String(v);
3605
+ }
3606
+ }
3607
+ __name(safeStringify, "safeStringify");
3608
+
3609
+ // src/resource-authorization.ts
3610
+ var MAX_JWT_BYTES = 16384;
3611
+ var PRIVATE_FIELDS = [
3612
+ "d",
3613
+ "p",
3614
+ "q",
3615
+ "dp",
3616
+ "dq",
3617
+ "qi",
3618
+ "oth",
3619
+ "k"
3620
+ ];
3621
+ function denied() {
3622
+ return new AccountError({
3623
+ code: "INVALID_TOKEN",
3624
+ message: "Resource authorization refused",
3625
+ retryable: false,
3626
+ httpStatus: 401
3627
+ });
3628
+ }
3629
+ __name(denied, "denied");
3630
+ function unavailable() {
3631
+ return new AccountError({
3632
+ code: "UNREACHABLE",
3633
+ message: "Resource authorization authority unavailable",
3634
+ retryable: true,
3635
+ httpStatus: 503
3636
+ });
3637
+ }
3638
+ __name(unavailable, "unavailable");
3639
+ function decodePart(part) {
3640
+ if (!/^[a-zA-Z0-9_-]+$/.test(part) || part.length % 4 === 1) throw denied();
3641
+ const padded = part.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - part.length % 4) % 4);
3642
+ try {
3643
+ return Uint8Array.from(atob(padded), (value) => value.charCodeAt(0));
3644
+ } catch {
3645
+ throw denied();
3646
+ }
3647
+ }
3648
+ __name(decodePart, "decodePart");
3649
+ function record(bytes2) {
3650
+ try {
3651
+ return parseJwtObject(new TextDecoder("utf-8", {
3652
+ fatal: true
3653
+ }).decode(bytes2));
3654
+ } catch {
3655
+ throw denied();
3656
+ }
3657
+ }
3658
+ __name(record, "record");
3659
+ async function sha(value) {
3660
+ const bytes2 = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));
3661
+ return btoa(String.fromCharCode(...bytes2)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
3662
+ }
3663
+ __name(sha, "sha");
3664
+ function frozenClaims(claims) {
3665
+ return Object.freeze({
3666
+ iss: claims.iss,
3667
+ sub: claims.sub,
3668
+ aud: claims.aud,
3669
+ exp: claims.exp,
3670
+ iat: claims.iat,
3671
+ sid: claims.sid,
3672
+ client_id: claims.client_id,
3673
+ azp: claims.azp,
3674
+ scope: claims.scope,
3675
+ typ: claims.typ,
3676
+ auth_epoch: claims.auth_epoch,
3677
+ ...claims.auth_time === void 0 ? {} : {
3678
+ auth_time: claims.auth_time
3679
+ },
3680
+ ...claims.acr ? {
3681
+ acr: claims.acr
3682
+ } : {},
3683
+ cnf: Object.freeze({
3684
+ jkt: claims.cnf.jkt
3685
+ }),
3686
+ ...Array.isArray(claims.aud) ? {
3687
+ aud: Object.freeze([
3688
+ ...claims.aud
3689
+ ])
3690
+ } : {},
3691
+ ...claims.act ? {
3692
+ act: Object.freeze({
3693
+ client_id: claims.act.client_id,
3694
+ installation_id_hash: claims.act.installation_id_hash,
3695
+ ...claims.act.sub ? {
3696
+ sub: claims.act.sub
3697
+ } : {}
3698
+ })
3699
+ } : {},
3700
+ ...claims.amr ? {
3701
+ amr: Object.freeze([
3702
+ ...claims.amr
3703
+ ])
3704
+ } : {}
3705
+ });
3706
+ }
3707
+ __name(frozenClaims, "frozenClaims");
3708
+ function createResourceRequestAuthorizer(options) {
3709
+ const issuer = normalizeDpopHtu(options.issuer);
3710
+ if (issuer.replace(/\/$/, "") !== options.issuer || !options.clientIds.length || options.clientIds.length > 128 || options.clientIds.some((id5) => !/^[a-zA-Z0-9._-]{1,128}$/.test(id5)) || new Set(options.clientIds).size !== options.clientIds.length) throw new TypeError("Explicit canonical issuer and unique clients required");
3711
+ const clients = new Set(options.clientIds);
3712
+ return {
3713
+ async authorize(request) {
3714
+ request = Object.freeze({
3715
+ ...request,
3716
+ ...request.scopes ? {
3717
+ scopes: [
3718
+ ...request.scopes
3719
+ ]
3720
+ } : {}
3721
+ });
3722
+ if (!/^[A-Z]{3,16}$/.test(request.method) || request.url.length > 8192 || request.authorization.length > MAX_JWT_BYTES + 5 || request.proof.length > MAX_JWT_BYTES || !request.proof || (request.scopes?.length ?? 0) > 128) throw denied();
3723
+ let url;
3724
+ try {
3725
+ const parsed = new URL(request.url);
3726
+ if (parsed.username || parsed.password || parsed.hash) throw denied();
3727
+ url = normalizeDpopHtu(request.url);
3728
+ } catch {
3729
+ throw denied();
3730
+ }
3731
+ const match = /^DPoP ([a-zA-Z0-9_.-]+)$/.exec(request.authorization);
3732
+ if (!match) throw denied();
3733
+ const token = match[1];
3734
+ const parts = request.proof.split(".");
3735
+ if (parts.length !== 3) throw denied();
3736
+ const header = record(decodePart(parts[0])), proof = record(decodePart(parts[1]));
3737
+ if (header.typ !== "dpop+jwt" || header.alg !== "ES256" || header.crit !== void 0 || header.b64 !== void 0 || !header.jwk || typeof header.jwk !== "object" || Array.isArray(header.jwk)) throw denied();
3738
+ const supplied = header.jwk;
3739
+ if (PRIVATE_FIELDS.some((field) => supplied[field] !== void 0) || supplied.kty !== "EC" || supplied.crv !== "P-256" || typeof supplied.x !== "string" || typeof supplied.y !== "string" || decodePart(supplied.x).length !== 32 || decodePart(supplied.y).length !== 32) throw denied();
3740
+ const jwk = {
3741
+ kty: "EC",
3742
+ crv: "P-256",
3743
+ x: supplied.x,
3744
+ y: supplied.y
3745
+ };
3746
+ const jkt = await sha(JSON.stringify({
3747
+ crv: jwk.crv,
3748
+ kty: jwk.kty,
3749
+ x: jwk.x,
3750
+ y: jwk.y
3751
+ }));
3752
+ const now = Math.floor(Date.now() / 1e3);
3753
+ if (typeof proof.jti !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/.test(proof.jti) || !Number.isSafeInteger(proof.iat) || Number(proof.iat) < now - 60 || Number(proof.iat) > now + 60 || proof.htm !== request.method || proof.htu !== url || proof.ath !== await sha(token) || (request.nonce === void 0 ? proof.nonce !== void 0 : proof.nonce !== request.nonce)) throw denied();
3754
+ try {
3755
+ const key = await crypto.subtle.importKey("jwk", jwk, {
3756
+ name: "ECDSA",
3757
+ namedCurve: "P-256"
3758
+ }, false, [
3759
+ "verify"
3760
+ ]);
3761
+ if (!await crypto.subtle.verify({
3762
+ name: "ECDSA",
3763
+ hash: "SHA-256"
3764
+ }, key, decodePart(parts[2]), new TextEncoder().encode(`${parts[0]}.${parts[1]}`))) throw denied();
3765
+ } catch {
3766
+ throw denied();
3767
+ }
3768
+ const tokenParts = token.split(".");
3769
+ if (tokenParts.length !== 3) throw denied();
3770
+ const tokenHeader = record(decodePart(tokenParts[0]));
3771
+ if (tokenHeader.alg !== "ES256" || tokenHeader.typ !== "at+jwt" || typeof tokenHeader.kid !== "string" || tokenHeader.kid.length > 128 || tokenHeader.crit !== void 0 || tokenHeader.b64 !== void 0 || tokenHeader.jku !== void 0 || tokenHeader.jwk !== void 0 || tokenHeader.x5u !== void 0) throw denied();
3772
+ const untrusted = record(decodePart(tokenParts[1]));
3773
+ if (untrusted.auth_time !== void 0 && (!Number.isSafeInteger(untrusted.auth_time) || Number(untrusted.auth_time) < 0 || Number(untrusted.auth_time) > now + 30)) throw denied();
3774
+ if (untrusted.acr !== void 0 && (typeof untrusted.acr !== "string" || untrusted.acr.length > 128)) throw denied();
3775
+ if (untrusted.amr !== void 0 && (!Array.isArray(untrusted.amr) || untrusted.amr.length > 16 || untrusted.amr.some((method) => typeof method !== "string" || !/^[a-zA-Z0-9._:-]{1,64}$/.test(method)))) throw denied();
3776
+ if (typeof untrusted.client_id !== "string" || !clients.has(untrusted.client_id)) throw denied();
3777
+ let verified;
3778
+ try {
3779
+ verified = await verifyAccessToken({
3780
+ token,
3781
+ transport: options.transport,
3782
+ issuer: options.issuer,
3783
+ clientId: untrusted.client_id,
3784
+ dpopJkt: jkt,
3785
+ expectedScopes: [
3786
+ ...request.scopes ?? []
3787
+ ]
3788
+ });
3789
+ } catch (error) {
3790
+ if (error instanceof AccountError && error.retryable) throw unavailable();
3791
+ throw denied();
3792
+ }
3793
+ if (!verified.sub || verified.sub.length > 256 || !verified.sid || verified.sid.length > 256 || !Number.isSafeInteger(verified.auth_epoch) || verified.auth_epoch < 0 || typeof verified.scope !== "string" || verified.scope.length > 8192) throw denied();
3794
+ const claims = frozenClaims(verified);
3795
+ const active = /* @__PURE__ */ __name(async () => {
3796
+ if (claims.exp <= Math.floor(Date.now() / 1e3)) throw denied();
3797
+ let current;
3798
+ try {
3799
+ current = await options.sessionActive(claims, token);
3800
+ } catch {
3801
+ throw unavailable();
3802
+ }
3803
+ if (current !== true) throw denied();
3804
+ }, "active");
3805
+ await active();
3806
+ let consumed;
3807
+ try {
3808
+ consumed = await options.replayStore.consume({
3809
+ keyThumbprint: jkt,
3810
+ proofId: proof.jti,
3811
+ method: request.method,
3812
+ url,
3813
+ expiresAtMs: Math.min(claims.exp * 1e3, (Number(proof.iat) + 61) * 1e3)
3814
+ });
3815
+ } catch {
3816
+ throw unavailable();
3817
+ }
3818
+ if (consumed !== true) throw denied();
3819
+ await active();
3820
+ return Object.freeze({
3821
+ claims,
3822
+ revalidate: active
3823
+ });
3824
+ }
3825
+ };
3826
+ }
3827
+ __name(createResourceRequestAuthorizer, "createResourceRequestAuthorizer");
3828
+ function createOidcIntrospectionSessionAuthority(options) {
3829
+ const base2 = new URL(options.issuer);
3830
+ const timeoutMs = options.timeoutMs ?? 5e3;
3831
+ if (base2.origin !== options.issuer || base2.protocol !== "https:" || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3e4) throw new TypeError("Canonical HTTPS issuer and bounded introspection timeout required");
3832
+ const fetchImpl = options.fetchImpl ?? fetch;
3833
+ return async (claims, token) => {
3834
+ if (token.length > MAX_JWT_BYTES || !token) throw unavailable();
3835
+ const controller = new AbortController();
3836
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
3837
+ let response;
3838
+ try {
3839
+ response = await fetchBeforeAbort(fetchImpl, `${base2.origin}/api/oauth2/introspect`, {
3840
+ method: "POST",
3841
+ redirect: "error",
3842
+ cache: "no-store",
3843
+ credentials: "omit",
3844
+ signal: controller.signal,
3845
+ headers: {
3846
+ accept: "application/json",
3847
+ "content-type": "application/x-www-form-urlencoded"
3848
+ },
3849
+ body: new URLSearchParams({
3850
+ token
3851
+ }).toString()
3852
+ }, controller.signal);
3853
+ if (!response.ok || !response.body) throw unavailable();
3854
+ const value = parseJwtObject(await readBoundedText(response, controller.signal, 32768));
3855
+ if (value.active === false) return false;
3856
+ const canonicalAudience = Array.isArray(value.aud) ? value.aud.includes("xeno-api") : value.aud === "xeno-api";
3857
+ return value.active === true && value.token_type === "access_token" && value.iss === claims.iss && value.sub === claims.sub && value.sid === claims.sid && value.client_id === claims.client_id && value.exp === claims.exp && value.scope === claims.scope && canonicalAudience;
3858
+ } catch {
3859
+ throw unavailable();
3860
+ } finally {
3861
+ controller.abort();
3862
+ clearTimeout(timer);
3863
+ if (response) cancelBody(response);
3864
+ }
3865
+ };
3866
+ }
3867
+ __name(createOidcIntrospectionSessionAuthority, "createOidcIntrospectionSessionAuthority");
3868
+
3869
+ // src/index.ts
3870
+ var ACCOUNT_SDK_CONTRACT = Object.freeze({
3871
+ version: 1,
3872
+ workspaceAuthority: 1,
3873
+ workforceResourceOperations: 1,
3874
+ workforceActorBinding: 2,
3875
+ workforceOwnedCatalog: 1,
3876
+ workspaceKeyAuthority: 1,
3877
+ workspaceKeyOperations: 1,
3878
+ workspaceMembershipOperations: 1,
3879
+ workspaceOperationAbandonment: 1,
3880
+ accountOperations: 1,
3881
+ accountIntegrations: 1,
3882
+ notificationAuthority: 1,
3883
+ notificationDestinationOperations: 1,
3884
+ requestBoundAuthorization: 1,
3885
+ serializedRefresh: 1
3886
+ });
3887
+ export {
3888
+ ACCOUNT_SDK_CONTRACT,
3889
+ AccountClient,
3890
+ AccountError,
3891
+ AccountIntegrationClient,
3892
+ AccountMutationError,
3893
+ AuthzClient,
3894
+ BffSessionClient,
3895
+ LedgerClient,
3896
+ MICRO_PER_CREDIT,
3897
+ NotificationsClient,
3898
+ Transport,
3899
+ WorkforceClient,
3900
+ WorkforceResourceMutationError,
3901
+ WorkspaceClient,
3902
+ WorkspaceKeyMutationError,
3903
+ WorkspaceMembershipMutationError,
3904
+ XenoAccountClient,
3905
+ accountOperationIntentSchema,
3906
+ accountSchema,
3907
+ assertMembershipOperation,
3908
+ authzCheckSchema,
3909
+ authzResultSchema,
3910
+ balanceSchema,
3911
+ buildAuthorizeUrl,
3912
+ codeForStatus,
3913
+ createOidcIntrospectionSessionAuthority,
3914
+ createResourceRequestAuthorizer,
3915
+ exchangeCode,
3916
+ fromMicro,
3917
+ generatePkce,
3918
+ generateState,
3919
+ holdRequestSchema,
3920
+ holdSchema,
3921
+ keychainStore,
3922
+ membershipAbandonedSchema,
3923
+ membershipCommittedSchema,
3924
+ membershipDeliverySchema,
3925
+ membershipMutationSchema,
3926
+ membershipOperationSchema,
3927
+ membershipRejectedSchema,
3928
+ memoryStore,
3929
+ meterAggregationSchema,
3930
+ normalize,
3931
+ normalizeDpopHtu,
3932
+ notificationChannelSchema,
3933
+ notificationDestinationActionSchema,
3934
+ notificationDestinationOperationSchema,
3935
+ notificationEventSchema,
3936
+ notificationRuleSchema,
3937
+ notificationScopeSchema,
3938
+ notificationSettingsSchema,
3939
+ oauthTokenResponseSchema,
3940
+ pollDeviceToken,
3941
+ redact,
3942
+ refreshTokens,
3943
+ startDeviceAuthorization,
3944
+ surfaceSchema,
3945
+ toMicro,
3946
+ tokenSetSchema,
3947
+ usageEventSchema,
3948
+ usageResultSchema,
3949
+ verifyAccessToken,
3950
+ verifyIdToken,
3951
+ verifyLogoutToken,
3952
+ workforceCreateResourceSchema,
3953
+ workforceDefinitionSchema,
3954
+ workforceListOwnedResourcesSchema,
3955
+ workforceOwnerSchema,
3956
+ workforceReadOperationSchema,
3957
+ workspaceInviteRoleSchema,
3958
+ workspaceInviteSchema,
3959
+ workspaceKeyOperationSchema,
3960
+ workspaceKeyRejectionSchema,
3961
+ workspaceKeySchema,
3962
+ workspaceKeyScopeSchema,
3963
+ workspaceMemberSchema,
3964
+ workspaceRoleSchema,
3965
+ workspaceSchema
3966
+ };
3967
+ //# sourceMappingURL=index.mjs.map