primitive-admin 1.1.0-alpha.9 → 1.2.0-alpha.0

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 (609) hide show
  1. package/README.md +530 -116
  2. package/assets/skill/skills/primitive-platform/SKILL.md +295 -0
  3. package/dist/bin/primitive.d.ts +2 -0
  4. package/dist/bin/primitive.js +372 -21
  5. package/dist/bin/primitive.js.map +1 -1
  6. package/dist/src/commands/admins.d.ts +2 -0
  7. package/dist/src/commands/admins.js +136 -30
  8. package/dist/src/commands/admins.js.map +1 -1
  9. package/dist/src/commands/analytics.d.ts +2 -0
  10. package/dist/src/commands/analytics.js +713 -55
  11. package/dist/src/commands/analytics.js.map +1 -1
  12. package/dist/src/commands/apps.d.ts +2 -0
  13. package/dist/src/commands/apps.js +65 -100
  14. package/dist/src/commands/apps.js.map +1 -1
  15. package/dist/src/commands/auth-sessions.d.ts +7 -0
  16. package/dist/src/commands/auth-sessions.js +144 -0
  17. package/dist/src/commands/auth-sessions.js.map +1 -0
  18. package/dist/src/commands/auth.d.ts +2 -0
  19. package/dist/src/commands/auth.js +238 -108
  20. package/dist/src/commands/auth.js.map +1 -1
  21. package/dist/src/commands/blob-buckets.d.ts +2 -0
  22. package/dist/src/commands/blob-buckets.js +331 -0
  23. package/dist/src/commands/blob-buckets.js.map +1 -0
  24. package/dist/src/commands/catalog.d.ts +2 -0
  25. package/dist/src/commands/catalog.js +63 -48
  26. package/dist/src/commands/catalog.js.map +1 -1
  27. package/dist/src/commands/collection-type-configs.d.ts +2 -0
  28. package/dist/src/commands/collection-type-configs.js +85 -0
  29. package/dist/src/commands/collection-type-configs.js.map +1 -0
  30. package/dist/src/commands/collections.d.ts +2 -0
  31. package/dist/src/commands/collections.js +1285 -0
  32. package/dist/src/commands/collections.js.map +1 -0
  33. package/dist/src/commands/comparisons.d.ts +2 -0
  34. package/dist/src/commands/comparisons.js +6 -6
  35. package/dist/src/commands/comparisons.js.map +1 -1
  36. package/dist/src/commands/config.d.ts +46 -0
  37. package/dist/src/commands/config.js +465 -0
  38. package/dist/src/commands/config.js.map +1 -0
  39. package/dist/src/commands/connections.d.ts +2 -0
  40. package/dist/src/commands/connections.js +99 -0
  41. package/dist/src/commands/connections.js.map +1 -0
  42. package/dist/src/commands/cron-triggers.d.ts +2 -0
  43. package/dist/src/commands/cron-triggers.js +266 -0
  44. package/dist/src/commands/cron-triggers.js.map +1 -0
  45. package/dist/src/commands/database-type-configs.d.ts +2 -0
  46. package/dist/src/commands/database-type-configs.js +164 -0
  47. package/dist/src/commands/database-type-configs.js.map +1 -0
  48. package/dist/src/commands/database-types.d.ts +2 -0
  49. package/dist/src/commands/database-types.js +171 -0
  50. package/dist/src/commands/database-types.js.map +1 -0
  51. package/dist/src/commands/databases.d.ts +65 -0
  52. package/dist/src/commands/databases.js +1868 -243
  53. package/dist/src/commands/databases.js.map +1 -1
  54. package/dist/src/commands/documents.d.ts +60 -0
  55. package/dist/src/commands/documents.js +2888 -22
  56. package/dist/src/commands/documents.js.map +1 -1
  57. package/dist/src/commands/email-templates.d.ts +2 -0
  58. package/dist/src/commands/email-templates.js +175 -0
  59. package/dist/src/commands/email-templates.js.map +1 -0
  60. package/dist/src/commands/env.d.ts +23 -0
  61. package/dist/src/commands/env.js +395 -0
  62. package/dist/src/commands/env.js.map +1 -0
  63. package/dist/src/commands/feature-flags.d.ts +14 -0
  64. package/dist/src/commands/feature-flags.js +117 -0
  65. package/dist/src/commands/feature-flags.js.map +1 -0
  66. package/dist/src/commands/functions.d.ts +20 -0
  67. package/dist/src/commands/functions.js +1630 -0
  68. package/dist/src/commands/functions.js.map +1 -0
  69. package/dist/src/commands/group-type-configs.d.ts +2 -0
  70. package/dist/src/commands/group-type-configs.js +87 -0
  71. package/dist/src/commands/group-type-configs.js.map +1 -0
  72. package/dist/src/commands/groups.d.ts +2 -0
  73. package/dist/src/commands/groups.js +81 -113
  74. package/dist/src/commands/groups.js.map +1 -1
  75. package/dist/src/commands/guides.d.ts +223 -0
  76. package/dist/src/commands/guides.js +627 -69
  77. package/dist/src/commands/guides.js.map +1 -1
  78. package/dist/src/commands/init.d.ts +37 -0
  79. package/dist/src/commands/init.js +1693 -208
  80. package/dist/src/commands/init.js.map +1 -1
  81. package/dist/src/commands/integrations.d.ts +2 -0
  82. package/dist/src/commands/integrations.js +428 -187
  83. package/dist/src/commands/integrations.js.map +1 -1
  84. package/dist/src/commands/llm.d.ts +2 -0
  85. package/dist/src/commands/llm.js +13 -8
  86. package/dist/src/commands/llm.js.map +1 -1
  87. package/dist/src/commands/locks.d.ts +8 -0
  88. package/dist/src/commands/locks.js +175 -0
  89. package/dist/src/commands/locks.js.map +1 -0
  90. package/dist/src/commands/metadata-category-configs.d.ts +12 -0
  91. package/dist/src/commands/metadata-category-configs.js +113 -0
  92. package/dist/src/commands/metadata-category-configs.js.map +1 -0
  93. package/dist/src/commands/metadata.d.ts +2 -0
  94. package/dist/src/commands/metadata.js +288 -0
  95. package/dist/src/commands/metadata.js.map +1 -0
  96. package/dist/src/commands/prompts.d.ts +2 -0
  97. package/dist/src/commands/prompts.js +322 -634
  98. package/dist/src/commands/prompts.js.map +1 -1
  99. package/dist/src/commands/rule-sets.d.ts +3 -0
  100. package/dist/src/commands/rule-sets.js +139 -148
  101. package/dist/src/commands/rule-sets.js.map +1 -1
  102. package/dist/src/commands/scripts.d.ts +30 -0
  103. package/dist/src/commands/scripts.js +688 -0
  104. package/dist/src/commands/scripts.js.map +1 -0
  105. package/dist/src/commands/secrets.d.ts +2 -0
  106. package/dist/src/commands/secrets.js +109 -0
  107. package/dist/src/commands/secrets.js.map +1 -0
  108. package/dist/src/commands/sessions.d.ts +2 -0
  109. package/dist/src/commands/sessions.js +76 -0
  110. package/dist/src/commands/sessions.js.map +1 -0
  111. package/dist/src/commands/settings.d.ts +18 -0
  112. package/dist/src/commands/settings.js +54 -0
  113. package/dist/src/commands/settings.js.map +1 -0
  114. package/dist/src/commands/skill.d.ts +2 -0
  115. package/dist/src/commands/skill.js +29 -0
  116. package/dist/src/commands/skill.js.map +1 -0
  117. package/dist/src/commands/sync-app-settings.d.ts +158 -0
  118. package/dist/src/commands/sync-app-settings.js +328 -0
  119. package/dist/src/commands/sync-app-settings.js.map +1 -0
  120. package/dist/src/commands/sync.d.ts +2667 -0
  121. package/dist/src/commands/sync.js +17141 -834
  122. package/dist/src/commands/sync.js.map +1 -1
  123. package/dist/src/commands/tokens.d.ts +2 -0
  124. package/dist/src/commands/tokens.js +132 -22
  125. package/dist/src/commands/tokens.js.map +1 -1
  126. package/dist/src/commands/users.d.ts +2 -0
  127. package/dist/src/commands/users.js +542 -24
  128. package/dist/src/commands/users.js.map +1 -1
  129. package/dist/src/commands/vars.d.ts +8 -0
  130. package/dist/src/commands/vars.js +97 -0
  131. package/dist/src/commands/vars.js.map +1 -0
  132. package/dist/src/commands/waitlist.d.ts +2 -0
  133. package/dist/src/commands/waitlist.js +12 -11
  134. package/dist/src/commands/waitlist.js.map +1 -1
  135. package/dist/src/commands/webhooks.d.ts +31 -0
  136. package/dist/src/commands/webhooks.js +633 -0
  137. package/dist/src/commands/webhooks.js.map +1 -0
  138. package/dist/src/commands/workflows.d.ts +88 -0
  139. package/dist/src/commands/workflows.js +1568 -742
  140. package/dist/src/commands/workflows.js.map +1 -1
  141. package/dist/src/lib/access-rule-display.d.ts +21 -0
  142. package/dist/src/lib/access-rule-display.js +34 -0
  143. package/dist/src/lib/access-rule-display.js.map +1 -0
  144. package/dist/src/lib/api-client.d.ts +2513 -0
  145. package/dist/src/lib/api-client.js +2456 -162
  146. package/dist/src/lib/api-client.js.map +1 -1
  147. package/dist/src/lib/app-match-guard.d.ts +44 -0
  148. package/dist/src/lib/app-match-guard.js +72 -0
  149. package/dist/src/lib/app-match-guard.js.map +1 -0
  150. package/dist/src/lib/app-settings-descriptor.d.ts +263 -0
  151. package/dist/src/lib/app-settings-descriptor.js +583 -0
  152. package/dist/src/lib/app-settings-descriptor.js.map +1 -0
  153. package/dist/src/lib/auth-flow.d.ts +8 -0
  154. package/dist/src/lib/batch.d.ts +26 -0
  155. package/dist/src/lib/batch.js +32 -0
  156. package/dist/src/lib/batch.js.map +1 -0
  157. package/dist/src/lib/block-layout.d.ts +160 -0
  158. package/dist/src/lib/block-layout.js +451 -0
  159. package/dist/src/lib/block-layout.js.map +1 -0
  160. package/dist/src/lib/block-selector.d.ts +58 -0
  161. package/dist/src/lib/block-selector.js +92 -0
  162. package/dist/src/lib/block-selector.js.map +1 -0
  163. package/dist/src/lib/canonical-json.d.ts +12 -0
  164. package/dist/src/lib/canonical-json.js +35 -0
  165. package/dist/src/lib/canonical-json.js.map +1 -0
  166. package/dist/src/lib/channel.d.ts +30 -0
  167. package/dist/src/lib/channel.js +68 -0
  168. package/dist/src/lib/channel.js.map +1 -0
  169. package/dist/src/lib/cli-manifest.d.ts +68 -0
  170. package/dist/src/lib/cli-manifest.js +71 -0
  171. package/dist/src/lib/cli-manifest.js.map +1 -0
  172. package/dist/src/lib/codegen-shared/generatedFiles.d.ts +101 -0
  173. package/dist/src/lib/codegen-shared/generatedFiles.js +191 -0
  174. package/dist/src/lib/codegen-shared/generatedFiles.js.map +1 -0
  175. package/dist/src/lib/codegen-shared/prettierStable.d.ts +262 -0
  176. package/dist/src/lib/codegen-shared/prettierStable.js +610 -0
  177. package/dist/src/lib/codegen-shared/prettierStable.js.map +1 -0
  178. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.d.ts +38 -0
  179. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js +46 -0
  180. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js.map +1 -0
  181. package/dist/src/lib/collection-export.d.ts +212 -0
  182. package/dist/src/lib/collection-export.js +288 -0
  183. package/dist/src/lib/collection-export.js.map +1 -0
  184. package/dist/src/lib/config-json-field.d.ts +28 -0
  185. package/dist/src/lib/config-json-field.js +56 -0
  186. package/dist/src/lib/config-json-field.js.map +1 -0
  187. package/dist/src/lib/config-object-descriptor.d.ts +127 -0
  188. package/dist/src/lib/config-object-descriptor.js +740 -0
  189. package/dist/src/lib/config-object-descriptor.js.map +1 -0
  190. package/dist/src/lib/config-payload.d.ts +92 -0
  191. package/dist/src/lib/config-payload.js +161 -0
  192. package/dist/src/lib/config-payload.js.map +1 -0
  193. package/dist/src/lib/config-surface.d.ts +141 -0
  194. package/dist/src/lib/config-surface.js +368 -0
  195. package/dist/src/lib/config-surface.js.map +1 -0
  196. package/dist/src/lib/config-toml.d.ts +10 -0
  197. package/dist/src/lib/config-toml.js +42 -0
  198. package/dist/src/lib/config-toml.js.map +1 -0
  199. package/dist/src/lib/config.d.ts +71 -0
  200. package/dist/src/lib/config.js +71 -68
  201. package/dist/src/lib/config.js.map +1 -1
  202. package/dist/src/lib/confirm-prompt.d.ts +83 -0
  203. package/dist/src/lib/confirm-prompt.js +110 -0
  204. package/dist/src/lib/confirm-prompt.js.map +1 -0
  205. package/dist/src/lib/constants.d.ts +11 -0
  206. package/dist/src/lib/constants.js +12 -0
  207. package/dist/src/lib/constants.js.map +1 -0
  208. package/dist/src/lib/crash-handlers.d.ts +20 -0
  209. package/dist/src/lib/crash-handlers.js +49 -0
  210. package/dist/src/lib/crash-handlers.js.map +1 -0
  211. package/dist/src/lib/credentials-store.d.ts +104 -0
  212. package/dist/src/lib/credentials-store.js +336 -0
  213. package/dist/src/lib/credentials-store.js.map +1 -0
  214. package/dist/src/lib/csv.d.ts +47 -0
  215. package/dist/src/lib/csv.js +172 -0
  216. package/dist/src/lib/csv.js.map +1 -0
  217. package/dist/src/lib/data-input.d.ts +23 -0
  218. package/dist/src/lib/data-input.js +50 -0
  219. package/dist/src/lib/data-input.js.map +1 -0
  220. package/dist/src/lib/db-codegen/dbFingerprint.d.ts +10 -0
  221. package/dist/src/lib/db-codegen/dbFingerprint.js +17 -0
  222. package/dist/src/lib/db-codegen/dbFingerprint.js.map +1 -0
  223. package/dist/src/lib/db-codegen/dbGenerator.d.ts +67 -0
  224. package/dist/src/lib/db-codegen/dbGenerator.js +170 -0
  225. package/dist/src/lib/db-codegen/dbGenerator.js.map +1 -0
  226. package/dist/src/lib/db-codegen/dbNaming.d.ts +87 -0
  227. package/dist/src/lib/db-codegen/dbNaming.js +180 -0
  228. package/dist/src/lib/db-codegen/dbNaming.js.map +1 -0
  229. package/dist/src/lib/db-codegen/dbTemplates.d.ts +272 -0
  230. package/dist/src/lib/db-codegen/dbTemplates.js +480 -0
  231. package/dist/src/lib/db-codegen/dbTemplates.js.map +1 -0
  232. package/dist/src/lib/db-codegen/dbTsTypes.d.ts +73 -0
  233. package/dist/src/lib/db-codegen/dbTsTypes.js +139 -0
  234. package/dist/src/lib/db-codegen/dbTsTypes.js.map +1 -0
  235. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +146 -0
  236. package/dist/src/lib/db-codegen/dbTypeIR.js +525 -0
  237. package/dist/src/lib/db-codegen/dbTypeIR.js.map +1 -0
  238. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.d.ts +112 -0
  239. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.js +211 -0
  240. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.js.map +1 -0
  241. package/dist/src/lib/deprecation.d.ts +22 -0
  242. package/dist/src/lib/deprecation.js +43 -0
  243. package/dist/src/lib/deprecation.js.map +1 -0
  244. package/dist/src/lib/document-export-permissions.d.ts +30 -0
  245. package/dist/src/lib/document-export-permissions.js +54 -0
  246. package/dist/src/lib/document-export-permissions.js.map +1 -0
  247. package/dist/src/lib/document-ingest-artifact.d.ts +120 -0
  248. package/dist/src/lib/document-ingest-artifact.js +505 -0
  249. package/dist/src/lib/document-ingest-artifact.js.map +1 -0
  250. package/dist/src/lib/document-ingest-input.d.ts +51 -0
  251. package/dist/src/lib/document-ingest-input.js +132 -0
  252. package/dist/src/lib/document-ingest-input.js.map +1 -0
  253. package/dist/src/lib/document-ingest-rows.d.ts +137 -0
  254. package/dist/src/lib/document-ingest-rows.js +181 -0
  255. package/dist/src/lib/document-ingest-rows.js.map +1 -0
  256. package/dist/src/lib/document-ingest.d.ts +101 -0
  257. package/dist/src/lib/document-ingest.js +384 -0
  258. package/dist/src/lib/document-ingest.js.map +1 -0
  259. package/dist/src/lib/env-resolver-core.d.ts +258 -0
  260. package/dist/src/lib/env-resolver-core.js +447 -0
  261. package/dist/src/lib/env-resolver-core.js.map +1 -0
  262. package/dist/src/lib/env-resolver.d.ts +99 -0
  263. package/dist/src/lib/env-resolver.js +153 -0
  264. package/dist/src/lib/env-resolver.js.map +1 -0
  265. package/dist/src/lib/fetch.d.ts +5 -0
  266. package/dist/src/lib/function-bundle.d.ts +147 -0
  267. package/dist/src/lib/function-bundle.js +341 -0
  268. package/dist/src/lib/function-bundle.js.map +1 -0
  269. package/dist/src/lib/function-collect.d.ts +123 -0
  270. package/dist/src/lib/function-collect.js +610 -0
  271. package/dist/src/lib/function-collect.js.map +1 -0
  272. package/dist/src/lib/function-db-types.d.ts +202 -0
  273. package/dist/src/lib/function-db-types.js +870 -0
  274. package/dist/src/lib/function-db-types.js.map +1 -0
  275. package/dist/src/lib/function-document-types.d.ts +144 -0
  276. package/dist/src/lib/function-document-types.js +370 -0
  277. package/dist/src/lib/function-document-types.js.map +1 -0
  278. package/dist/src/lib/function-grants-preflight.d.ts +64 -0
  279. package/dist/src/lib/function-grants-preflight.js +105 -0
  280. package/dist/src/lib/function-grants-preflight.js.map +1 -0
  281. package/dist/src/lib/function-log-lines.d.ts +76 -0
  282. package/dist/src/lib/function-log-lines.js +160 -0
  283. package/dist/src/lib/function-log-lines.js.map +1 -0
  284. package/dist/src/lib/function-log-row.d.ts +29 -0
  285. package/dist/src/lib/function-log-row.js +73 -0
  286. package/dist/src/lib/function-log-row.js.map +1 -0
  287. package/dist/src/lib/function-log-tail.d.ts +132 -0
  288. package/dist/src/lib/function-log-tail.js +262 -0
  289. package/dist/src/lib/function-log-tail.js.map +1 -0
  290. package/dist/src/lib/function-run.d.ts +289 -0
  291. package/dist/src/lib/function-run.js +389 -0
  292. package/dist/src/lib/function-run.js.map +1 -0
  293. package/dist/src/lib/function-schema-codegen.d.ts +143 -0
  294. package/dist/src/lib/function-schema-codegen.js +420 -0
  295. package/dist/src/lib/function-schema-codegen.js.map +1 -0
  296. package/dist/src/lib/function-sync.d.ts +459 -0
  297. package/dist/src/lib/function-sync.js +1258 -0
  298. package/dist/src/lib/function-sync.js.map +1 -0
  299. package/dist/src/lib/function-trigger-listing.d.ts +27 -0
  300. package/dist/src/lib/function-trigger-listing.js +70 -0
  301. package/dist/src/lib/function-trigger-listing.js.map +1 -0
  302. package/dist/src/lib/function-triggers.d.ts +66 -0
  303. package/dist/src/lib/function-triggers.js +285 -0
  304. package/dist/src/lib/function-triggers.js.map +1 -0
  305. package/dist/src/lib/function-typecheck.d.ts +86 -0
  306. package/dist/src/lib/function-typecheck.js +370 -0
  307. package/dist/src/lib/function-typecheck.js.map +1 -0
  308. package/dist/src/lib/function-versions.d.ts +122 -0
  309. package/dist/src/lib/function-versions.js +182 -0
  310. package/dist/src/lib/function-versions.js.map +1 -0
  311. package/dist/src/lib/generated-allowlist.d.ts +28 -0
  312. package/dist/src/lib/generated-allowlist.js +280 -0
  313. package/dist/src/lib/generated-allowlist.js.map +1 -0
  314. package/dist/src/lib/generated-config-surfaces.d.ts +2936 -0
  315. package/dist/src/lib/generated-config-surfaces.js +10593 -0
  316. package/dist/src/lib/generated-config-surfaces.js.map +1 -0
  317. package/dist/src/lib/generated-sdk-types.d.ts +12 -0
  318. package/dist/src/lib/generated-sdk-types.js +13 -0
  319. package/dist/src/lib/generated-sdk-types.js.map +1 -0
  320. package/dist/src/lib/generated-template-lint.d.ts +212 -0
  321. package/dist/src/lib/generated-template-lint.js +624 -0
  322. package/dist/src/lib/generated-template-lint.js.map +1 -0
  323. package/dist/src/lib/generated-workflow-model-fields.d.ts +20 -0
  324. package/dist/src/lib/generated-workflow-model-fields.js +53 -0
  325. package/dist/src/lib/generated-workflow-model-fields.js.map +1 -0
  326. package/dist/src/lib/google-client-secret-status.d.ts +35 -0
  327. package/dist/src/lib/google-client-secret-status.js +56 -0
  328. package/dist/src/lib/google-client-secret-status.js.map +1 -0
  329. package/dist/src/lib/init-adopt.d.ts +16 -0
  330. package/dist/src/lib/init-adopt.js +34 -0
  331. package/dist/src/lib/init-adopt.js.map +1 -0
  332. package/dist/src/lib/init-assets.d.ts +39 -0
  333. package/dist/src/lib/init-assets.js +97 -0
  334. package/dist/src/lib/init-assets.js.map +1 -0
  335. package/dist/src/lib/init-client-platforms.d.ts +14 -0
  336. package/dist/src/lib/init-client-platforms.js +71 -0
  337. package/dist/src/lib/init-client-platforms.js.map +1 -0
  338. package/dist/src/lib/init-config.d.ts +98 -0
  339. package/dist/src/lib/init-config.js +186 -0
  340. package/dist/src/lib/init-config.js.map +1 -0
  341. package/dist/src/lib/init-email-redirect-uris.d.ts +37 -0
  342. package/dist/src/lib/init-email-redirect-uris.js +46 -0
  343. package/dist/src/lib/init-email-redirect-uris.js.map +1 -0
  344. package/dist/src/lib/init-ios-links.d.ts +91 -0
  345. package/dist/src/lib/init-ios-links.js +219 -0
  346. package/dist/src/lib/init-ios-links.js.map +1 -0
  347. package/dist/src/lib/init-plan.d.ts +80 -0
  348. package/dist/src/lib/init-plan.js +95 -0
  349. package/dist/src/lib/init-plan.js.map +1 -0
  350. package/dist/src/lib/init-production-env.d.ts +48 -0
  351. package/dist/src/lib/init-production-env.js +59 -0
  352. package/dist/src/lib/init-production-env.js.map +1 -0
  353. package/dist/src/lib/init-schema.d.ts +74 -0
  354. package/dist/src/lib/init-schema.js +358 -0
  355. package/dist/src/lib/init-schema.js.map +1 -0
  356. package/dist/src/lib/init-xcode.d.ts +34 -0
  357. package/dist/src/lib/init-xcode.js +138 -0
  358. package/dist/src/lib/init-xcode.js.map +1 -0
  359. package/dist/src/lib/integration-request-config.d.ts +30 -0
  360. package/dist/src/lib/integration-request-config.js +145 -0
  361. package/dist/src/lib/integration-request-config.js.map +1 -0
  362. package/dist/src/lib/integration-selector.d.ts +42 -0
  363. package/dist/src/lib/integration-selector.js +46 -0
  364. package/dist/src/lib/integration-selector.js.map +1 -0
  365. package/dist/src/lib/ios-app-id.d.ts +34 -0
  366. package/dist/src/lib/ios-app-id.js +69 -0
  367. package/dist/src/lib/ios-app-id.js.map +1 -0
  368. package/dist/src/lib/list-options.d.ts +68 -0
  369. package/dist/src/lib/list-options.js +89 -0
  370. package/dist/src/lib/list-options.js.map +1 -0
  371. package/dist/src/lib/local-state.d.ts +55 -0
  372. package/dist/src/lib/local-state.js +167 -0
  373. package/dist/src/lib/local-state.js.map +1 -0
  374. package/dist/src/lib/local-test-cases.d.ts +63 -0
  375. package/dist/src/lib/local-test-cases.js +136 -0
  376. package/dist/src/lib/local-test-cases.js.map +1 -0
  377. package/dist/src/lib/log-inspection.d.ts +710 -0
  378. package/dist/src/lib/log-inspection.js +814 -0
  379. package/dist/src/lib/log-inspection.js.map +1 -0
  380. package/dist/src/lib/logout-admin-session.d.ts +33 -0
  381. package/dist/src/lib/logout-admin-session.js +70 -0
  382. package/dist/src/lib/logout-admin-session.js.map +1 -0
  383. package/dist/src/lib/migration-nag.d.ts +49 -0
  384. package/dist/src/lib/migration-nag.js +164 -0
  385. package/dist/src/lib/migration-nag.js.map +1 -0
  386. package/dist/src/lib/object-status-filter.d.ts +22 -0
  387. package/dist/src/lib/object-status-filter.js +45 -0
  388. package/dist/src/lib/object-status-filter.js.map +1 -0
  389. package/dist/src/lib/output.d.ts +124 -0
  390. package/dist/src/lib/output.js +219 -8
  391. package/dist/src/lib/output.js.map +1 -1
  392. package/dist/src/lib/package-manager.d.ts +140 -0
  393. package/dist/src/lib/package-manager.js +305 -0
  394. package/dist/src/lib/package-manager.js.map +1 -0
  395. package/dist/src/lib/paginate.d.ts +82 -0
  396. package/dist/src/lib/paginate.js +99 -0
  397. package/dist/src/lib/paginate.js.map +1 -0
  398. package/dist/src/lib/platform-owned.d.ts +63 -0
  399. package/dist/src/lib/platform-owned.js +85 -0
  400. package/dist/src/lib/platform-owned.js.map +1 -0
  401. package/dist/src/lib/project-config.d.ts +122 -0
  402. package/dist/src/lib/project-config.js +244 -0
  403. package/dist/src/lib/project-config.js.map +1 -0
  404. package/dist/src/lib/prompt-cost-format.d.ts +11 -0
  405. package/dist/src/lib/prompt-cost-format.js +41 -0
  406. package/dist/src/lib/prompt-cost-format.js.map +1 -0
  407. package/dist/src/lib/prompt-schema-codegen.d.ts +147 -0
  408. package/dist/src/lib/prompt-schema-codegen.js +462 -0
  409. package/dist/src/lib/prompt-schema-codegen.js.map +1 -0
  410. package/dist/src/lib/query-operators.d.ts +43 -0
  411. package/dist/src/lib/query-operators.js +80 -0
  412. package/dist/src/lib/query-operators.js.map +1 -0
  413. package/dist/src/lib/record-filter.d.ts +18 -0
  414. package/dist/src/lib/record-filter.js +55 -0
  415. package/dist/src/lib/record-filter.js.map +1 -0
  416. package/dist/src/lib/refresh-admin-credentials.d.ts +73 -0
  417. package/dist/src/lib/refresh-admin-credentials.js +123 -0
  418. package/dist/src/lib/refresh-admin-credentials.js.map +1 -0
  419. package/dist/src/lib/resolve-init-dev-port.d.ts +56 -0
  420. package/dist/src/lib/resolve-init-dev-port.js +55 -0
  421. package/dist/src/lib/resolve-init-dev-port.js.map +1 -0
  422. package/dist/src/lib/resolve-init-server.d.ts +64 -0
  423. package/dist/src/lib/resolve-init-server.js +77 -0
  424. package/dist/src/lib/resolve-init-server.js.map +1 -0
  425. package/dist/src/lib/resolve-owner.d.ts +19 -0
  426. package/dist/src/lib/resolve-owner.js +20 -0
  427. package/dist/src/lib/resolve-owner.js.map +1 -0
  428. package/dist/src/lib/resolve-platform.d.ts +74 -0
  429. package/dist/src/lib/resolve-platform.js +105 -0
  430. package/dist/src/lib/resolve-platform.js.map +1 -0
  431. package/dist/src/lib/run-status.d.ts +19 -0
  432. package/dist/src/lib/run-status.generated.d.ts +39 -0
  433. package/dist/src/lib/run-status.generated.js +66 -0
  434. package/dist/src/lib/run-status.generated.js.map +1 -0
  435. package/dist/src/lib/run-status.js +19 -0
  436. package/dist/src/lib/run-status.js.map +1 -0
  437. package/dist/src/lib/server-text-normalization.d.ts +51 -0
  438. package/dist/src/lib/server-text-normalization.js +90 -0
  439. package/dist/src/lib/server-text-normalization.js.map +1 -0
  440. package/dist/src/lib/server-url.d.ts +22 -0
  441. package/dist/src/lib/server-url.js +33 -0
  442. package/dist/src/lib/server-url.js.map +1 -0
  443. package/dist/src/lib/signing-secret-status.d.ts +81 -0
  444. package/dist/src/lib/signing-secret-status.js +116 -0
  445. package/dist/src/lib/signing-secret-status.js.map +1 -0
  446. package/dist/src/lib/skill-installer.d.ts +71 -0
  447. package/dist/src/lib/skill-installer.js +441 -0
  448. package/dist/src/lib/skill-installer.js.map +1 -0
  449. package/dist/src/lib/snapshot-audit-source.d.ts +45 -0
  450. package/dist/src/lib/snapshot-audit-source.js +58 -0
  451. package/dist/src/lib/snapshot-audit-source.js.map +1 -0
  452. package/dist/src/lib/snapshot-audit-store.d.ts +52 -0
  453. package/dist/src/lib/snapshot-audit-store.js +196 -0
  454. package/dist/src/lib/snapshot-audit-store.js.map +1 -0
  455. package/dist/src/lib/snapshot-audit.d.ts +207 -0
  456. package/dist/src/lib/snapshot-audit.js +431 -0
  457. package/dist/src/lib/snapshot-audit.js.map +1 -0
  458. package/dist/src/lib/snapshot-build-rows.d.ts +60 -0
  459. package/dist/src/lib/snapshot-build-rows.js +87 -0
  460. package/dist/src/lib/snapshot-build-rows.js.map +1 -0
  461. package/dist/src/lib/snapshot-build.d.ts +50 -0
  462. package/dist/src/lib/snapshot-build.js +111 -0
  463. package/dist/src/lib/snapshot-build.js.map +1 -0
  464. package/dist/src/lib/snapshot-manifest-layout.d.ts +61 -0
  465. package/dist/src/lib/snapshot-manifest-layout.js +70 -0
  466. package/dist/src/lib/snapshot-manifest-layout.js.map +1 -0
  467. package/dist/src/lib/snapshots.d.ts +98 -0
  468. package/dist/src/lib/snapshots.js +294 -0
  469. package/dist/src/lib/snapshots.js.map +1 -0
  470. package/dist/src/lib/step-run-table.d.ts +43 -0
  471. package/dist/src/lib/step-run-table.js +129 -0
  472. package/dist/src/lib/step-run-table.js.map +1 -0
  473. package/dist/src/lib/storage-pending-retry.d.ts +26 -0
  474. package/dist/src/lib/storage-pending-retry.js +42 -0
  475. package/dist/src/lib/storage-pending-retry.js.map +1 -0
  476. package/dist/src/lib/swift-codegen/agentGenerator.d.ts +42 -0
  477. package/dist/src/lib/swift-codegen/agentGenerator.js +118 -0
  478. package/dist/src/lib/swift-codegen/agentGenerator.js.map +1 -0
  479. package/dist/src/lib/swift-codegen/banners.d.ts +24 -0
  480. package/dist/src/lib/swift-codegen/banners.js +25 -0
  481. package/dist/src/lib/swift-codegen/banners.js.map +1 -0
  482. package/dist/src/lib/swift-codegen/dbGenerator.d.ts +113 -0
  483. package/dist/src/lib/swift-codegen/dbGenerator.js +926 -0
  484. package/dist/src/lib/swift-codegen/dbGenerator.js.map +1 -0
  485. package/dist/src/lib/swift-codegen/dbSwiftTypes.d.ts +42 -0
  486. package/dist/src/lib/swift-codegen/dbSwiftTypes.js +100 -0
  487. package/dist/src/lib/swift-codegen/dbSwiftTypes.js.map +1 -0
  488. package/dist/src/lib/swift-codegen/functionGenerator.d.ts +139 -0
  489. package/dist/src/lib/swift-codegen/functionGenerator.js +462 -0
  490. package/dist/src/lib/swift-codegen/functionGenerator.js.map +1 -0
  491. package/dist/src/lib/swift-codegen/generator.d.ts +100 -0
  492. package/dist/src/lib/swift-codegen/generator.js +457 -0
  493. package/dist/src/lib/swift-codegen/generator.js.map +1 -0
  494. package/dist/src/lib/swift-codegen/schemaToSwift.d.ts +87 -0
  495. package/dist/src/lib/swift-codegen/schemaToSwift.js +661 -0
  496. package/dist/src/lib/swift-codegen/schemaToSwift.js.map +1 -0
  497. package/dist/src/lib/swift-codegen/siblingSymbols.d.ts +94 -0
  498. package/dist/src/lib/swift-codegen/siblingSymbols.js +155 -0
  499. package/dist/src/lib/swift-codegen/siblingSymbols.js.map +1 -0
  500. package/dist/src/lib/swift-codegen/swiftNaming.d.ts +85 -0
  501. package/dist/src/lib/swift-codegen/swiftNaming.js +198 -0
  502. package/dist/src/lib/swift-codegen/swiftNaming.js.map +1 -0
  503. package/dist/src/lib/sync-dir-selector.d.ts +21 -0
  504. package/dist/src/lib/sync-dir-selector.js +30 -0
  505. package/dist/src/lib/sync-dir-selector.js.map +1 -0
  506. package/dist/src/lib/sync-paths.d.ts +128 -0
  507. package/dist/src/lib/sync-paths.js +195 -0
  508. package/dist/src/lib/sync-paths.js.map +1 -0
  509. package/dist/src/lib/sync-resource-types.d.ts +563 -0
  510. package/dist/src/lib/sync-resource-types.js +1073 -0
  511. package/dist/src/lib/sync-resource-types.js.map +1 -0
  512. package/dist/src/lib/sync-selectors.d.ts +138 -0
  513. package/dist/src/lib/sync-selectors.js +289 -0
  514. package/dist/src/lib/sync-selectors.js.map +1 -0
  515. package/dist/src/lib/template.d.ts +170 -0
  516. package/dist/src/lib/template.js +484 -68
  517. package/dist/src/lib/template.js.map +1 -1
  518. package/dist/src/lib/test-case-file-names.d.ts +40 -0
  519. package/dist/src/lib/test-case-file-names.js +91 -0
  520. package/dist/src/lib/test-case-file-names.js.map +1 -0
  521. package/dist/src/lib/test-case-keys.d.ts +29 -0
  522. package/dist/src/lib/test-case-keys.js +55 -0
  523. package/dist/src/lib/test-case-keys.js.map +1 -0
  524. package/dist/src/lib/test-case-variables.d.ts +29 -0
  525. package/dist/src/lib/test-case-variables.js +71 -0
  526. package/dist/src/lib/test-case-variables.js.map +1 -0
  527. package/dist/src/lib/token-inject.d.ts +56 -0
  528. package/dist/src/lib/token-inject.js +204 -0
  529. package/dist/src/lib/token-inject.js.map +1 -0
  530. package/dist/src/lib/toml-database-config.d.ts +123 -0
  531. package/dist/src/lib/toml-database-config.js +544 -0
  532. package/dist/src/lib/toml-database-config.js.map +1 -0
  533. package/dist/src/lib/toml-metadata-config.d.ts +151 -0
  534. package/dist/src/lib/toml-metadata-config.js +476 -0
  535. package/dist/src/lib/toml-metadata-config.js.map +1 -0
  536. package/dist/src/lib/toml-native-form.d.ts +46 -0
  537. package/dist/src/lib/toml-native-form.js +78 -0
  538. package/dist/src/lib/toml-native-form.js.map +1 -0
  539. package/dist/src/lib/toml-params-validator.d.ts +129 -0
  540. package/dist/src/lib/toml-params-validator.js +298 -0
  541. package/dist/src/lib/toml-params-validator.js.map +1 -0
  542. package/dist/src/lib/toml-scalar-edit.d.ts +43 -0
  543. package/dist/src/lib/toml-scalar-edit.js +283 -0
  544. package/dist/src/lib/toml-scalar-edit.js.map +1 -0
  545. package/dist/src/lib/user-selector.d.ts +24 -0
  546. package/dist/src/lib/user-selector.js +33 -0
  547. package/dist/src/lib/user-selector.js.map +1 -0
  548. package/dist/src/lib/version-check.d.ts +35 -0
  549. package/dist/src/lib/version-check.js +241 -0
  550. package/dist/src/lib/version-check.js.map +1 -0
  551. package/dist/src/lib/watch.d.ts +121 -0
  552. package/dist/src/lib/watch.js +169 -0
  553. package/dist/src/lib/watch.js.map +1 -0
  554. package/dist/src/lib/web-url.d.ts +40 -0
  555. package/dist/src/lib/web-url.js +76 -0
  556. package/dist/src/lib/web-url.js.map +1 -0
  557. package/dist/src/lib/webhook-deliver.d.ts +209 -0
  558. package/dist/src/lib/webhook-deliver.js +519 -0
  559. package/dist/src/lib/webhook-deliver.js.map +1 -0
  560. package/dist/src/lib/workflow-apply.d.ts +110 -0
  561. package/dist/src/lib/workflow-apply.js +164 -0
  562. package/dist/src/lib/workflow-apply.js.map +1 -0
  563. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.d.ts +129 -0
  564. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.js +269 -0
  565. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.js.map +1 -0
  566. package/dist/src/lib/workflow-codegen/generator.d.ts +96 -0
  567. package/dist/src/lib/workflow-codegen/generator.js +361 -0
  568. package/dist/src/lib/workflow-codegen/generator.js.map +1 -0
  569. package/dist/src/lib/workflow-codegen/invokerIR.d.ts +94 -0
  570. package/dist/src/lib/workflow-codegen/invokerIR.js +76 -0
  571. package/dist/src/lib/workflow-codegen/invokerIR.js.map +1 -0
  572. package/dist/src/lib/workflow-codegen/naming.d.ts +33 -0
  573. package/dist/src/lib/workflow-codegen/naming.js +81 -0
  574. package/dist/src/lib/workflow-codegen/naming.js.map +1 -0
  575. package/dist/src/lib/workflow-codegen/schemaToTs.d.ts +80 -0
  576. package/dist/src/lib/workflow-codegen/schemaToTs.js +303 -0
  577. package/dist/src/lib/workflow-codegen/schemaToTs.js.map +1 -0
  578. package/dist/src/lib/workflow-config-apply.d.ts +70 -0
  579. package/dist/src/lib/workflow-config-apply.js +137 -0
  580. package/dist/src/lib/workflow-config-apply.js.map +1 -0
  581. package/dist/src/lib/workflow-config-sidecar.d.ts +63 -0
  582. package/dist/src/lib/workflow-config-sidecar.js +96 -0
  583. package/dist/src/lib/workflow-config-sidecar.js.map +1 -0
  584. package/dist/src/lib/workflow-defaults.d.ts +29 -0
  585. package/dist/src/lib/workflow-defaults.js +41 -0
  586. package/dist/src/lib/workflow-defaults.js.map +1 -0
  587. package/dist/src/lib/workflow-field-descriptor.d.ts +91 -0
  588. package/dist/src/lib/workflow-field-descriptor.js +153 -0
  589. package/dist/src/lib/workflow-field-descriptor.js.map +1 -0
  590. package/dist/src/lib/workflow-fragments.d.ts +64 -0
  591. package/dist/src/lib/workflow-fragments.js +342 -0
  592. package/dist/src/lib/workflow-fragments.js.map +1 -0
  593. package/dist/src/lib/workflow-include-preserve.d.ts +76 -0
  594. package/dist/src/lib/workflow-include-preserve.js +286 -0
  595. package/dist/src/lib/workflow-include-preserve.js.map +1 -0
  596. package/dist/src/lib/workflow-payload.d.ts +98 -0
  597. package/dist/src/lib/workflow-payload.js +178 -0
  598. package/dist/src/lib/workflow-payload.js.map +1 -0
  599. package/dist/src/lib/workflow-toml-validator.d.ts +211 -0
  600. package/dist/src/lib/workflow-toml-validator.js +770 -0
  601. package/dist/src/lib/workflow-toml-validator.js.map +1 -0
  602. package/dist/src/lib/workflow-usage.d.ts +196 -0
  603. package/dist/src/lib/workflow-usage.js +310 -0
  604. package/dist/src/lib/workflow-usage.js.map +1 -0
  605. package/dist/src/types/index.d.ts +591 -0
  606. package/dist/src/validators.d.ts +65 -0
  607. package/dist/src/validators.js +64 -0
  608. package/dist/src/validators.js.map +1 -0
  609. package/package.json +34 -9
@@ -1,36 +1,266 @@
1
1
  import { loadCredentials, saveCredentials, isTokenExpiringSoon, } from "./config.js";
2
+ import { getCurrentEnvNameSafe } from "./env-resolver.js";
2
3
  import { fetchWithTLS } from "./fetch.js";
4
+ import { paginateAll, normalizeCliListEnvelope } from "./paginate.js";
5
+ import { RefreshError, refreshAdminCredentials, } from "./refresh-admin-credentials.js";
6
+ import { drainAppsUntilConverged, } from "./workflow-usage.js";
7
+ /**
8
+ * Page size the admin per-user inventories are asked for (#3399).
9
+ *
10
+ * `MAX_LIST_LIMIT` on the server, so a heavy user's inventory is walked in the
11
+ * fewest round trips the contract allows; a larger value is clamped there.
12
+ */
13
+ const ADMIN_INVENTORY_PAGE_SIZE = 100;
3
14
  export class ApiError extends Error {
4
15
  statusCode;
5
16
  code;
6
- constructor(message, statusCode, code) {
17
+ /**
18
+ * Structured `details` payload from `corsErrorResponse`.
19
+ *
20
+ * The server's error envelope can emit `details` as either:
21
+ * - an array of validation issues (e.g. `[{ path, message }, ...]`) —
22
+ * this is what most legacy endpoints produce, and what sync.ts walks
23
+ * via `Array.isArray(err.details)` / `for (const detail of ...)`.
24
+ * - a record of structured offender fields (e.g. `{ refs, operations,
25
+ * opCount, line, column, ... }`) — emitted by the issue #666 schema
26
+ * gate and consumed by the typed exception subclasses below.
27
+ *
28
+ * Callers must narrow before use: `Array.isArray(err.details)` for the
29
+ * legacy shape, otherwise treat as `Record<string, any>`.
30
+ */
31
+ details;
32
+ constructor(message, statusCode, code, details) {
7
33
  super(message);
8
34
  this.statusCode = statusCode;
9
35
  this.code = code;
10
36
  this.name = "ApiError";
37
+ if (details !== undefined) {
38
+ this.details = details;
39
+ }
11
40
  }
12
41
  }
13
42
  export class ConflictError extends ApiError {
14
43
  serverModifiedAt;
15
44
  expectedModifiedAt;
16
- constructor(message, serverModifiedAt, expectedModifiedAt) {
17
- super(message, 409, "CONFLICT");
45
+ constructor(message, serverModifiedAt, expectedModifiedAt, details) {
46
+ super(message, 409, "CONFLICT", details);
18
47
  this.serverModifiedAt = serverModifiedAt;
19
48
  this.expectedModifiedAt = expectedModifiedAt;
20
49
  this.name = "ConflictError";
21
50
  }
22
51
  }
52
+ /**
53
+ * The `ApiError` for a non-OK response read by a raw `fetch` call (#3403).
54
+ *
55
+ * The blob methods and the two document-artifact transfers build their own
56
+ * `fetch` call, so they never reached `parseErrorResponse` and never carried a
57
+ * `code` — a download refusal surfaced as `response.statusText` and an upload
58
+ * refusal as the raw JSON body shown to the operator as the message. This
59
+ * routes them through the same parser every other call site uses while keeping
60
+ * their human prefixes.
61
+ *
62
+ * Named for the blob paths it was written for; every raw-`fetch` path in this
63
+ * file answers through it now.
64
+ */
65
+ export async function blobFailure(response, prefix) {
66
+ const text = await response.text().catch(() => "");
67
+ const parsed = parseErrorResponse(response, text);
68
+ return new ApiError(`${prefix}${parsed.message}`, response.status, parsed.code, parsed.details);
69
+ }
70
+ /**
71
+ * Extract a human-readable error message + structured fields from a non-OK
72
+ * HTTP response body. Single source of truth used by every error-handler call
73
+ * site in this file (see issue #684).
74
+ */
75
+ export function parseErrorResponse(response, text, path) {
76
+ // Empty body → fall back to status code.
77
+ if (!text) {
78
+ return { message: `HTTP ${response.status}` };
79
+ }
80
+ let errorData;
81
+ try {
82
+ errorData = JSON.parse(text);
83
+ }
84
+ catch {
85
+ // Non-JSON body. Surface the existing `<!DOCTYPE` special-case (an HTML
86
+ // 404 page from hitting the wrong path) so we don't regress the helpful
87
+ // "API endpoint not found" message at api-client.ts:343.
88
+ if (text.includes("<!DOCTYPE")) {
89
+ const where = path ? `: ${path}` : "";
90
+ return {
91
+ message: `API endpoint not found${where}. Make sure the server is running.`,
92
+ htmlNotFound: true,
93
+ };
94
+ }
95
+ // Other non-JSON bodies (e.g. plain-text 502 from a proxy) — surface the
96
+ // raw text so the operator at least sees what the server returned.
97
+ return { message: text };
98
+ }
99
+ // Server's standard envelope uses `error`; ConflictError + integrations
100
+ // proxy use `message`. Prefer `error` (more common), fall back to `message`.
101
+ const message = (typeof errorData?.error === "string" && errorData.error) ||
102
+ (typeof errorData?.message === "string" && errorData.message) ||
103
+ `HTTP ${response.status}`;
104
+ // Per issue #666 addendum A1, `code` may be at the top level or nested
105
+ // under `details.code` when the server's bespoke envelope didn't flatten.
106
+ const code = (typeof errorData?.code === "string" ? errorData.code : undefined) ??
107
+ (typeof errorData?.details?.code === "string"
108
+ ? errorData.details.code
109
+ : undefined);
110
+ // Accept either an array (legacy) or a plain object (#666 schema gate).
111
+ const details = Array.isArray(errorData?.details)
112
+ ? errorData.details
113
+ : errorData?.details && typeof errorData.details === "object"
114
+ ? errorData.details
115
+ : undefined;
116
+ return { message, code, details, raw: errorData };
117
+ }
118
+ /**
119
+ * Typed exception classes for the database-schema feature (issue #666).
120
+ * Each maps 1:1 to a server `code` value emitted from the op-edit or
121
+ * schema-edit gate. They all extend ApiError so existing catch-all paths
122
+ * continue to work; specialized catch blocks can branch on `instanceof`.
123
+ *
124
+ * Per round-2 addendum A1, `details` is always preserved so callers can
125
+ * extract structured offender lists (refs[], operations[], etc.).
126
+ */
127
+ export class SchemaRequiredError extends ApiError {
128
+ constructor(message, details) {
129
+ super(message, 422, "SCHEMA_REQUIRED", details);
130
+ this.name = "SchemaRequiredError";
131
+ }
132
+ }
133
+ function detailsRecord(details) {
134
+ return details && !Array.isArray(details) && typeof details === "object"
135
+ ? details
136
+ : undefined;
137
+ }
138
+ export class OperationRefError extends ApiError {
139
+ constructor(message, details) {
140
+ super(message, 422, "OPERATION_REFERENCES_UNDEFINED", details);
141
+ this.name = "OperationRefError";
142
+ }
143
+ get refs() {
144
+ const d = detailsRecord(this.details);
145
+ return Array.isArray(d?.refs) ? d.refs : [];
146
+ }
147
+ }
148
+ export class SchemaBreaksOpsError extends ApiError {
149
+ constructor(message, details) {
150
+ super(message, 422, "SCHEMA_BREAKS_OPERATIONS", details);
151
+ this.name = "SchemaBreaksOpsError";
152
+ }
153
+ get operations() {
154
+ const d = detailsRecord(this.details);
155
+ return Array.isArray(d?.operations) ? d.operations : [];
156
+ }
157
+ }
158
+ export class SchemaHasUncheckableOpsError extends ApiError {
159
+ constructor(message, details) {
160
+ super(message, 422, "SCHEMA_HAS_UNCHECKABLE_OPS", details);
161
+ this.name = "SchemaHasUncheckableOpsError";
162
+ }
163
+ get operations() {
164
+ const d = detailsRecord(this.details);
165
+ return Array.isArray(d?.operations) ? d.operations : [];
166
+ }
167
+ }
168
+ export class TomlParseError extends ApiError {
169
+ constructor(message, details) {
170
+ super(message, 400, "TOML_PARSE_ERROR", details);
171
+ this.name = "TomlParseError";
172
+ }
173
+ get line() {
174
+ const d = detailsRecord(this.details);
175
+ return typeof d?.line === "number" ? d.line : undefined;
176
+ }
177
+ get column() {
178
+ const d = detailsRecord(this.details);
179
+ return typeof d?.column === "number" ? d.column : undefined;
180
+ }
181
+ }
182
+ export class OpsExistError extends ApiError {
183
+ constructor(message, details) {
184
+ super(message, 409, "OPS_EXIST", details);
185
+ this.name = "OpsExistError";
186
+ }
187
+ get opCount() {
188
+ const d = detailsRecord(this.details);
189
+ return typeof d?.opCount === "number" ? d.opCount : 0;
190
+ }
191
+ }
192
+ /**
193
+ * Normalize a `databases operations execute` result to the CLI's one list
194
+ * envelope — but only when the result is a Durable Object query page
195
+ * (issue #2440).
196
+ *
197
+ * A registered operation is a list only sometimes. Of the shapes the server's
198
+ * operation dispatch can return, exactly two carry a top-level `data` array: a
199
+ * bare `query` and a `pipeline` whose `returnField` names a query step. A
200
+ * `count` (`{ count }`), an `aggregate` (`{ result }`), a mutation
201
+ * (`{ results }`), an `applyToQuery` (`{ matched, affected, failed, … }`) and a
202
+ * `returnField: "all"` pipeline (`{ steps: { … } }`) do not, so blanket
203
+ * normalization would corrupt them. This helper therefore tests the shape
204
+ * first and passes everything else through byte-for-byte — including the
205
+ * nested steps of a `returnField: "all"` pipeline, which are operation-defined
206
+ * objects the CLI must not reach into.
207
+ *
208
+ * Deliberately narrow, not a general-purpose predicate: the contract is
209
+ * specifically "an operations-execute result may be a DO query page".
210
+ * `executeDatabaseOperation()` is the only caller.
211
+ *
212
+ * The conversion itself is delegated to `normalizeCliListEnvelope()` so cursor
213
+ * handling, `prevCursor` dropping and `hasMore` derivation have exactly one
214
+ * implementation. That helper throws on an unrecognized shape — correct when
215
+ * the payload is supposed to be a list, wrong here, where the payload is the
216
+ * caller's own result — which is why the shape test has to run first. `_timing`
217
+ * (`--timing`) is re-attached afterwards, since it rides alongside the envelope
218
+ * rather than inside it.
219
+ */
220
+ export function normalizeDatabaseOperationResult(raw) {
221
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
222
+ return raw;
223
+ const page = raw;
224
+ if (!Array.isArray(page.data))
225
+ return raw;
226
+ const envelope = normalizeCliListEnvelope(page);
227
+ if (page._timing !== undefined)
228
+ envelope._timing = page._timing;
229
+ return envelope;
230
+ }
23
231
  export class ApiClient {
232
+ /**
233
+ * Loaded on first use (`ensureAuthenticated`), never in a constructor.
234
+ *
235
+ * There used to be an `apiClient` singleton constructed at MODULE scope, so
236
+ * a constructor body ran while `bin/primitive.ts` was still being imported —
237
+ * before its first `try`, and before any command had said whether it needed
238
+ * the project at all. `loadCredentials()` resolves the environment, so on a
239
+ * project still holding the pre-#3153 layout that read threw the stale-layout
240
+ * refusal out of module evaluation, where not even the `uncaughtException`
241
+ * handler can reach it: the user got Node's raw stack trace, and `guides
242
+ * get` — which reads nothing from the project — died with it (#3273). The
243
+ * singleton is gone (#3154, it had no callers) and the read stays lazy,
244
+ * which is what keeps that shape from coming back.
245
+ *
246
+ * Nothing is lost by waiting, and one thing is gained: a `login` earlier in
247
+ * the same process is visible to a later request.
248
+ */
24
249
  credentials = null;
25
- constructor() {
26
- this.credentials = loadCredentials();
27
- }
28
250
  async ensureAuthenticated() {
29
251
  if (!this.credentials) {
30
252
  this.credentials = loadCredentials();
31
253
  }
32
254
  if (!this.credentials) {
33
- throw new ApiError("Not logged in. Run 'bao-admin login' first.", 401);
255
+ // Name the environment when there is one (#1293). Before #3152 this case
256
+ // surfaced from `resolveAppId`, because an unauthenticated environment
257
+ // resolved no app at all; now the environment always names its app, so
258
+ // "not logged in" is only ever an auth failure, and it is reported here,
259
+ // once, for every command.
260
+ const envName = getCurrentEnvNameSafe();
261
+ throw new ApiError(envName
262
+ ? `Not logged in to environment "${envName}". Run 'primitive -e ${envName} login'.`
263
+ : "Not logged in. Run 'primitive login' first.", 401);
34
264
  }
35
265
  // Check if token needs refresh
36
266
  if (isTokenExpiringSoon(this.credentials)) {
@@ -39,39 +269,27 @@ export class ApiClient {
39
269
  return this.credentials;
40
270
  }
41
271
  async refreshToken() {
42
- if (!this.credentials?.refreshToken) {
43
- throw new ApiError("No refresh token available. Please login again.", 401);
272
+ if (!this.credentials) {
273
+ throw new ApiError("Not logged in. Run 'primitive login' first.", 401);
44
274
  }
45
- const url = `${this.credentials.serverUrl}/admin/api/auth/refresh`;
46
275
  try {
47
- const headers = {
48
- "Content-Type": "application/json",
49
- };
50
- if (this.credentials.globalAdminAppId) {
51
- headers["X-Global-Admin-App-Id"] = this.credentials.globalAdminAppId;
52
- }
53
- const response = await fetchWithTLS(url, {
54
- method: "POST",
55
- headers,
56
- body: JSON.stringify({ refreshToken: this.credentials.refreshToken }),
57
- });
58
- if (!response.ok) {
59
- throw new ApiError("Token refresh failed. Please login again.", 401);
60
- }
61
- const data = await response.json();
62
- // Update credentials with new tokens
63
- this.credentials = {
64
- ...this.credentials,
65
- accessToken: data.accessToken || data.token,
66
- refreshToken: data.refreshToken || this.credentials.refreshToken,
67
- expiresAt: data.expiresAt,
68
- };
276
+ const updated = await refreshAdminCredentials(this.credentials);
277
+ this.credentials = updated;
69
278
  saveCredentials(this.credentials);
70
279
  }
71
- catch (error) {
72
- if (error instanceof ApiError)
73
- throw error;
74
- throw new ApiError("Token refresh failed. Please login again.", 401);
280
+ catch (err) {
281
+ if (err instanceof RefreshError) {
282
+ // Preserve historical behavior: ApiClient surfaces refresh failures
283
+ // as 401s regardless of whether the underlying cause was a network
284
+ // error or a server-side rejection. Callers that need a finer
285
+ // distinction (e.g. `primitive token`) consume RefreshError directly
286
+ // from refresh-admin-credentials.ts instead of going through here.
287
+ // A revoked session (#3885) says so.
288
+ throw new ApiError(err.code === "SESSION_REVOKED"
289
+ ? err.message
290
+ : "Token refresh failed. Please login again.", 401, err.code);
291
+ }
292
+ throw err;
75
293
  }
76
294
  }
77
295
  async request(path, options = {}) {
@@ -92,20 +310,42 @@ export class ApiClient {
92
310
  });
93
311
  const text = await response.text();
94
312
  if (!response.ok) {
95
- let errorData;
96
- try {
97
- errorData = JSON.parse(text);
313
+ const parsed = parseErrorResponse(response, text, path);
314
+ // Preserve the `<!DOCTYPE` → 404 ApiError shape (status forced to 404).
315
+ if (parsed.htmlNotFound) {
316
+ throw new ApiError(parsed.message, 404);
98
317
  }
99
- catch {
100
- if (text.includes("<!DOCTYPE")) {
101
- throw new ApiError(`API endpoint not found: ${path}. Make sure the server is running.`, 404);
102
- }
103
- errorData = { message: text || `HTTP ${response.status}` };
318
+ // Narrow details to the record shape for the issue #666 typed-exception
319
+ // dispatch below. Conflict metadata may live under `details.*` (canonical
320
+ // location per A1) or on the top-level envelope (legacy).
321
+ const detailsRecord = parsed.details && !Array.isArray(parsed.details)
322
+ ? parsed.details
323
+ : undefined;
324
+ const serverModifiedAt = detailsRecord?.serverModifiedAt ?? parsed.raw?.serverModifiedAt;
325
+ const expectedModifiedAt = detailsRecord?.expectedModifiedAt ?? parsed.raw?.expectedModifiedAt;
326
+ // Typed exceptions for the schema-feature (issue #666).
327
+ if (response.status === 409 && parsed.code === "CONFLICT") {
328
+ throw new ConflictError(parsed.message, serverModifiedAt, expectedModifiedAt, detailsRecord);
329
+ }
330
+ if (response.status === 409 && parsed.code === "OPS_EXIST") {
331
+ throw new OpsExistError(parsed.message, detailsRecord);
332
+ }
333
+ if (response.status === 400 && parsed.code === "TOML_PARSE_ERROR") {
334
+ throw new TomlParseError(parsed.message, detailsRecord);
335
+ }
336
+ if (response.status === 422 && parsed.code === "SCHEMA_REQUIRED") {
337
+ throw new SchemaRequiredError(parsed.message, detailsRecord);
104
338
  }
105
- if (response.status === 409 && errorData?.code === "CONFLICT") {
106
- throw new ConflictError(errorData.message || "Resource conflict", errorData.serverModifiedAt, errorData.expectedModifiedAt);
339
+ if (response.status === 422 && parsed.code === "OPERATION_REFERENCES_UNDEFINED") {
340
+ throw new OperationRefError(parsed.message, detailsRecord);
107
341
  }
108
- throw new ApiError(errorData.message || `HTTP ${response.status}`, response.status, errorData.code);
342
+ if (response.status === 422 && parsed.code === "SCHEMA_BREAKS_OPERATIONS") {
343
+ throw new SchemaBreaksOpsError(parsed.message, detailsRecord);
344
+ }
345
+ if (response.status === 422 && parsed.code === "SCHEMA_HAS_UNCHECKABLE_OPS") {
346
+ throw new SchemaHasUncheckableOpsError(parsed.message, detailsRecord);
347
+ }
348
+ throw new ApiError(parsed.message, response.status, parsed.code, parsed.details);
109
349
  }
110
350
  return text ? JSON.parse(text) : null;
111
351
  }
@@ -154,8 +394,74 @@ export class ApiClient {
154
394
  // ============================================
155
395
  // APPS
156
396
  // ============================================
397
+ /**
398
+ * One page of the apps the caller can reach.
399
+ *
400
+ * The route paginates cursor-style (default pageSize=25, cap=100). This
401
+ * method used to walk the whole chain so `primitive apps list` could not
402
+ * truncate at 25 (#436); since #3646 the page boundary belongs to the
403
+ * caller instead — `apps list` declares `--limit`/`--cursor` and prints the
404
+ * `hasMore`/`nextCursor` the server reported, and the aggregate readers that
405
+ * really do mean "every app" call `listAllApps()`.
406
+ */
407
+ async listAppsPage(params) {
408
+ const qs = new URLSearchParams();
409
+ if (params?.limit !== undefined)
410
+ qs.set("limit", String(params.limit));
411
+ if (params?.cursor)
412
+ qs.set("cursor", params.cursor);
413
+ const q = qs.toString();
414
+ const resp = await this.get(`/admin/api/admins/me/apps${q ? `?${q}` : ""}`);
415
+ return {
416
+ items: resp?.items ?? [],
417
+ hasMore: resp?.hasMore,
418
+ nextCursor: resp?.nextCursor ?? null,
419
+ };
420
+ }
421
+ /**
422
+ * Every app the caller can reach, cursor chain walked (#436).
423
+ *
424
+ * For readers that genuinely need the whole set — an app picker, a sweep —
425
+ * rather than the one page `apps list` prints.
426
+ */
157
427
  async listApps() {
158
- return this.get("/admin/api/admins/me/apps");
428
+ const apps = await paginateAll(async (cursor) => {
429
+ const page = await this.listAppsPage({ limit: 100, cursor });
430
+ return { items: page.items, nextCursor: page.nextCursor };
431
+ });
432
+ return { apps };
433
+ }
434
+ /**
435
+ * Every app on the server, not just the caller's own.
436
+ *
437
+ * Deliberately separate from `listApps()`, whose contract is "apps assigned
438
+ * to me" (`GET /admin/api/admins/me/apps`, backed by `admin.queryApps()`) —
439
+ * the contract every other command depends on. `analytics workflow-usage
440
+ * --all-apps` has to reach apps nobody is assigned to, which is the global
441
+ * route `GET /admin/api/apps` (`App.iterateAll()`), and that route
442
+ * identifies an app as `appId` rather than `id` (D3130-001).
443
+ *
444
+ * One drain of that route is lossy — its cursor re-scans `App.iterateAll()`
445
+ * from the start of each page, so a list that changes under it both repeats
446
+ * and drops rows — so the walk is the union of repeated drains
447
+ * (`drainAppsUntilConverged`, which carries the measurement).
448
+ */
449
+ async listAllAppsGlobal() {
450
+ const drainOnce = () => paginateAll(async (cursor) => {
451
+ const qs = new URLSearchParams({ limit: "100" });
452
+ if (cursor)
453
+ qs.set("cursor", cursor);
454
+ const resp = await this.get(`/admin/api/apps?${qs.toString()}`);
455
+ const rows = resp.items ?? [];
456
+ return {
457
+ items: rows.map((row) => ({
458
+ appId: String(row.appId ?? row.id ?? ""),
459
+ name: String(row.name ?? ""),
460
+ })),
461
+ nextCursor: resp.nextCursor,
462
+ };
463
+ });
464
+ return drainAppsUntilConverged(drainOnce);
159
465
  }
160
466
  async createApp(data) {
161
467
  return this.post("/admin/api/apps", data);
@@ -181,12 +487,77 @@ export class ApiClient {
181
487
  async addUserByEmail(appId, data) {
182
488
  return this.post(`/admin/api/apps/${appId}/users/add-by-email`, data);
183
489
  }
184
- async listUsers(appId) {
185
- return this.get(`/app/${appId}/api/users`);
490
+ async mintTestJwt(appId, userId, role) {
491
+ return this.post(`/admin/api/apps/${appId}/users/${userId}/mint-test-jwt`, role ? { role } : {});
492
+ }
493
+ async rebuildUserSearchText(appId) {
494
+ return this.post(`/admin/api/apps/${appId}/users/rebuild-search-text`, {});
495
+ }
496
+ async listUsers(appId, params) {
497
+ const query = new URLSearchParams();
498
+ if (params?.name)
499
+ query.set("name", params.name);
500
+ if (params?.email)
501
+ query.set("email", params.email);
502
+ if (params?.userId)
503
+ query.set("userId", params.userId);
504
+ if (params?.limit)
505
+ query.set("limit", String(params.limit));
506
+ if (params?.cursor)
507
+ query.set("cursor", params.cursor);
508
+ const path = query.toString()
509
+ ? `/app/${appId}/api/users?${query.toString()}`
510
+ : `/app/${appId}/api/users`;
511
+ const result = await this.get(path);
512
+ return {
513
+ items: result?.items ?? (Array.isArray(result) ? result : []),
514
+ // `hasMore` travels with the page so the caller prints the server's own
515
+ // page boundary rather than inferring one from the cursor (#3646).
516
+ hasMore: result?.hasMore,
517
+ nextCursor: result?.nextCursor ?? null,
518
+ };
186
519
  }
520
+ /**
521
+ * @deprecated Use {@link setUserAvailability} with `"disable"`
522
+ * (`PUT /admin/api/apps/:appId/users/:userId/disable`) instead (#518).
523
+ */
187
524
  async removeUser(appId, userId) {
188
525
  return this.delete(`/app/${appId}/api/users/${userId}`);
189
526
  }
527
+ /**
528
+ * #2803 — take a user's access away, or give it back. Distinct from
529
+ * `removeUser`, which detaches the membership: this blocks the person's auth
530
+ * in the app, revokes their sessions and tokens, and is reversible. Both
531
+ * routes already existed; nothing on the CLI reached them.
532
+ */
533
+ async setUserAvailability(appId, userId, action) {
534
+ return this.put(`/admin/api/apps/${appId}/users/${userId}/${action}`, {});
535
+ }
536
+ // ============================================
537
+ // FEATURE FLAGS (super-admin)
538
+ // ============================================
539
+ /**
540
+ * #2803 — the platform's feature flags. A server-owned admin toggle with a
541
+ * console but, until now, no CLI: the same "one control, both surfaces" rule
542
+ * the carrying types get.
543
+ */
544
+ async listFeatureFlags() {
545
+ return this.get(`/admin/api/flags`);
546
+ }
547
+ /**
548
+ * The flag itself, not the `{ flag }` envelope the route answers with —
549
+ * `feature-flags get` prints the key, the enabled state and the per-app
550
+ * overrides, and reading them off the envelope printed a blank row.
551
+ */
552
+ async getFeatureFlag(flagKey) {
553
+ const result = await this.get(`/admin/api/flags/${flagKey}`);
554
+ return result?.flag ?? result;
555
+ }
556
+ /** Same envelope, same unwrap: `enable`/`disable` print the updated flag. */
557
+ async setFeatureFlagEnabled(flagKey, enabled) {
558
+ const result = await this.put(`/admin/api/flags/${flagKey}`, { enabled });
559
+ return result?.flag ?? result;
560
+ }
190
561
  async updateUserRole(appId, userId, role) {
191
562
  return this.put(`/app/${appId}/api/users/${userId}/role`, { role });
192
563
  }
@@ -196,14 +567,36 @@ export class ApiClient {
196
567
  async transferAdminOwnership(appId, adminId) {
197
568
  return this.post(`/admin/api/apps/${appId}/admins/transfer-ownership`, { adminId });
198
569
  }
570
+ // App-level console admin management
571
+ async listAppAdmins(appId) {
572
+ return this.get(`/admin/api/apps/${appId}/admins`);
573
+ }
574
+ async addAppAdmin(appId, data) {
575
+ return this.post(`/admin/api/apps/${appId}/admins`, data);
576
+ }
577
+ async removeAppAdmin(appId, adminId) {
578
+ return this.delete(`/admin/api/apps/${appId}/admins/${adminId}`);
579
+ }
580
+ async listAppAdminInvitations(appId) {
581
+ return this.get(`/admin/api/apps/${appId}/admin-invitations`);
582
+ }
583
+ async deleteAppAdminInvitation(appId, invitationId) {
584
+ return this.delete(`/admin/api/apps/${appId}/admin-invitations/${invitationId}`);
585
+ }
199
586
  async transferDocumentOwnership(appId, documentId, newOwnerId) {
200
587
  return this.post(`/app/${appId}/api/documents/${documentId}/permissions/transfer`, { newOwnerId });
201
588
  }
202
589
  // ============================================
203
590
  // INVITATIONS
204
591
  // ============================================
205
- async listInvitations(appId) {
206
- return this.get(`/app/${appId}/api/invitations`);
592
+ async listInvitations(appId, params) {
593
+ const result = await this.get(`/app/${appId}/api/invitations`, params);
594
+ const nextCursor = result?.nextCursor;
595
+ return {
596
+ items: result?.items ?? [],
597
+ nextCursor,
598
+ hasMore: result?.hasMore ?? nextCursor != null,
599
+ };
207
600
  }
208
601
  async createInvitation(appId, data) {
209
602
  return this.post(`/app/${appId}/api/invitations`, data);
@@ -228,18 +621,44 @@ export class ApiClient {
228
621
  return this.delete(`/app/${appId}/api/waitlist/${waitlistId}`);
229
622
  }
230
623
  // ============================================
624
+ // DEFERRED GRANTS
625
+ // ============================================
626
+ async listDeferredGrants(appId, params) {
627
+ const result = await this.get(`/app/${appId}/api/deferred-grants`, params);
628
+ const items = result?.items ?? [];
629
+ return {
630
+ items,
631
+ nextCursor: result?.nextCursor ?? null,
632
+ hasMore: result?.hasMore,
633
+ };
634
+ }
635
+ async revokeDeferredGrant(appId, deferredId, type) {
636
+ return this.delete(`/app/${appId}/api/deferred-grants/${deferredId}?type=${type}`);
637
+ }
638
+ // ============================================
231
639
  // INTEGRATIONS
232
640
  // ============================================
233
641
  async listIntegrations(appId, params) {
234
642
  const result = await this.get(`/admin/api/apps/${appId}/integrations`, params);
235
643
  return {
236
644
  items: result?.items ?? [],
645
+ hasMore: result?.hasMore,
237
646
  nextCursor: result?.nextCursor ?? null,
238
647
  };
239
648
  }
649
+ /** Integration detail (#2631: `accessRule` is on the detail, not the list summary). */
240
650
  async getIntegration(appId, integrationId) {
241
651
  return this.get(`/admin/api/apps/${appId}/integrations/${integrationId}`);
242
652
  }
653
+ /**
654
+ * An integration's named configs. Test cases pin a config by NAME so the
655
+ * sidecar is portable across apps (#2769); this is the map pull and push
656
+ * resolve that name through, the same way prompts/workflows/scripts do.
657
+ */
658
+ async listIntegrationConfigs(appId, integrationId) {
659
+ const result = await this.get(`/admin/api/apps/${appId}/integrations/${integrationId}/configs`);
660
+ return { items: result?.items ?? result ?? [] };
661
+ }
243
662
  async createIntegration(appId, payload) {
244
663
  return this.post(`/admin/api/apps/${appId}/integrations`, payload);
245
664
  }
@@ -247,8 +666,15 @@ export class ApiClient {
247
666
  const body = expectedModifiedAt ? { ...payload, expectedModifiedAt } : payload;
248
667
  return this.patch(`/admin/api/apps/${appId}/integrations/${integrationId}`, body);
249
668
  }
669
+ /**
670
+ * Delete an integration. Archives it by default; `{ hard: true }` destroys
671
+ * the row instead, which is what `config push --prune` passes (#2803) so a
672
+ * pruned integration stops holding its key. The positional boolean is still
673
+ * accepted for the existing callers.
674
+ */
250
675
  async deleteIntegration(appId, integrationId, hard) {
251
- const path = hard
676
+ const isHard = typeof hard === "object" ? hard?.hard === true : hard === true;
677
+ const path = isHard
252
678
  ? `/admin/api/apps/${appId}/integrations/${integrationId}?hard=true`
253
679
  : `/admin/api/apps/${appId}/integrations/${integrationId}`;
254
680
  return this.delete(path);
@@ -260,17 +686,515 @@ export class ApiClient {
260
686
  const result = await this.get(`/admin/api/apps/${appId}/integrations/${integrationId}/logs`, params);
261
687
  return result?.items ?? [];
262
688
  }
263
- async listIntegrationSecrets(appId, integrationId, params) {
264
- const result = await this.get(`/admin/api/apps/${appId}/integrations/${integrationId}/secrets`, params);
689
+ async listWorkflowRunIntegrationLogs(appId, runId, params) {
690
+ const result = await this.get(`/admin/api/apps/${appId}/workflows/runs/${runId}/integration-logs`, params);
265
691
  return result?.items ?? [];
266
692
  }
267
- async addIntegrationSecret(appId, integrationId, payload) {
268
- const result = await this.post(`/admin/api/apps/${appId}/integrations/${integrationId}/secrets`, payload);
269
- return result?.secret ?? null;
693
+ // ============================================
694
+ // APP SECRETS
695
+ // ============================================
696
+ async listAppSecrets(appId) {
697
+ const result = await this.get(`/admin/api/apps/${appId}/secrets`);
698
+ return result?.items ?? [];
699
+ }
700
+ async createAppSecret(appId, payload) {
701
+ return this.post(`/admin/api/apps/${appId}/secrets`, payload);
702
+ }
703
+ async updateAppSecret(appId, secretId, payload) {
704
+ return this.put(`/admin/api/apps/${appId}/secrets/${secretId}`, payload);
705
+ }
706
+ async upsertAppSecret(appId, key, payload) {
707
+ return this.put(`/admin/api/apps/${appId}/secrets/by-key/${key}`, payload);
708
+ }
709
+ async deleteAppSecret(appId, secretId) {
710
+ return this.delete(`/admin/api/apps/${appId}/secrets/${secretId}`);
711
+ }
712
+ // ============================================
713
+ // APP CONFIG VARS (issue #1364 — non-secret twin of secrets)
714
+ // ============================================
715
+ async listAppConfigVars(appId) {
716
+ const result = await this.get(`/admin/api/apps/${appId}/vars`);
717
+ return result?.items ?? [];
718
+ }
719
+ async upsertAppConfigVar(appId, key, payload, expectedModifiedAt, options = {}) {
720
+ // Encode the key so a malformed one (e.g. containing "/") reaches the
721
+ // server's key validation (400) instead of producing a routing 404.
722
+ // `expectedModifiedAt` (issue #1423 review r-2 P1) is the optimistic-
723
+ // concurrency precondition for an UPDATE — the server rejects the write
724
+ // with a 409 CONFLICT (surfaced as `ConflictError`) if the var changed
725
+ // since it.
726
+ //
727
+ // `expectNotExists` (issue #1423 review r-3 P1a) is the create-only
728
+ // precondition. A create has no baseline timestamp to send, but without
729
+ // any precondition the by-key upsert silently overwrites a var created
730
+ // remotely since our snapshot. Setting `expectNotExists` makes the server
731
+ // 409 CONFLICT if the key already exists instead of overwriting it.
732
+ const body = { ...payload };
733
+ if (expectedModifiedAt !== undefined)
734
+ body.expectedModifiedAt = expectedModifiedAt;
735
+ if (options.expectNotExists)
736
+ body.expectNotExists = true;
737
+ return this.put(`/admin/api/apps/${appId}/vars/by-key/${encodeURIComponent(key)}`, body);
738
+ }
739
+ async deleteAppConfigVar(appId, key, expectedModifiedAt) {
740
+ // The DELETE carries the optimistic-concurrency precondition (issue #1423
741
+ // review r-2 P1) as a query param since it has no body; the server 409s
742
+ // (ConflictError) if the var was edited remotely since `expectedModifiedAt`.
743
+ let path = `/admin/api/apps/${appId}/vars/by-key/${encodeURIComponent(key)}`;
744
+ if (expectedModifiedAt !== undefined) {
745
+ path += `?expectedModifiedAt=${encodeURIComponent(expectedModifiedAt)}`;
746
+ }
747
+ return this.delete(path);
748
+ }
749
+ // ============================================
750
+ // WEBHOOKS
751
+ // ============================================
752
+ async listWebhooks(appId, params) {
753
+ const result = await this.get(`/admin/api/apps/${appId}/webhooks`, params);
754
+ return {
755
+ items: result?.items ?? [],
756
+ hasMore: result?.hasMore,
757
+ nextCursor: result?.nextCursor ?? null,
758
+ };
759
+ }
760
+ async getWebhook(appId, webhookId) {
761
+ return this.get(`/admin/api/apps/${appId}/webhooks/${webhookId}`);
762
+ }
763
+ async createWebhook(appId, payload) {
764
+ return this.post(`/admin/api/apps/${appId}/webhooks`, payload);
765
+ }
766
+ async updateWebhook(appId, webhookId, payload, expectedModifiedAt) {
767
+ const body = expectedModifiedAt ? { ...payload, expectedModifiedAt } : payload;
768
+ return this.patch(`/admin/api/apps/${appId}/webhooks/${webhookId}`, body);
769
+ }
770
+ /**
771
+ * Delete a webhook. Archives it by default; `hard` hard-deletes the row
772
+ * instead (#2232), which is what frees a slot under the per-app webhook cap
773
+ * and releases the webhook key for reuse. Same `?hard=true` verb the admin
774
+ * integrations delete uses.
775
+ */
776
+ async deleteWebhook(appId, webhookId, options) {
777
+ const query = options?.hard ? "?hard=true" : "";
778
+ return this.delete(`/admin/api/apps/${appId}/webhooks/${webhookId}${query}`);
779
+ }
780
+ /**
781
+ * #2803 — the operational verb pair for a webhook. It posts to the
782
+ * enable/disable route rather than PATCHing `status`, which is server-owned
783
+ * and refused on every configuration write path.
784
+ */
785
+ async setWebhookAvailability(appId, webhookId, action) {
786
+ return this.post(`/admin/api/apps/${appId}/webhooks/${webhookId}/${action}`, {});
787
+ }
788
+ // ── Server functions (#3179) ─────────────────────────────────────────
789
+ //
790
+ // The `functions` family mirrors workflows and scripts: a header with the
791
+ // gate and the entry, and append-only immutable config versions carrying the
792
+ // authored TOML bytes, the sources and the built bundle. The listing drains
793
+ // server-side, so it has no cursor.
794
+ async listFunctions(appId) {
795
+ const result = await this.get(`/admin/api/apps/${appId}/functions`);
796
+ return { items: result?.items ?? [] };
797
+ }
798
+ async getFunction(appId, functionId) {
799
+ return this.get(`/admin/api/apps/${appId}/functions/${functionId}`);
800
+ }
801
+ async createFunction(appId, payload) {
802
+ return this.post(`/admin/api/apps/${appId}/functions`, payload);
803
+ }
804
+ async updateFunction(appId, functionId, payload) {
805
+ return this.patch(`/admin/api/apps/${appId}/functions/${functionId}`, payload);
806
+ }
807
+ /**
808
+ * Archive a function, or destroy it with `hard`. Archiving KEEPS the key
809
+ * reserved in the app's single key namespace; the hard delete is what
810
+ * releases it, destroys every config version and removes the R2 objects.
811
+ */
812
+ async deleteFunction(appId, functionId, options) {
813
+ const query = options?.hard ? "?hard=true" : "";
814
+ return this.delete(`/admin/api/apps/${appId}/functions/${functionId}${query}`);
815
+ }
816
+ /** #2803 — the operational verb pair for a server function. */
817
+ async setFunctionAvailability(appId, functionId, action) {
818
+ return this.post(`/admin/api/apps/${appId}/functions/${functionId}/${action}`, {});
819
+ }
820
+ /** Every config version of a function, oldest first. */
821
+ /**
822
+ * A function's runs, newest first (#3181).
823
+ *
824
+ * A function run has no `workflowId`, so no workflow runs listing can see
825
+ * it — this is the only surface that lists one. Cursor-paginated like the
826
+ * other admin listings.
827
+ */
828
+ async listFunctionRuns(appId, functionId, params) {
829
+ const result = await this.get(`/admin/api/apps/${appId}/functions/${functionId}/runs`, params);
830
+ return { items: result?.items ?? [], nextCursor: result?.nextCursor ?? null };
831
+ }
832
+ /**
833
+ * A function run's step trace — #3348.
834
+ *
835
+ * The function-scoped twin of `getWorkflowStepRuns`, and it answers with the
836
+ * same rows in the same shape: `workflows/:idOrKey/runs/...` resolves its
837
+ * first argument to a workflow DEFINITION, which a function id and a function
838
+ * key alike miss, so a durable run's steps needed a route that addresses the
839
+ * run by the function that owns it.
840
+ */
841
+ async getFunctionStepRuns(appId, functionId, runId) {
842
+ const result = await this.get(`/admin/api/apps/${appId}/functions/${functionId}/runs/${runId}/steps`);
843
+ return { items: result?.items ?? [] };
844
+ }
845
+ /**
846
+ * End a function run that will not settle — #3348.
847
+ *
848
+ * `terminated: false` means the run had already settled and the route
849
+ * reported its outcome instead of overwriting it.
850
+ */
851
+ async terminateFunctionRun(appId, functionId, runId) {
852
+ return this.post(`/admin/api/apps/${appId}/functions/${functionId}/runs/${runId}/terminate`, {});
853
+ }
854
+ /**
855
+ * A function's invocation records, newest first — #3287.
856
+ *
857
+ * The ADMIN route, beside the runs listing above and for the same reason:
858
+ * the CLI acts as an operator, not as a member of the app. The app-API twin
859
+ * (`functions.logs`) is what a FUNCTION reads through the SDK profile.
860
+ */
861
+ async listFunctionLogs(appId, functionId, params) {
862
+ const result = await this.get(`/admin/api/apps/${appId}/functions/${functionId}/logs`, params);
863
+ return { items: result?.items ?? [], nextCursor: result?.nextCursor ?? null };
864
+ }
865
+ /**
866
+ * One invocation record by its id — #3448, behind `functions logs
867
+ * --invocation <id>`.
868
+ *
869
+ * The id the invoke envelope answered with. A record that never existed,
870
+ * one of ANOTHER function, and one the seven-day TTL has expired all answer
871
+ * the same 404, which is what the listing's own filter promises.
872
+ */
873
+ async getFunctionLog(appId, functionId, invocationId) {
874
+ return this.get(`/admin/api/apps/${appId}/functions/${functionId}/logs/${invocationId}`);
875
+ }
876
+ /**
877
+ * One function run, RECONCILED against the engine — #3448, what
878
+ * `functions runs wait` polls.
879
+ *
880
+ * NOT the runs listing: that reports the STORED status, and a durable run's
881
+ * row stays `running` until something asks the engine, so a wait built on it
882
+ * would never settle.
883
+ */
884
+ async getFunctionRun(appId, functionId, runId) {
885
+ return this.get(`/admin/api/apps/${appId}/functions/${functionId}/runs/${runId}`);
886
+ }
887
+ /**
888
+ * The operator's own APP user — #3448 D3448-009.
889
+ *
890
+ * `getMe()` reads the ADMIN profile (`/admin/api/me`); this is the
891
+ * app-scoped route, which answers the app user `requireAppPermission`
892
+ * provisions for an admin and the `appRole` it gave them. That is the
893
+ * identity a `functions invoke` runs under by default, and printing it is
894
+ * how an operator knows their call bypassed the function's `access` gate.
895
+ */
896
+ async getAppProfile(appId) {
897
+ return this.get(`/app/${appId}/api/me`);
898
+ }
899
+ /**
900
+ * Invoke a function and hand back the ANSWER, whatever its HTTP status —
901
+ * #3448 D3448-010.
902
+ *
903
+ * `request` throws an `ApiError` on any non-2xx, which is right for every
904
+ * other verb and wrong for this one: a 429 carries a `Retry-After` an
905
+ * operator needs to see, and a 409 mode mismatch carries the version's real
906
+ * mode. Rendering those from an exception means re-deriving what the server
907
+ * already said. So this returns the envelope with its status and its retry
908
+ * hint, and throws only when the request did not complete at all.
909
+ *
910
+ * `bearer` is the `--user` path's minted token; absent, the CLI's own
911
+ * credentials. `mode` is ALWAYS sent (D3448-012): it is what makes the
912
+ * server, not the CLI, the authority on a wrong verb.
913
+ */
914
+ async invokeFunction(appId, functionKey, body, options) {
915
+ const credentials = await this.ensureAuthenticated();
916
+ const base = `/app/${appId}/api/functions/${encodeURIComponent(functionKey)}`;
917
+ const path = options?.asSystem
918
+ ? `${base}/invoke-as-system`
919
+ : options?.runtime === "task"
920
+ ? `${base}/start`
921
+ : base;
922
+ const headers = {
923
+ Authorization: `Bearer ${options?.bearer ?? credentials.accessToken}`,
924
+ "Content-Type": "application/json",
925
+ };
926
+ // The CLI's own credentials reach an app-scoped route through the
927
+ // global-admin header; a minted user token does not need it and must not
928
+ // carry it.
929
+ if (!options?.bearer && credentials.globalAdminAppId) {
930
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
931
+ }
932
+ const response = await fetchWithTLS(`${credentials.serverUrl}${path}`, {
933
+ method: "POST",
934
+ headers,
935
+ body: JSON.stringify(body),
936
+ });
937
+ const text = await response.text();
938
+ let parsed = null;
939
+ try {
940
+ parsed = text ? JSON.parse(text) : null;
941
+ }
942
+ catch {
943
+ // A body that is not JSON is still an answer; keep it readable.
944
+ parsed = { error: text };
945
+ }
946
+ const retryAfter = response.headers.get("retry-after");
947
+ const retryAfterSeconds = retryAfter && Number.isFinite(Number(retryAfter)) ? Number(retryAfter) : null;
948
+ return {
949
+ httpStatus: response.status,
950
+ retryAfterSeconds: retryAfterSeconds ??
951
+ (typeof parsed?.retryAfter === "number" ? parsed.retryAfter : null),
952
+ body: parsed,
953
+ };
954
+ }
955
+ /**
956
+ * A function's versions, newest first (#3462).
957
+ *
958
+ * Paging is opt-in on the server: with no `limit` and no `cursor` every
959
+ * version comes back, which is what this method did before paging existed and
960
+ * what an already-installed CLI still asks for. A caller that passes either
961
+ * gets the shared `{ items, hasMore, nextCursor }` page.
962
+ */
963
+ async listFunctionConfigs(appId, functionId, options = {}) {
964
+ const query = new URLSearchParams();
965
+ if (options.limit !== undefined)
966
+ query.set("limit", String(options.limit));
967
+ if (options.cursor)
968
+ query.set("cursor", options.cursor);
969
+ const suffix = query.toString() ? `?${query.toString()}` : "";
970
+ const result = await this.get(`/admin/api/apps/${appId}/functions/${functionId}/configs${suffix}`);
971
+ return {
972
+ items: result?.items ?? [],
973
+ hasMore: result?.hasMore === true,
974
+ nextCursor: result?.nextCursor ?? null,
975
+ };
976
+ }
977
+ /**
978
+ * Point the function at one of its OWN existing versions (#3462). Creates no
979
+ * version; the activated version's capabilities, limits and triggers apply
980
+ * from the next call.
981
+ */
982
+ async activateFunctionConfig(appId, functionId, configId) {
983
+ return this.post(`/admin/api/apps/${appId}/functions/${functionId}/configs/${configId}/activate`, {});
984
+ }
985
+ async getFunctionConfig(appId, functionId, configId) {
986
+ return this.get(`/admin/api/apps/${appId}/functions/${functionId}/configs/${configId}`);
987
+ }
988
+ /**
989
+ * The stored envelope: the authored TOML bytes, every source file and the
990
+ * built bundle, all base64. This is what `config pull` writes back verbatim.
991
+ */
992
+ async getFunctionConfigEnvelope(appId, functionId, configId) {
993
+ return this.get(`/admin/api/apps/${appId}/functions/${functionId}/configs/${configId}/envelope`);
994
+ }
995
+ /** Push a config version. The server verifies `contentHash` itself. */
996
+ async pushFunctionConfig(appId, functionId, payload) {
997
+ return this.post(`/admin/api/apps/${appId}/functions/${functionId}/configs`, payload);
998
+ }
999
+ /** #2803 — the operational verb pair for a prompt (admin API). */
1000
+ async setPromptAvailability(appId, promptId, action) {
1001
+ return this.post(`/admin/api/apps/${appId}/prompts/${promptId}/${action}`, {});
1002
+ }
1003
+ /** #2803 — the operational verb pair for an integration (admin API). */
1004
+ async setIntegrationAvailability(appId, integrationId, action) {
1005
+ return this.post(`/admin/api/apps/${appId}/integrations/${integrationId}/${action}`, {});
1006
+ }
1007
+ async rotateWebhookSecret(appId, webhookId, payload) {
1008
+ return this.post(`/admin/api/apps/${appId}/webhooks/${webhookId}/rotate-secret`, payload);
1009
+ }
1010
+ async listWebhookEvents(appId, webhookId, params) {
1011
+ const result = await this.get(`/admin/api/apps/${appId}/webhooks/${webhookId}/events`, params);
1012
+ const nextCursor = result?.nextCursor ?? null;
1013
+ return {
1014
+ items: result?.items ?? [],
1015
+ hasMore: result?.hasMore ?? !!nextCursor,
1016
+ nextCursor,
1017
+ };
1018
+ }
1019
+ // ============================================
1020
+ // CONNECTIONS INSPECTION (#1968)
1021
+ // ============================================
1022
+ /**
1023
+ * List the live connections the server believes exist for exactly one of a
1024
+ * document, user, or database. Read-only inspection over admin-api. Rows are
1025
+ * per-connection-×-subscription bindings, so `connectionId` is not unique
1026
+ * across rows. `params` on a database-subscription row is caller-defined
1027
+ * bound CEL input — typed `unknown`.
1028
+ */
1029
+ async listConnections(appId, selector, params) {
1030
+ const result = await this.get(`/admin/api/apps/${appId}/connections`, {
1031
+ ...selector,
1032
+ ...params,
1033
+ });
1034
+ return {
1035
+ items: result?.items ?? [],
1036
+ hasMore: result?.hasMore,
1037
+ nextCursor: result?.nextCursor ?? null,
1038
+ };
270
1039
  }
271
- async archiveIntegrationSecret(appId, integrationId, secretId) {
272
- return this.patch(`/admin/api/apps/${appId}/integrations/${integrationId}/secrets/${secretId}`, {
273
- status: "inactive",
1040
+ async listSessions(appId, userId, params) {
1041
+ const result = await this.get(`/admin/api/apps/${appId}/sessions`, {
1042
+ userId,
1043
+ ...params,
1044
+ });
1045
+ return {
1046
+ items: result?.items ?? [],
1047
+ hasMore: result?.hasMore,
1048
+ nextCursor: result?.nextCursor ?? null,
1049
+ };
1050
+ }
1051
+ /**
1052
+ * One page of admin sessions (#3885): the caller's own, or — for a
1053
+ * super-admin — the admin `adminId` names.
1054
+ */
1055
+ async listAdminSessions(params) {
1056
+ const result = await this.get("/admin/api/auth/sessions", params);
1057
+ return {
1058
+ items: result?.items ?? [],
1059
+ hasMore: result?.hasMore,
1060
+ nextCursor: result?.nextCursor ?? null,
1061
+ };
1062
+ }
1063
+ /** Revoke an admin session (idempotent). */
1064
+ async revokeAdminSession(sessionId) {
1065
+ return this.delete(`/admin/api/auth/sessions/${encodeURIComponent(sessionId)}`);
1066
+ }
1067
+ async testWebhook(appId, webhookId, payload) {
1068
+ return this.post(`/admin/api/apps/${appId}/webhooks/${webhookId}/test`, payload || {});
1069
+ }
1070
+ /**
1071
+ * Run a webhook's configured verifier over headers and a body captured from
1072
+ * a real delivery, and report whether that signature checks out (#2445).
1073
+ *
1074
+ * `headers` is sent as ordered `[name, value]` pairs so a capture carrying a
1075
+ * field name on more than one line survives the round trip. Nothing is
1076
+ * delivered: no delivery record, no workflow run.
1077
+ */
1078
+ async verifyWebhook(appId, webhookId, payload) {
1079
+ return this.post(`/admin/api/apps/${appId}/webhooks/${webhookId}/verify`, payload);
1080
+ }
1081
+ // ============================================
1082
+ // NAMED LOCKS (#1518)
1083
+ // ============================================
1084
+ async listLocks(appId) {
1085
+ const result = await this.get(`/app/${appId}/api/locks`);
1086
+ return { locks: result?.locks ?? [] };
1087
+ }
1088
+ async getLockStatus(appId, key) {
1089
+ return this.post(`/app/${appId}/api/locks/status`, { key });
1090
+ }
1091
+ /**
1092
+ * #3562 — `owner` is sent only when one was given, so a call that names none
1093
+ * composes byte for byte the body it always did.
1094
+ */
1095
+ async acquireLock(appId, key, ttlMs, owner) {
1096
+ return this.post(`/app/${appId}/api/locks/acquire`, {
1097
+ key,
1098
+ ttlMs,
1099
+ ...(owner !== undefined ? { owner } : {}),
1100
+ });
1101
+ }
1102
+ async releaseLock(appId, key, handleId) {
1103
+ return this.post(`/app/${appId}/api/locks/release`, {
1104
+ key,
1105
+ handle: { handleId },
1106
+ });
1107
+ }
1108
+ // ============================================
1109
+ // CRON TRIGGERS
1110
+ // ============================================
1111
+ async listCronTriggers(appId) {
1112
+ const result = await this.get(`/app/${appId}/api/cron-triggers`);
1113
+ return { items: result?.items ?? [] };
1114
+ }
1115
+ async getCronTrigger(appId, triggerId) {
1116
+ return this.get(`/app/${appId}/api/cron-triggers/${triggerId}`);
1117
+ }
1118
+ async createCronTrigger(appId, payload) {
1119
+ return this.post(`/app/${appId}/api/cron-triggers`, payload);
1120
+ }
1121
+ async updateCronTrigger(appId, triggerId, payload) {
1122
+ return this.put(`/app/${appId}/api/cron-triggers/${triggerId}`, payload);
1123
+ }
1124
+ /**
1125
+ * Retire a cron trigger. The default soft-deletes (writes the `archived`
1126
+ * tombstone); `{ hard: true }` destroys the row, which is what
1127
+ * `config push --prune` passes (#2803) so a pruned trigger stops consuming
1128
+ * the per-app cap and holding its key.
1129
+ */
1130
+ async deleteCronTrigger(appId, triggerId, options = {}) {
1131
+ const query = options.hard ? "?hard=true" : "";
1132
+ return this.delete(`/app/${appId}/api/cron-triggers/${triggerId}${query}`);
1133
+ }
1134
+ async disableCronTrigger(appId, triggerId) {
1135
+ return this.post(`/app/${appId}/api/cron-triggers/${triggerId}/disable`, {});
1136
+ }
1137
+ async enableCronTrigger(appId, triggerId) {
1138
+ return this.post(`/app/${appId}/api/cron-triggers/${triggerId}/enable`, {});
1139
+ }
1140
+ async testCronTrigger(appId, triggerId) {
1141
+ return this.post(`/app/${appId}/api/cron-triggers/${triggerId}/test`, {});
1142
+ }
1143
+ // ============================================
1144
+ // ITERATIONS (iterate-users introspection / reset — #1209)
1145
+ // ============================================
1146
+ async listIterations(appId) {
1147
+ const result = await this.get(`/app/${appId}/api/iterations`);
1148
+ return { items: result?.items ?? [] };
1149
+ }
1150
+ async getIteration(appId, iterationName) {
1151
+ return this.get(`/app/${appId}/api/iterations/${encodeURIComponent(iterationName)}`);
1152
+ }
1153
+ async resetIteration(appId, iterationName) {
1154
+ return this.post(`/app/${appId}/api/iterations/${encodeURIComponent(iterationName)}/reset`, {});
1155
+ }
1156
+ // ============================================
1157
+ // RESOURCE METADATA (values — issue #1352)
1158
+ // ============================================
1159
+ async readResourceMetadata(appId, resourceType, resourceId, category) {
1160
+ return this.get(`/app/${appId}/api/resources/${encodeURIComponent(resourceType)}/${encodeURIComponent(resourceId)}/metadata/${encodeURIComponent(category)}`);
1161
+ }
1162
+ async writeResourceMetadata(appId, resourceType, resourceId, category, data) {
1163
+ return this.put(`/app/${appId}/api/resources/${encodeURIComponent(resourceType)}/${encodeURIComponent(resourceId)}/metadata/${encodeURIComponent(category)}`, { data });
1164
+ }
1165
+ async batchReadResourceMetadata(appId, requests) {
1166
+ return this.post(`/app/${appId}/api/resources/metadata/batch`, {
1167
+ requests,
1168
+ });
1169
+ }
1170
+ /**
1171
+ * List every stored metadata category on one resource (issue #1402 — debug
1172
+ * tooling). The CLI authenticates as a console admin, so the app-level
1173
+ * owner/admin bypass returns every category regardless of its readRule.
1174
+ */
1175
+ async listResourceMetadata(appId, resourceType, resourceId) {
1176
+ return this.get(`/app/${appId}/api/resources/${encodeURIComponent(resourceType)}/${encodeURIComponent(resourceId)}/metadata`);
1177
+ }
1178
+ /**
1179
+ * Delete one resource's metadata for one category (issue #1402 — debug
1180
+ * tooling). Idempotent: deleting an absent item succeeds with
1181
+ * `deleted: false` rather than a 404.
1182
+ */
1183
+ async deleteResourceMetadata(appId, resourceType, resourceId, category) {
1184
+ return this.delete(`/app/${appId}/api/resources/${encodeURIComponent(resourceType)}/${encodeURIComponent(resourceId)}/metadata/${encodeURIComponent(category)}`);
1185
+ }
1186
+ /**
1187
+ * Reverse-resolve a resource by a category's unique metadata value (issue
1188
+ * #2137). A miss is a success with `resourceId: null`, never an error. The
1189
+ * CLI authenticates as a console admin, so the app-level owner/admin bypass
1190
+ * skips readRule evaluation.
1191
+ */
1192
+ async resolveResourceMetadata(appId, resourceType, category, key, value) {
1193
+ return this.post(`/app/${appId}/api/metadata/resolve`, {
1194
+ resourceType,
1195
+ category,
1196
+ key,
1197
+ value,
274
1198
  });
275
1199
  }
276
1200
  // ============================================
@@ -280,6 +1204,7 @@ export class ApiClient {
280
1204
  const result = await this.get(`/admin/api/apps/${appId}/prompts`, params);
281
1205
  return {
282
1206
  items: result?.items ?? [],
1207
+ hasMore: result?.hasMore,
283
1208
  nextCursor: result?.nextCursor ?? null,
284
1209
  };
285
1210
  }
@@ -293,6 +1218,12 @@ export class ApiClient {
293
1218
  const body = expectedModifiedAt ? { ...payload, expectedModifiedAt } : payload;
294
1219
  return this.patch(`/admin/api/apps/${appId}/prompts/${promptId}`, body);
295
1220
  }
1221
+ /**
1222
+ * Retire a prompt, or destroy it.
1223
+ *
1224
+ * `hard` was always sent by both first-party clients and always ignored by
1225
+ * the server; #2887 made it mean something — the plain call now archives.
1226
+ */
296
1227
  async deletePrompt(appId, promptId, hard) {
297
1228
  const path = hard
298
1229
  ? `/admin/api/apps/${appId}/prompts/${promptId}?hard=true`
@@ -325,36 +1256,136 @@ export class ApiClient {
325
1256
  async duplicatePromptConfig(appId, promptId, configId, payload) {
326
1257
  return this.post(`/admin/api/apps/${appId}/prompts/${promptId}/configs/${configId}/duplicate`, payload || {});
327
1258
  }
1259
+ // ============================================
1260
+ // SCRIPTS (Rhai transforms) — #1000 (prompt-model convergence)
1261
+ // ============================================
1262
+ //
1263
+ // The `Script` model is the authoring surface for `script` workflow
1264
+ // steps. A `Script` is a HEADER (name/description/activeConfigId); the
1265
+ // Rhai body lives on versioned `ScriptConfig` rows resolved LIVE at run
1266
+ // time. CLI `config push` reads `transforms/*.rhai` files and reconciles
1267
+ // them: a new file → create script (mints a default config); a changed
1268
+ // file → create a new config + activate it (zero fan-out — referencing
1269
+ // workflows pick up the new body on their next run).
1270
+ async listScripts(appId) {
1271
+ const result = await this.get(`/admin/api/apps/${appId}/scripts`);
1272
+ return { items: result?.items ?? [] };
1273
+ }
1274
+ async getScript(appId, scriptId) {
1275
+ return this.get(`/admin/api/apps/${appId}/scripts/${scriptId}`);
1276
+ }
1277
+ /**
1278
+ * List a script's versioned configs (the `ScriptConfig` rows). Each config
1279
+ * is a distinct block version: `configId` is the stable version selector,
1280
+ * `contentHash` is its content identity, and `status` reports whether it is
1281
+ * `active`/`draft`/`archived`. The script header's `activeConfigId` names
1282
+ * the live version. Used by `scripts configs list` and by the script test
1283
+ * commands to run against a specific pinned version.
1284
+ */
1285
+ async listScriptConfigs(appId, scriptId) {
1286
+ const result = await this.get(`/admin/api/apps/${appId}/scripts/${scriptId}/configs`);
1287
+ return { items: result?.items ?? [] };
1288
+ }
1289
+ async createScript(appId, payload) {
1290
+ // Mints the script header + a default `active` config carrying the body.
1291
+ return this.post(`/admin/api/apps/${appId}/scripts`, payload);
1292
+ }
1293
+ /**
1294
+ * Push a new body for an existing script by creating a new `ScriptConfig`
1295
+ * and activating it (the prompt-model "edit → activate" flow). Referencing
1296
+ * workflows pick up the new body on their next run with no fan-out. The
1297
+ * config name is unique per script, so we mint a timestamped name.
1298
+ */
1299
+ async pushScriptBody(appId, scriptId, body,
1300
+ /**
1301
+ * The active state the caller believes holds right now (#2731 B10).
1302
+ * Creating an inactive config races nothing, so the guard sits on the
1303
+ * ACTIVATION step: if the active config has moved since the caller read it,
1304
+ * the server rejects with a 409 instead of overwriting a concurrent script
1305
+ * change. It takes BOTH halves of "what is active", because a config's body
1306
+ * can be edited in place without the active id changing — the id alone
1307
+ * would let such an edit through. Omitted (e.g. `--force`) means activate
1308
+ * unconditionally.
1309
+ */
1310
+ expectedActive) {
1311
+ const configName = `sync-${Date.now()}`;
1312
+ const config = await this.post(`/admin/api/apps/${appId}/scripts/${scriptId}/configs`, { configName, body });
1313
+ const activateBody = {};
1314
+ if (expectedActive?.configId) {
1315
+ activateBody.expectedActiveConfigId = expectedActive.configId;
1316
+ }
1317
+ if (expectedActive?.modifiedAt) {
1318
+ activateBody.expectedActiveModifiedAt = expectedActive.modifiedAt;
1319
+ }
1320
+ await this.post(`/admin/api/apps/${appId}/scripts/${scriptId}/configs/${config.configId}/activate`, activateBody);
1321
+ return config;
1322
+ }
1323
+ /**
1324
+ * Delete a script header (cascades its configs). `force` overrides the
1325
+ * server's guard against deleting a script that an active workflow still
1326
+ * references by name — without it the server answers 409.
1327
+ */
1328
+ async deleteScript(appId, scriptId, force) {
1329
+ const path = force
1330
+ ? `/admin/api/apps/${appId}/scripts/${scriptId}?force=true`
1331
+ : `/admin/api/apps/${appId}/scripts/${scriptId}`;
1332
+ return this.delete(path);
1333
+ }
328
1334
  async getPromptSchema(appId, promptId) {
329
1335
  return this.get(`/admin/api/apps/${appId}/prompts/${promptId}/schema`);
330
1336
  }
331
1337
  // ============================================
332
1338
  // BLOCK TEST CASES (Prompts, Integrations, Workflows)
333
1339
  // ============================================
334
- async listTestCases(appId, blockType, blockId) {
335
- const result = await this.get(`/admin/api/apps/${appId}/blocks/${blockType}/${blockId}/test-cases`);
336
- return { items: result?.items ?? result ?? [] };
1340
+ /**
1341
+ * One page of a block's test cases. The endpoint paginates (default 50, cap
1342
+ * 100) and reports `nextCursor`; callers that reconcile the sync tree must
1343
+ * drain every page before deleting or classifying anything (#2769).
1344
+ */
1345
+ async listTestCases(appId, blockType, blockId, params = {}) {
1346
+ const query = new URLSearchParams();
1347
+ if (params.limit !== undefined)
1348
+ query.set("limit", String(params.limit));
1349
+ if (params.cursor)
1350
+ query.set("cursor", params.cursor);
1351
+ const suffix = query.toString() ? `?${query.toString()}` : "";
1352
+ const result = await this.get(`/admin/api/apps/${appId}/blocks/${blockType}/${blockId}/test-cases${suffix}`);
1353
+ return {
1354
+ items: result?.items ?? result ?? [],
1355
+ hasMore: result?.hasMore,
1356
+ nextCursor: result?.nextCursor ?? undefined,
1357
+ };
337
1358
  }
338
1359
  async getTestCase(appId, blockType, blockId, testCaseId) {
339
1360
  return this.get(`/admin/api/apps/${appId}/blocks/${blockType}/${blockId}/test-cases/${testCaseId}`);
340
1361
  }
341
1362
  async createTestCase(appId, blockType, blockId, payload) {
342
- // Server expects JSON strings for these fields
1363
+ // #2769 — the JSON fields travel PARSED. The handler stringifies them for
1364
+ // storage (`createBlockTestCase`) and `serializeBlockTestCase` parses them
1365
+ // on the way back out, so a client that stringifies first stores a JSON
1366
+ // string of a JSON string and reads back a quoted blob.
343
1367
  const serverPayload = {
344
1368
  name: payload.name,
345
- inputVariables: JSON.stringify(payload.inputVariables),
1369
+ inputVariables: payload.inputVariables,
346
1370
  configId: payload.configId,
347
1371
  evaluatorPromptId: payload.evaluatorPromptId,
348
1372
  evaluatorConfigId: payload.evaluatorConfigId,
349
1373
  };
1374
+ // #2896 — only when the caller has one: an older server rejects the key
1375
+ // outright, and push reads that 400 to learn what it is talking to.
1376
+ if (payload.key !== undefined)
1377
+ serverPayload.key = payload.key;
1378
+ if (payload.description !== undefined) {
1379
+ serverPayload.description = payload.description;
1380
+ }
350
1381
  if (payload.expectedOutputPattern) {
351
1382
  serverPayload.expectedOutputPattern = payload.expectedOutputPattern;
352
1383
  }
353
1384
  if (payload.expectedOutputContains) {
354
- serverPayload.expectedOutputContains = JSON.stringify(payload.expectedOutputContains);
1385
+ serverPayload.expectedOutputContains = payload.expectedOutputContains;
355
1386
  }
356
1387
  if (payload.expectedJsonSubset) {
357
- serverPayload.expectedJsonSubset = JSON.stringify(payload.expectedJsonSubset);
1388
+ serverPayload.expectedJsonSubset = payload.expectedJsonSubset;
358
1389
  }
359
1390
  return this.post(`/admin/api/apps/${appId}/blocks/${blockType}/${blockId}/test-cases`, serverPayload);
360
1391
  }
@@ -362,21 +1393,23 @@ export class ApiClient {
362
1393
  const serverPayload = {};
363
1394
  if (payload.name !== undefined)
364
1395
  serverPayload.name = payload.name;
1396
+ if (payload.description !== undefined) {
1397
+ serverPayload.description = payload.description;
1398
+ }
1399
+ // #2769 — parsed on the wire (see `createTestCase`), and an explicit `null`
1400
+ // is how the authored file clears a field: the handler only touches keys
1401
+ // that are present, so an omitted key retains the previous value.
365
1402
  if (payload.inputVariables !== undefined) {
366
- serverPayload.inputVariables = JSON.stringify(payload.inputVariables);
1403
+ serverPayload.inputVariables = payload.inputVariables;
367
1404
  }
368
1405
  if (payload.expectedOutputPattern !== undefined) {
369
1406
  serverPayload.expectedOutputPattern = payload.expectedOutputPattern;
370
1407
  }
371
1408
  if (payload.expectedOutputContains !== undefined) {
372
- serverPayload.expectedOutputContains = payload.expectedOutputContains
373
- ? JSON.stringify(payload.expectedOutputContains)
374
- : null;
1409
+ serverPayload.expectedOutputContains = payload.expectedOutputContains;
375
1410
  }
376
1411
  if (payload.expectedJsonSubset !== undefined) {
377
- serverPayload.expectedJsonSubset = payload.expectedJsonSubset
378
- ? JSON.stringify(payload.expectedJsonSubset)
379
- : null;
1412
+ serverPayload.expectedJsonSubset = payload.expectedJsonSubset;
380
1413
  }
381
1414
  if (payload.configId !== undefined)
382
1415
  serverPayload.configId = payload.configId;
@@ -386,6 +1419,8 @@ export class ApiClient {
386
1419
  if (payload.evaluatorConfigId !== undefined) {
387
1420
  serverPayload.evaluatorConfigId = payload.evaluatorConfigId;
388
1421
  }
1422
+ if (payload.key !== undefined)
1423
+ serverPayload.key = payload.key;
389
1424
  return this.patch(`/admin/api/apps/${appId}/blocks/${blockType}/${blockId}/test-cases/${testCaseId}`, serverPayload);
390
1425
  }
391
1426
  async deleteTestCase(appId, blockType, blockId, testCaseId) {
@@ -415,14 +1450,8 @@ export class ApiClient {
415
1450
  });
416
1451
  const text = await response.text();
417
1452
  if (!response.ok) {
418
- let errorData;
419
- try {
420
- errorData = JSON.parse(text);
421
- }
422
- catch {
423
- errorData = { message: text || `HTTP ${response.status}` };
424
- }
425
- throw new ApiError(errorData.message || `HTTP ${response.status}`, response.status, errorData.code);
1453
+ const parsed = parseErrorResponse(response, text, url);
1454
+ throw new ApiError(parsed.message, response.status, parsed.code, parsed.details);
426
1455
  }
427
1456
  return text ? JSON.parse(text) : null;
428
1457
  }
@@ -442,14 +1471,8 @@ export class ApiClient {
442
1471
  });
443
1472
  if (!response.ok) {
444
1473
  const text = await response.text();
445
- let errorData;
446
- try {
447
- errorData = JSON.parse(text);
448
- }
449
- catch {
450
- errorData = { message: text || `HTTP ${response.status}` };
451
- }
452
- throw new ApiError(errorData.message || `HTTP ${response.status}`, response.status, errorData.code);
1474
+ const parsed = parseErrorResponse(response, text, url);
1475
+ throw new ApiError(parsed.message, response.status, parsed.code, parsed.details);
453
1476
  }
454
1477
  const arrayBuffer = await response.arrayBuffer();
455
1478
  return {
@@ -481,12 +1504,23 @@ export class ApiClient {
481
1504
  const result = await this.get(`/admin/api/apps/${appId}/workflows`, params);
482
1505
  return {
483
1506
  items: result?.items ?? [],
1507
+ hasMore: result?.hasMore,
484
1508
  nextCursor: result?.nextCursor ?? null,
485
1509
  };
486
1510
  }
487
1511
  async getWorkflow(appId, workflowId) {
488
1512
  return this.get(`/admin/api/apps/${appId}/workflows/${workflowId}`);
489
1513
  }
1514
+ /**
1515
+ * One app's workflow step usage report (#3132).
1516
+ *
1517
+ * `windowDays` is omitted from the query when the caller did not ask for a
1518
+ * window, so the server applies its own default rather than the CLI
1519
+ * restating it on the wire.
1520
+ */
1521
+ async getWorkflowUsage(appId, params) {
1522
+ return this.get(`/admin/api/apps/${appId}/workflows/usage`, params);
1523
+ }
490
1524
  async createWorkflow(appId, payload) {
491
1525
  return this.post(`/admin/api/apps/${appId}/workflows`, payload);
492
1526
  }
@@ -494,15 +1528,33 @@ export class ApiClient {
494
1528
  const body = expectedModifiedAt ? { ...payload, expectedModifiedAt } : payload;
495
1529
  return this.patch(`/admin/api/apps/${appId}/workflows/${workflowId}`, body);
496
1530
  }
497
- async deleteWorkflow(appId, workflowId) {
498
- return this.delete(`/admin/api/apps/${appId}/workflows/${workflowId}`);
1531
+ /**
1532
+ * Retire a workflow, or destroy it (#2887).
1533
+ *
1534
+ * The plain call ARCHIVES: the definition row stays, so its runs, revisions
1535
+ * and test cases keep resolving. `{ hard: true }` performs the full cascade
1536
+ * and is what releases the `workflowKey` — the flag `config push --prune`
1537
+ * sends, for the same reason it sends it for webhooks and integrations.
1538
+ */
1539
+ async deleteWorkflow(appId, workflowId, options) {
1540
+ const path = `/admin/api/apps/${appId}/workflows/${workflowId}`;
1541
+ return this.delete(options?.hard ? `${path}?hard=true` : path);
1542
+ }
1543
+ /**
1544
+ * #2645 criterion 9 — the operational toggle. Deliberately NOT the config
1545
+ * PATCH: `config push` owns every configuration field, and taking a workflow
1546
+ * out of service must not touch one, or an operator's action would show up as
1547
+ * drift against the repo. Same route shape as `cron-triggers pause|resume`.
1548
+ */
1549
+ async disableWorkflow(appId, workflowId) {
1550
+ return this.post(`/app/${appId}/api/workflows/${workflowId}/disable`, {});
1551
+ }
1552
+ async enableWorkflow(appId, workflowId) {
1553
+ return this.post(`/app/${appId}/api/workflows/${workflowId}/enable`, {});
499
1554
  }
500
1555
  async updateWorkflowDraft(appId, workflowId, payload) {
501
1556
  return this.put(`/admin/api/apps/${appId}/workflows/${workflowId}/draft`, payload);
502
1557
  }
503
- async publishWorkflow(appId, workflowId) {
504
- return this.post(`/admin/api/apps/${appId}/workflows/${workflowId}/publish`, {});
505
- }
506
1558
  async previewWorkflow(appId, workflowId, payload) {
507
1559
  return this.post(`/admin/api/apps/${appId}/workflows/${workflowId}/preview`, payload);
508
1560
  }
@@ -511,14 +1563,40 @@ export class ApiClient {
511
1563
  }
512
1564
  async listWorkflowRuns(appId, workflowId, params) {
513
1565
  const result = await this.get(`/admin/api/apps/${appId}/workflows/${workflowId}/runs`, params);
1566
+ const nextCursor = result?.nextCursor ?? null;
1567
+ return {
1568
+ items: result?.items ?? [],
1569
+ hasMore: result?.hasMore,
1570
+ nextCursor,
1571
+ resumeAfter: result?.resumeAfter,
1572
+ scanned: typeof result?.scanned === "number" ? result.scanned : undefined,
1573
+ };
1574
+ }
1575
+ /**
1576
+ * Workflow runs started by one app user, across every workflow (#1967).
1577
+ * Backed by `GET /admin/api/apps/{appId}/users/{userId}/workflow-runs`,
1578
+ * which resolves the app user before querying the `runsByUser` index.
1579
+ */
1580
+ async listUserWorkflowRuns(appId, userId, params) {
1581
+ const result = await this.get(`/admin/api/apps/${appId}/users/${encodeURIComponent(userId)}/workflow-runs`, params);
1582
+ const nextCursor = result?.nextCursor ?? null;
514
1583
  return {
515
1584
  items: result?.items ?? [],
516
- cursor: result?.cursor ?? null,
1585
+ hasMore: result?.hasMore,
1586
+ nextCursor,
1587
+ scanned: typeof result?.scanned === "number" ? result.scanned : undefined,
517
1588
  };
518
1589
  }
519
1590
  async getWorkflowRunStatus(appId, workflowId, runId) {
520
1591
  return this.get(`/admin/api/apps/${appId}/workflows/${workflowId}/runs/${runId}/status`);
521
1592
  }
1593
+ async getWorkflowStepRuns(appId, workflowId, runId) {
1594
+ const result = await this.get(`/admin/api/apps/${appId}/workflows/${workflowId}/runs/${runId}/steps`);
1595
+ return { items: result?.items ?? [] };
1596
+ }
1597
+ // Workflow analytics have one client path, `getAnalyticsTopWorkflows`
1598
+ // (issue #2766): `getTopWorkflows` was a second name for the same endpoint,
1599
+ // and `getWorkflowAnalytics` called a route the server never registered.
522
1600
  // ============================================
523
1601
  // WORKFLOW CONFIGURATIONS
524
1602
  // ============================================
@@ -547,29 +1625,78 @@ export class ApiClient {
547
1625
  // ============================================
548
1626
  // ANALYTICS
549
1627
  // ============================================
550
- async getAnalyticsOverview(appId, params) {
551
- return this.get(`/app/${appId}/api/analytics/overview`, params);
552
- }
553
1628
  async getAnalyticsTopUsers(appId, params) {
554
1629
  return this.get(`/app/${appId}/api/analytics/users/top`, params);
555
1630
  }
556
- async getAnalyticsUserTimeline(appId, userUlid, params) {
557
- return this.get(`/app/${appId}/api/analytics/users/${userUlid}/timeline`, params);
558
- }
559
- async getAnalyticsUserEvents(appId, userUlid, params) {
560
- return this.get(`/app/${appId}/api/analytics/users/${userUlid}/events`, params);
561
- }
562
1631
  async getAnalyticsIntegrationMetrics(appId, params) {
563
1632
  return this.get(`/app/${appId}/api/analytics/integrations`, params);
564
1633
  }
1634
+ async getAnalyticsOverviewDau(appId) {
1635
+ return this.get(`/app/${appId}/api/analytics/overview/dau`);
1636
+ }
1637
+ async getAnalyticsOverviewWau(appId) {
1638
+ return this.get(`/app/${appId}/api/analytics/overview/wau`);
1639
+ }
1640
+ async getAnalyticsOverviewMau(appId) {
1641
+ return this.get(`/app/${appId}/api/analytics/overview/mau`);
1642
+ }
1643
+ async getAnalyticsOverviewGrowth(appId, params) {
1644
+ return this.get(`/app/${appId}/api/analytics/overview/growth`, params);
1645
+ }
1646
+ async getAnalyticsDailyActive(appId, params) {
1647
+ return this.get(`/app/${appId}/api/analytics/daily-active`, params);
1648
+ }
1649
+ async getAnalyticsRollingActive(appId, params) {
1650
+ return this.get(`/app/${appId}/api/analytics/rolling-active`, params);
1651
+ }
1652
+ async getAnalyticsCohortRetention(appId) {
1653
+ return this.get(`/app/${appId}/api/analytics/cohort-retention`);
1654
+ }
1655
+ async getAnalyticsUserSearch(appId, params) {
1656
+ return this.get(`/app/${appId}/api/analytics/users/search`, params);
1657
+ }
1658
+ async getAnalyticsUserDetail(appId, userUlid) {
1659
+ return this.get(`/app/${appId}/api/analytics/users/${userUlid}/detail`);
1660
+ }
1661
+ async getAnalyticsUserSnapshot(appId, userUlid) {
1662
+ return this.get(`/app/${appId}/api/analytics/users/${userUlid}/snapshot`);
1663
+ }
1664
+ async getAnalyticsEvents(appId, params) {
1665
+ return this.get(`/app/${appId}/api/analytics/events`, params);
1666
+ }
1667
+ async getAnalyticsEventsGrouped(appId, params) {
1668
+ return this.get(`/app/${appId}/api/analytics/events/grouped`, params);
1669
+ }
1670
+ async getAnalyticsErrorsGroups(appId, params) {
1671
+ return this.get(`/app/${appId}/api/analytics/errors/groups`, params);
1672
+ }
1673
+ async getAnalyticsTopWorkflows(appId, params) {
1674
+ return this.get(`/app/${appId}/api/analytics/workflows/top`, params);
1675
+ }
1676
+ async getAnalyticsTopPrompts(appId, params) {
1677
+ return this.get(`/app/${appId}/api/analytics/prompts/top`, params);
1678
+ }
565
1679
  // ============================================
566
1680
  // SUPER ADMIN: ADMINS
567
1681
  // ============================================
1682
+ /**
1683
+ * The signed-in admin's own profile, `role` included.
1684
+ *
1685
+ * The role is read from the server rather than from the cached credentials
1686
+ * file: a role changed after login would otherwise let a stale local record
1687
+ * decide an authorization question.
1688
+ */
1689
+ async getMe() {
1690
+ return this.get("/admin/api/me");
1691
+ }
568
1692
  async listAllAdmins(params) {
569
1693
  const result = await this.get("/admin/api/admins", params);
1694
+ const nextCursor = result?.nextCursor ?? null;
1695
+ const items = result?.items ?? [];
570
1696
  return {
571
- admins: result?.admins ?? [],
572
- cursor: result?.cursor ?? null,
1697
+ items,
1698
+ hasMore: result?.hasMore,
1699
+ nextCursor,
573
1700
  };
574
1701
  }
575
1702
  async searchAdminByEmail(email) {
@@ -602,6 +1729,7 @@ export class ApiClient {
602
1729
  const result = await this.get("/admin/api/catalog/prompts", params);
603
1730
  return {
604
1731
  items: result?.items ?? [],
1732
+ hasMore: result?.hasMore,
605
1733
  nextCursor: result?.nextCursor ?? null,
606
1734
  };
607
1735
  }
@@ -621,6 +1749,7 @@ export class ApiClient {
621
1749
  const result = await this.get("/admin/api/catalog/integrations", params);
622
1750
  return {
623
1751
  items: result?.items ?? [],
1752
+ hasMore: result?.hasMore,
624
1753
  nextCursor: result?.nextCursor ?? null,
625
1754
  };
626
1755
  }
@@ -637,21 +1766,6 @@ export class ApiClient {
637
1766
  return this.delete(`/admin/api/catalog/integrations/${catalogId}`);
638
1767
  }
639
1768
  // ============================================
640
- // LLM UTILITIES
641
- // ============================================
642
- async listLlmModels(provider = "openrouter") {
643
- return this.get("/admin/api/llm/models", { provider });
644
- }
645
- async generatePrompt(payload) {
646
- return this.post("/admin/api/llm/generate-prompt", payload);
647
- }
648
- async generateEvaluator(payload) {
649
- return this.post("/admin/api/llm/generate-evaluator", payload);
650
- }
651
- async generateWorkflowEvaluator(payload) {
652
- return this.post("/admin/api/llm/generate-evaluator-workflow", payload);
653
- }
654
- // ============================================
655
1769
  // BATCH TEST EXECUTION
656
1770
  // ============================================
657
1771
  async startBatchTests(appId, blockType, blockId, payload) {
@@ -670,6 +1784,33 @@ export class ApiClient {
670
1784
  return this.get(`/admin/api/apps/${appId}/comparisons/${group}`);
671
1785
  }
672
1786
  // ============================================
1787
+ // EMAIL TEMPLATES
1788
+ // ============================================
1789
+ async listEmailTemplates(appId) {
1790
+ return this.get(`/admin/api/apps/${appId}/email-templates`);
1791
+ }
1792
+ async getEmailTemplate(appId, emailType) {
1793
+ return this.get(`/admin/api/apps/${appId}/email-templates/${emailType}`);
1794
+ }
1795
+ /**
1796
+ * Create or replace an email-template override.
1797
+ *
1798
+ * `expectedModifiedAt` is the optimistic-concurrency token every sibling
1799
+ * config endpoint already takes (#2731 B10). Optional and additive: when
1800
+ * omitted the write is unconditional, which is how `--force` and every
1801
+ * pre-existing caller keep working; when supplied and stale, the server
1802
+ * answers 409 rather than silently overwriting a concurrent edit.
1803
+ */
1804
+ async upsertEmailTemplate(appId, emailType, payload, expectedModifiedAt) {
1805
+ return this.put(`/admin/api/apps/${appId}/email-templates/${emailType}`, expectedModifiedAt ? { ...payload, expectedModifiedAt } : payload);
1806
+ }
1807
+ async deleteEmailTemplate(appId, emailType) {
1808
+ return this.delete(`/admin/api/apps/${appId}/email-templates/${emailType}`);
1809
+ }
1810
+ async testEmailTemplate(appId, emailType, payload) {
1811
+ return this.post(`/admin/api/apps/${appId}/email-templates/${emailType}/test`, payload || {});
1812
+ }
1813
+ // ============================================
673
1814
  // ACCESS TOKENS
674
1815
  // ============================================
675
1816
  async createToken(appId, data) {
@@ -688,8 +1829,54 @@ export class ApiClient {
688
1829
  // ============================================
689
1830
  // DATABASES
690
1831
  // ============================================
691
- async listDatabases(appId) {
692
- return this.get(`/app/${appId}/api/databases`);
1832
+ /**
1833
+ * List an app's databases, following the cursor to the end.
1834
+ *
1835
+ * The endpoint returns the `{ items, hasMore, nextCursor }` envelope and
1836
+ * caps a page at 100 (#1958), so `databases list` needs the follow-up pages
1837
+ * to show every database. `paginateAll` carries the repeat-cursor and
1838
+ * max-page guards, so a server that hands out a non-advancing cursor fails
1839
+ * loudly instead of looping forever.
1840
+ *
1841
+ * `options.owner` narrows the result to the databases that user created; the
1842
+ * server resolves it through the `databasesByCreator` index (#1965).
1843
+ */
1844
+ /**
1845
+ * One page of an app's databases (#3646).
1846
+ *
1847
+ * `databases list` used to walk the chain here. The route pages, so the page
1848
+ * boundary belongs to the caller: the verb declares `--limit`/`--cursor` and
1849
+ * prints what came back.
1850
+ */
1851
+ async listDatabases(appId, options) {
1852
+ const params = new URLSearchParams();
1853
+ if (options?.owner)
1854
+ params.set("owner", options.owner);
1855
+ if (options?.limit !== undefined)
1856
+ params.set("limit", String(options.limit));
1857
+ if (options?.cursor)
1858
+ params.set("cursor", options.cursor);
1859
+ const qs = params.toString() ? `?${params.toString()}` : "";
1860
+ const resp = await this.get(`/app/${appId}/api/databases${qs}`);
1861
+ // Tolerant read: a server older than #1958 answers with a bare array.
1862
+ // Without this a published CLI pointed at a not-yet-upgraded server would
1863
+ // print nothing at all. Such a server also predates the `owner` filter
1864
+ // (#1965) and ignores the unknown query parameter, so apply the filter
1865
+ // here — the legacy rows carry `createdBy`, so this reproduces the
1866
+ // server's own post-join filter (#2245). It has no pages either.
1867
+ if (Array.isArray(resp)) {
1868
+ return {
1869
+ items: options?.owner
1870
+ ? resp.filter((db) => db?.createdBy === options.owner)
1871
+ : resp,
1872
+ hasMore: false,
1873
+ };
1874
+ }
1875
+ return {
1876
+ items: resp?.items ?? [],
1877
+ hasMore: resp?.hasMore,
1878
+ nextCursor: resp?.nextCursor ?? null,
1879
+ };
693
1880
  }
694
1881
  async createDatabase(appId, data) {
695
1882
  return this.post(`/app/${appId}/api/databases`, data);
@@ -703,31 +1890,59 @@ export class ApiClient {
703
1890
  async deleteDatabase(appId, databaseId) {
704
1891
  return this.delete(`/app/${appId}/api/databases/${databaseId}`);
705
1892
  }
1893
+ /**
1894
+ * Read a database's CEL context dict.
1895
+ *
1896
+ * The HTTP path stays `/metadata` because the wire field name is still
1897
+ * `metadata`; only the client/CLI-facing helper names were reframed.
1898
+ *
1899
+ * @deprecated Use resource metadata categories instead (`primitive metadata
1900
+ * get database <id> <category>`, #1420, #1815).
1901
+ */
1902
+ async getDatabaseCelContext(appId, databaseId) {
1903
+ return this.get(`/app/${appId}/api/databases/${databaseId}/metadata`);
1904
+ }
1905
+ /**
1906
+ * Update a database's CEL context dict (merge with existing).
1907
+ *
1908
+ * @deprecated Use resource metadata categories instead (`primitive metadata
1909
+ * set database <id> <category>`, #1420, #1815).
1910
+ */
1911
+ async updateDatabaseCelContext(appId, databaseId, celContext) {
1912
+ return this.patch(`/app/${appId}/api/databases/${databaseId}/metadata`, celContext);
1913
+ }
1914
+ /**
1915
+ * @deprecated Database CEL context is deprecated; use resource metadata
1916
+ * categories instead (`primitive metadata get database <id> <category>`,
1917
+ * #1420, #1815).
1918
+ */
1919
+ async getDatabaseMetadata(appId, databaseId) {
1920
+ return this.getDatabaseCelContext(appId, databaseId);
1921
+ }
1922
+ /**
1923
+ * @deprecated Database CEL context is deprecated; use resource metadata
1924
+ * categories instead (`primitive metadata set database <id> <category>`,
1925
+ * #1420, #1815).
1926
+ */
1927
+ async updateDatabaseMetadata(appId, databaseId, metadata) {
1928
+ return this.updateDatabaseCelContext(appId, databaseId, metadata);
1929
+ }
706
1930
  // ============================================
707
1931
  // DATABASE PERMISSIONS
708
1932
  // ============================================
709
1933
  async listDatabasePermissions(appId, databaseId) {
710
1934
  return this.get(`/app/${appId}/api/databases/${databaseId}/permissions`);
711
1935
  }
712
- async grantDatabasePermission(appId, databaseId, data) {
713
- return this.put(`/app/${appId}/api/databases/${databaseId}/permissions`, data);
1936
+ async addDatabaseManager(appId, databaseId, userId) {
1937
+ return this.put(`/app/${appId}/api/databases/${databaseId}/permissions`, {
1938
+ userId,
1939
+ permission: "manager",
1940
+ });
714
1941
  }
715
- async revokeDatabasePermission(appId, databaseId, userId) {
1942
+ async removeDatabaseManager(appId, databaseId, userId) {
716
1943
  return this.delete(`/app/${appId}/api/databases/${databaseId}/permissions/${userId}`);
717
1944
  }
718
1945
  // ============================================
719
- // DATABASE GROUP PERMISSIONS
720
- // ============================================
721
- async listDatabaseGroupPermissions(appId, databaseId) {
722
- return this.get(`/app/${appId}/api/databases/${databaseId}/group-permissions`);
723
- }
724
- async grantDatabaseGroupPermission(appId, databaseId, data) {
725
- return this.post(`/app/${appId}/api/databases/${databaseId}/group-permissions`, data);
726
- }
727
- async revokeDatabaseGroupPermission(appId, databaseId, groupType, groupId) {
728
- return this.delete(`/app/${appId}/api/databases/${databaseId}/group-permissions/${groupType}/${groupId}`);
729
- }
730
- // ============================================
731
1946
  // DATABASE RECORDS & SCHEMA
732
1947
  // ============================================
733
1948
  async listDatabaseModels(appId, databaseId) {
@@ -736,17 +1951,140 @@ export class ApiClient {
736
1951
  async describeDatabaseModel(appId, databaseId, modelName) {
737
1952
  return this.get(`/app/${appId}/api/databases/${databaseId}/records/describe`, { modelName });
738
1953
  }
739
- async queryDatabaseRecords(appId, databaseId, data) {
740
- return this.post(`/app/${appId}/api/databases/${databaseId}/records/query`, data);
741
- }
742
- async saveDatabaseRecord(appId, databaseId, data) {
743
- return this.post(`/app/${appId}/api/databases/${databaseId}/records/save`, data);
1954
+ /**
1955
+ * Query records in a database model. The Durable Object answers with its own
1956
+ * `{ data, hasMore, nextCursor?, prevCursor? }` envelope; that wire shape is
1957
+ * shared with the JS client, the Swift client and web-admin, so the CLI
1958
+ * normalizes it at its own boundary instead (issue #2357) and hands callers
1959
+ * the same `{ items, hasMore, nextCursor? }` envelope as
1960
+ * {@link queryDocumentRecords}.
1961
+ */
1962
+ async queryDatabaseRecords(appId, databaseId, modelName, queryOptions) {
1963
+ const body = { modelName };
1964
+ if (queryOptions?.filter)
1965
+ body.filter = queryOptions.filter;
1966
+ const options = {};
1967
+ if (queryOptions?.limit)
1968
+ options.limit = queryOptions.limit;
1969
+ if (queryOptions?.cursor)
1970
+ options.uniqueStartKey = queryOptions.cursor;
1971
+ if (Object.keys(options).length > 0)
1972
+ body.options = options;
1973
+ const raw = await this.post(`/app/${appId}/api/databases/${databaseId}/records/query`, body);
1974
+ return normalizeCliListEnvelope(raw);
1975
+ }
1976
+ async countDatabaseRecords(appId, databaseId, modelName, filter) {
1977
+ const body = { modelName };
1978
+ if (filter)
1979
+ body.filter = filter;
1980
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/count`, body);
1981
+ }
1982
+ async aggregateDatabaseRecords(appId, databaseId, modelName, options) {
1983
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/aggregate`, {
1984
+ modelName,
1985
+ options,
1986
+ });
744
1987
  }
745
- async deleteDatabaseRecord(appId, databaseId, data) {
746
- return this.post(`/app/${appId}/api/databases/${databaseId}/records/delete`, data);
1988
+ /**
1989
+ * Upsert one record via `records/save`: creates the record when the id is
1990
+ * new, and merges the supplied fields into it when it already exists (the DO
1991
+ * writes with `ON CONFLICT … json_patch`, so fields you leave out survive).
1992
+ * `patchDatabaseRecord` is the same merge but requires the record to exist.
1993
+ *
1994
+ * `id` is optional: when omitted the body carries no `id`, which the
1995
+ * DatabaseDO only accepts alongside an `upsertOn` field — callers that want a
1996
+ * plain create must supply an id themselves (`databases records save` mints a
1997
+ * ULID, matching the CSV import path).
1998
+ *
1999
+ * Returns the endpoint's flat `{ success, id, appliedFields }` — not the
2000
+ * saved record.
2001
+ */
2002
+ async saveDatabaseRecord(appId, databaseId, modelName, id, data) {
2003
+ const body = { modelName, data };
2004
+ if (id !== undefined)
2005
+ body.id = id;
2006
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/save`, body);
2007
+ }
2008
+ /**
2009
+ * Merge the supplied fields into an existing record via `records/patch`.
2010
+ *
2011
+ * Fields absent from `data` are left as they are. Unlike `saveDatabaseRecord`
2012
+ * the record must already exist — the DatabaseDO answers 404 for an unknown
2013
+ * id rather than creating one. Returns the flat
2014
+ * `{ success, id, appliedFields }`.
2015
+ */
2016
+ async patchDatabaseRecord(appId, databaseId, modelName, id, data) {
2017
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/patch`, {
2018
+ modelName,
2019
+ id,
2020
+ data,
2021
+ });
747
2022
  }
748
- async countDatabaseRecords(appId, databaseId, data) {
749
- return this.post(`/app/${appId}/api/databases/${databaseId}/records/count`, data);
2023
+ // ============================================
2024
+ // DATABASE OPERATIONS (registered operations)
2025
+ // ============================================
2026
+ async listDatabaseOperations(appId, databaseId) {
2027
+ return this.get(`/app/${appId}/api/databases/${databaseId}/operations`);
2028
+ }
2029
+ /**
2030
+ * Execute a registered operation and, when the result is a query page,
2031
+ * normalize it to the CLI's one list envelope (issue #2440).
2032
+ *
2033
+ * The registered operation decides the response shape, so the normalization
2034
+ * is conditional — see {@link normalizeDatabaseOperationResult}. Everything
2035
+ * else (a `count`, an `aggregate`, a mutation, a `returnField: "all"`
2036
+ * pipeline) is returned exactly as the server sent it.
2037
+ */
2038
+ async executeDatabaseOperation(appId, databaseId, operationName, data, token, options) {
2039
+ const path = `/app/${appId}/api/databases/${databaseId}/operations/${encodeURIComponent(operationName)}/execute`;
2040
+ const extraHeaders = {};
2041
+ if (options?.timing) {
2042
+ extraHeaders["X-Timing"] = "true";
2043
+ }
2044
+ if (token) {
2045
+ return normalizeDatabaseOperationResult(await this.requestWithToken(path, token, {
2046
+ method: "POST",
2047
+ body: JSON.stringify(data || {}),
2048
+ headers: extraHeaders,
2049
+ }));
2050
+ }
2051
+ return normalizeDatabaseOperationResult(await this.request(path, {
2052
+ method: "POST",
2053
+ body: JSON.stringify(data || {}),
2054
+ headers: extraHeaders,
2055
+ }));
2056
+ }
2057
+ /**
2058
+ * Execute a registered batch (bulk) database operation. Posts a chunk of
2059
+ * items to the canonical `operations/:name/batch` endpoint (the same one the
2060
+ * client library's `executeBatch` uses — NOT the deprecated `import-bulk`
2061
+ * alias). Used by `databases import-csv`.
2062
+ *
2063
+ * @returns `{ imported, failed }` — DO-level write outcome counts. Per-item
2064
+ * validation/access failures abort the whole chunk with a 4xx (thrown).
2065
+ */
2066
+ async executeBatch(appId, databaseId, operationName, batch) {
2067
+ return this.post(`/app/${appId}/api/databases/${databaseId}/operations/${encodeURIComponent(operationName)}/batch`, { batch });
2068
+ }
2069
+ /**
2070
+ * Make a request using a specific JWT token instead of the CLI's credentials.
2071
+ * Used for executing operations as a different user.
2072
+ */
2073
+ async requestWithToken(path, token, options = {}) {
2074
+ const credentials = await this.ensureAuthenticated();
2075
+ const url = `${credentials.serverUrl}${path}`;
2076
+ const headers = {
2077
+ Authorization: `Bearer ${token}`,
2078
+ "Content-Type": "application/json",
2079
+ ...(options.headers || {}),
2080
+ };
2081
+ const response = await fetchWithTLS(url, { ...options, headers });
2082
+ const text = await response.text();
2083
+ if (!response.ok) {
2084
+ const parsed = parseErrorResponse(response, text, path);
2085
+ throw new ApiError(parsed.message, response.status, parsed.code, parsed.details);
2086
+ }
2087
+ return text ? JSON.parse(text) : null;
750
2088
  }
751
2089
  // ============================================
752
2090
  // DATABASE INDEXES
@@ -760,11 +2098,157 @@ export class ApiClient {
760
2098
  async dropDatabaseIndex(appId, databaseId, data) {
761
2099
  return this.post(`/app/${appId}/api/databases/${databaseId}/records/index/drop`, data);
762
2100
  }
2101
+ /**
2102
+ * Issue #974: back-provision an existing database instance's schema-declared
2103
+ * unique indexes by reading its type schema and registering any declared-but-
2104
+ * missing unique index. Idempotent.
2105
+ */
2106
+ async reindexDatabaseFromSchema(appId, databaseId) {
2107
+ return this.post(`/app/${appId}/api/databases/${databaseId}/reindex`, {});
2108
+ }
2109
+ // ============================================
2110
+ // DATABASE TYPE CONFIGS
2111
+ // ============================================
2112
+ async listDatabaseTypeConfigs(appId) {
2113
+ return this.get(`/app/${appId}/api/databases/types`);
2114
+ }
2115
+ async getDatabaseTypeConfig(appId, databaseType) {
2116
+ return this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}`);
2117
+ }
2118
+ async createDatabaseTypeConfig(appId, data,
2119
+ // Issue #1336 (codex round-1 P2): `dryRun` runs every create-time
2120
+ // validation (inline CEL rule lint, manifest shape, schema TOML parse)
2121
+ // WITHOUT persisting, so a fresh-type `config push --dry-run` surfaces a
2122
+ // malformed `defaultAccess`/manifest the same way the real POST would.
2123
+ options) {
2124
+ const query = options?.dryRun ? "?dryRun=true" : "";
2125
+ return this.post(`/app/${appId}/api/databases/types${query}`, data);
2126
+ }
2127
+ async updateDatabaseTypeConfig(appId, databaseType, data, expectedModifiedAt, options) {
2128
+ const body = expectedModifiedAt ? { ...data, expectedModifiedAt } : data;
2129
+ const qs = new URLSearchParams();
2130
+ if (options?.dryRun)
2131
+ qs.set("dryRun", "true");
2132
+ if (options?.acceptWarnings)
2133
+ qs.set("acceptWarnings", "true");
2134
+ const query = qs.toString();
2135
+ const path = `/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}${query ? `?${query}` : ""}`;
2136
+ return this.patch(path, body);
2137
+ }
2138
+ async deleteDatabaseTypeConfig(appId, databaseType, options) {
2139
+ const query = options?.force ? "?force=true" : "";
2140
+ return this.delete(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}${query}`);
2141
+ }
2142
+ /**
2143
+ * Issue #666 Phase 3: ask the server to scaffold a TOML schema from
2144
+ * existing ops + DO field introspection. Read-only — does NOT persist.
2145
+ */
2146
+ async scaffoldDatabaseTypeSchema(appId, databaseType) {
2147
+ return this.post(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/schema:scaffold`, {});
2148
+ }
2149
+ // ============================================
2150
+ // DATABASE TYPE OPERATIONS
2151
+ // ============================================
2152
+ async listDatabaseTypeOperations(appId, databaseType) {
2153
+ return this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations`);
2154
+ }
2155
+ async getDatabaseTypeOperation(appId, databaseType, name) {
2156
+ return this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations/${encodeURIComponent(name)}`);
2157
+ }
2158
+ async createDatabaseTypeOperation(appId, databaseType, data,
2159
+ // Issue #813 (1A): when `dryRun` is set the server runs the op-edit gate
2160
+ // without persisting — used by `config push --dry-run` to surface gate
2161
+ // failures the real push would hit. `schemaOverride` lets the gate run
2162
+ // against the schema the SAME push is about to land (so an op that depends
2163
+ // on a new field isn't falsely rejected against the stale stored schema).
2164
+ //
2165
+ // Issue #915 (defect a, follow-up): for a FRESH db-type the parent config
2166
+ // does not exist on the server yet, so the server's "access required"
2167
+ // check has no `defaultAccess` to fall back on. Thread the TOML-declared
2168
+ // type-level `defaultAccess` so an op that omits `access` (intending to
2169
+ // inherit it after the type is created) isn't falsely rejected during the
2170
+ // dry-run. Server only trusts this on the fresh-type dry-run path.
2171
+ options) {
2172
+ const query = options?.dryRun ? "?dryRun=true" : "";
2173
+ let body = data;
2174
+ if (options?.dryRun && options.schemaOverride !== undefined) {
2175
+ body = { ...body, schemaOverride: options.schemaOverride };
2176
+ }
2177
+ if (options?.dryRun && options.defaultAccess !== undefined) {
2178
+ body = { ...body, defaultAccess: options.defaultAccess };
2179
+ }
2180
+ if (options?.dryRun && options.metadataManifestOverride !== undefined) {
2181
+ body = { ...body, metadataManifestOverride: options.metadataManifestOverride };
2182
+ }
2183
+ return this.post(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations${query}`, body);
2184
+ }
2185
+ async updateDatabaseTypeOperation(appId, databaseType, name, data, expectedModifiedAt,
2186
+ // Issue #813 (1A): dry-run runs the op-edit gate without persisting.
2187
+ // `schemaOverride` gates against the schema the same push is landing.
2188
+ // Issue #1336: `metadataManifestOverride` gates the op-access lint against
2189
+ // the manifest the same push is landing (see `createDatabaseTypeOperation`).
2190
+ options) {
2191
+ let body = expectedModifiedAt ? { ...data, expectedModifiedAt } : { ...data };
2192
+ if (options?.dryRun && options.schemaOverride !== undefined) {
2193
+ body = { ...body, schemaOverride: options.schemaOverride };
2194
+ }
2195
+ if (options?.dryRun && options.metadataManifestOverride !== undefined) {
2196
+ body = { ...body, metadataManifestOverride: options.metadataManifestOverride };
2197
+ }
2198
+ const query = options?.dryRun ? "?dryRun=true" : "";
2199
+ return this.patch(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations/${encodeURIComponent(name)}${query}`, body);
2200
+ }
2201
+ async deleteDatabaseTypeOperation(appId, databaseType, name) {
2202
+ return this.delete(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/operations/${encodeURIComponent(name)}`);
2203
+ }
2204
+ // ============================================
2205
+ // DATABASE TYPE SUBSCRIPTIONS (#740 / #803)
2206
+ // ============================================
2207
+ //
2208
+ // Transparent passthroughs against the server's type-scoped subscription
2209
+ // routes (GET/POST/PUT/DELETE `/databases/types/:type/subscriptions[/:key]`).
2210
+ // The wire format is authoritative in the controller
2211
+ // (`database-type-subscriptions-controller.ts`): create requires
2212
+ // `subscriptionKey`, `displayName`, `modelName`, `filter` (CEL), `access`
2213
+ // (CEL); optional `description`, `select` (string[]), `emit`
2214
+ // (enter/update/leave subset), `params` (object, ≤5 entries), `status`.
2215
+ //
2216
+ // The list endpoint wraps results in `{ items: [...] }` (unlike operations,
2217
+ // which returns a bare array). We unwrap here so callers get an array,
2218
+ // matching `listDatabaseTypeOperations`.
2219
+ async listDatabaseTypeSubscriptions(appId, databaseType) {
2220
+ const result = await this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions`);
2221
+ if (Array.isArray(result))
2222
+ return result;
2223
+ return Array.isArray(result?.items) ? result.items : [];
2224
+ }
2225
+ async getDatabaseTypeSubscription(appId, databaseType, subscriptionKey) {
2226
+ return this.get(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions/${encodeURIComponent(subscriptionKey)}`);
2227
+ }
2228
+ async createDatabaseTypeSubscription(appId, databaseType, data) {
2229
+ return this.post(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions`, data);
2230
+ }
2231
+ async updateDatabaseTypeSubscription(appId, databaseType, subscriptionKey, data,
2232
+ // #2731 B10 — optimistic concurrency, as the sibling operation update has
2233
+ // had. Omitted (by `--force`, and by every caller predating it) means the
2234
+ // write stays unconditional.
2235
+ expectedModifiedAt) {
2236
+ return this.put(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions/${encodeURIComponent(subscriptionKey)}`, expectedModifiedAt ? { ...data, expectedModifiedAt } : data);
2237
+ }
2238
+ async deleteDatabaseTypeSubscription(appId, databaseType, subscriptionKey) {
2239
+ return this.delete(`/app/${appId}/api/databases/types/${encodeURIComponent(databaseType)}/subscriptions/${encodeURIComponent(subscriptionKey)}`);
2240
+ }
763
2241
  // ============================================
764
2242
  // GROUPS
765
2243
  // ============================================
766
2244
  async listGroups(appId, params) {
767
- return this.get(`/app/${appId}/api/groups`, params);
2245
+ const result = await this.get(`/app/${appId}/api/groups`, params);
2246
+ const nextCursor = result?.nextCursor;
2247
+ return {
2248
+ items: result?.items ?? [],
2249
+ nextCursor,
2250
+ hasMore: result?.hasMore ?? nextCursor != null,
2251
+ };
768
2252
  }
769
2253
  async createGroup(appId, data) {
770
2254
  return this.post(`/app/${appId}/api/groups`, data);
@@ -781,8 +2265,26 @@ export class ApiClient {
781
2265
  // ============================================
782
2266
  // GROUP MEMBERS
783
2267
  // ============================================
784
- async listGroupMembers(appId, groupType, groupId) {
785
- return this.get(`/app/${appId}/api/groups/${groupType}/${groupId}/members`);
2268
+ /**
2269
+ * One page of a group's members.
2270
+ *
2271
+ * The route paginates cursor-style (no default limit, cap 200) and reports
2272
+ * the boundary, so `groups members list` carries `--limit`/`--cursor` and
2273
+ * forwards them (#3646) rather than printing a first page that claims to be
2274
+ * the whole membership.
2275
+ */
2276
+ async listGroupMembers(appId, groupType, groupId, options) {
2277
+ const result = await this.get(`/app/${appId}/api/groups/${groupType}/${groupId}/members`, {
2278
+ ...(options?.include ? { include: options.include } : {}),
2279
+ ...(options?.limit !== undefined ? { limit: options.limit } : {}),
2280
+ ...(options?.cursor ? { cursor: options.cursor } : {}),
2281
+ });
2282
+ const nextCursor = result?.nextCursor;
2283
+ return {
2284
+ items: result?.items ?? [],
2285
+ nextCursor,
2286
+ hasMore: result?.hasMore ?? nextCursor != null,
2287
+ };
786
2288
  }
787
2289
  async addGroupMember(appId, groupType, groupId, data) {
788
2290
  return this.post(`/app/${appId}/api/groups/${groupType}/${groupId}/members`, data);
@@ -790,18 +2292,12 @@ export class ApiClient {
790
2292
  async removeGroupMember(appId, groupType, groupId, userId) {
791
2293
  return this.delete(`/app/${appId}/api/groups/${groupType}/${groupId}/members/${userId}`);
792
2294
  }
793
- async updateGroupMemberRole(appId, groupType, groupId, userId, data) {
794
- return this.patch(`/app/${appId}/api/groups/${groupType}/${groupId}/members/${userId}`, data);
795
- }
796
2295
  // ============================================
797
2296
  // GROUP RESOURCE LISTINGS
798
2297
  // ============================================
799
2298
  async listGroupDocuments(appId, groupType, groupId) {
800
2299
  return this.get(`/app/${appId}/api/groups/${groupType}/${groupId}/documents`);
801
2300
  }
802
- async listGroupDatabases(appId, groupType, groupId) {
803
- return this.get(`/app/${appId}/api/groups/${groupType}/${groupId}/databases`);
804
- }
805
2301
  // ============================================
806
2302
  // USER MEMBERSHIPS
807
2303
  // ============================================
@@ -821,6 +2317,159 @@ export class ApiClient {
821
2317
  return this.delete(`/app/${appId}/api/documents/${documentId}/group-permissions/${groupType}/${groupId}`);
822
2318
  }
823
2319
  // ============================================
2320
+ // COLLECTIONS
2321
+ // ============================================
2322
+ async listCollections(appId, params) {
2323
+ const qs = new URLSearchParams();
2324
+ if (params?.limit)
2325
+ qs.set("limit", String(params.limit));
2326
+ if (params?.cursor)
2327
+ qs.set("cursor", params.cursor);
2328
+ const q = qs.toString();
2329
+ const result = await this.get(`/app/${appId}/api/collections${q ? `?${q}` : ""}`);
2330
+ return {
2331
+ items: result?.items ?? [],
2332
+ hasMore: result?.hasMore,
2333
+ nextCursor: result?.nextCursor ?? null,
2334
+ };
2335
+ }
2336
+ async listAllCollections(appId, params) {
2337
+ const qs = new URLSearchParams();
2338
+ if (params?.limit)
2339
+ qs.set("limit", String(params.limit));
2340
+ if (params?.cursor)
2341
+ qs.set("cursor", params.cursor);
2342
+ const q = qs.toString();
2343
+ const result = await this.get(`/app/${appId}/api/admin/collections${q ? `?${q}` : ""}`);
2344
+ return {
2345
+ items: result?.items ?? [],
2346
+ hasMore: result?.hasMore,
2347
+ nextCursor: result?.nextCursor ?? null,
2348
+ };
2349
+ }
2350
+ async createCollection(appId, data) {
2351
+ return this.post(`/app/${appId}/api/collections`, data);
2352
+ }
2353
+ async getCollection(appId, collectionId) {
2354
+ return this.get(`/app/${appId}/api/collections/${collectionId}`);
2355
+ }
2356
+ async updateCollection(appId, collectionId, data) {
2357
+ return this.patch(`/app/${appId}/api/collections/${collectionId}`, data);
2358
+ }
2359
+ async deleteCollection(appId, collectionId) {
2360
+ return this.delete(`/app/${appId}/api/collections/${collectionId}`);
2361
+ }
2362
+ // ============================================
2363
+ // COLLECTION DOCUMENTS
2364
+ // ============================================
2365
+ async listCollectionDocuments(appId, collectionId, params) {
2366
+ const qs = new URLSearchParams();
2367
+ if (params?.limit)
2368
+ qs.set("limit", String(params.limit));
2369
+ if (params?.cursor)
2370
+ qs.set("cursor", params.cursor);
2371
+ const q = qs.toString();
2372
+ const result = await this.get(`/app/${appId}/api/collections/${collectionId}/documents${q ? `?${q}` : ""}`);
2373
+ return {
2374
+ items: result?.items ?? [],
2375
+ hasMore: result?.hasMore,
2376
+ nextCursor: result?.nextCursor ?? null,
2377
+ };
2378
+ }
2379
+ async addCollectionDocument(appId, collectionId, data) {
2380
+ return this.post(`/app/${appId}/api/collections/${collectionId}/documents`, data);
2381
+ }
2382
+ async removeCollectionDocument(appId, collectionId, documentId) {
2383
+ return this.delete(`/app/${appId}/api/collections/${collectionId}/documents/${documentId}`);
2384
+ }
2385
+ async listCollectionsForDocument(appId, documentId, params) {
2386
+ const qs = new URLSearchParams();
2387
+ if (params?.limit)
2388
+ qs.set("limit", String(params.limit));
2389
+ if (params?.cursor)
2390
+ qs.set("cursor", params.cursor);
2391
+ const q = qs.toString();
2392
+ const result = await this.get(`/app/${appId}/api/documents/${documentId}/collections${q ? `?${q}` : ""}`);
2393
+ return {
2394
+ items: result?.items ?? [],
2395
+ nextCursor: result?.nextCursor ?? null,
2396
+ };
2397
+ }
2398
+ // ============================================
2399
+ // COLLECTION ACCESS (GROUPS + MEMBERS)
2400
+ // ============================================
2401
+ async getCollectionAccess(appId, collectionId) {
2402
+ return this.get(`/app/${appId}/api/collections/${collectionId}/access`);
2403
+ }
2404
+ async grantCollectionGroupPermission(appId, collectionId, data) {
2405
+ return this.post(`/app/${appId}/api/collections/${collectionId}/group-permissions`, data);
2406
+ }
2407
+ async revokeCollectionGroupPermission(appId, collectionId, groupType, groupId) {
2408
+ return this.delete(`/app/${appId}/api/collections/${collectionId}/group-permissions/${groupType}/${groupId}`);
2409
+ }
2410
+ async addCollectionMember(appId, collectionId, data) {
2411
+ return this.post(`/app/${appId}/api/collections/${collectionId}/members`, data);
2412
+ }
2413
+ async removeCollectionMember(appId, collectionId, userId) {
2414
+ return this.delete(`/app/${appId}/api/collections/${collectionId}/members/${userId}`);
2415
+ }
2416
+ // ============================================
2417
+ // COLLECTION TYPE CONFIGS
2418
+ // ============================================
2419
+ async listCollectionTypeConfigs(appId) {
2420
+ return this.get(`/app/${appId}/api/collection-type-configs`);
2421
+ }
2422
+ async getCollectionTypeConfig(appId, collectionType) {
2423
+ return this.get(`/app/${appId}/api/collection-type-configs/${collectionType}`);
2424
+ }
2425
+ async createCollectionTypeConfig(appId, data) {
2426
+ return this.post(`/app/${appId}/api/collection-type-configs`, data);
2427
+ }
2428
+ async updateCollectionTypeConfig(appId, collectionType, data, expectedModifiedAt) {
2429
+ const body = expectedModifiedAt ? { ...data, expectedModifiedAt } : data;
2430
+ return this.patch(`/app/${appId}/api/collection-type-configs/${collectionType}`, body);
2431
+ }
2432
+ async deleteCollectionTypeConfig(appId, collectionType) {
2433
+ return this.delete(`/app/${appId}/api/collection-type-configs/${collectionType}`);
2434
+ }
2435
+ // ============================================
2436
+ // METADATA CATEGORY CONFIGS (issue #1304, P-B)
2437
+ // ============================================
2438
+ /**
2439
+ * List all metadata category configs for an app. The route returns
2440
+ * `{ configs: [...] }`; unwrap to a bare array to match the other
2441
+ * `list*Configs` helpers.
2442
+ */
2443
+ async listMetadataCategoryConfigs(appId) {
2444
+ const res = await this.get(`/app/${appId}/api/metadata-categories`);
2445
+ return Array.isArray(res?.configs) ? res.configs : [];
2446
+ }
2447
+ async getMetadataCategoryConfig(appId, resourceType, category) {
2448
+ return this.get(`/app/${appId}/api/metadata-categories/${encodeURIComponent(resourceType)}/${encodeURIComponent(category)}`);
2449
+ }
2450
+ /**
2451
+ * Create or replace a metadata category config (idempotent upsert via the
2452
+ * path-addressed PUT route). `resourceType` / `category` identify the config;
2453
+ * the body carries `schema` / `readRule` / `writeRule` / `description`.
2454
+ */
2455
+ async upsertMetadataCategoryConfig(appId, resourceType, category, data,
2456
+ /** Optimistic-concurrency token; see `upsertEmailTemplate` (#2731 B10). */
2457
+ expectedModifiedAt) {
2458
+ return this.put(`/app/${appId}/api/metadata-categories/${encodeURIComponent(resourceType)}/${encodeURIComponent(category)}`, expectedModifiedAt ? { ...data, expectedModifiedAt } : data);
2459
+ }
2460
+ /**
2461
+ * Delete a metadata category config (issue #1426, admin-gated route shipped
2462
+ * in #1364). Orphan semantics: the config row is hard-deleted; any stored
2463
+ * `ResourceMetadata` value rows for the category are left behind and become
2464
+ * unreachable (no query path from a category to its values). Delete the
2465
+ * values first if you need them gone — an orphaned value row can't be
2466
+ * removed through any surface once its config is gone. Returns
2467
+ * `{ resourceType, category, deleted }`; a missing config is a 404.
2468
+ */
2469
+ async deleteMetadataCategoryConfig(appId, resourceType, category) {
2470
+ return this.delete(`/app/${appId}/api/metadata-categories/${encodeURIComponent(resourceType)}/${encodeURIComponent(category)}`);
2471
+ }
2472
+ // ============================================
824
2473
  // ACCESS RULE SETS
825
2474
  // ============================================
826
2475
  async listRuleSets(appId, params) {
@@ -832,13 +2481,658 @@ export class ApiClient {
832
2481
  async getRuleSet(appId, ruleSetId) {
833
2482
  return this.get(`/app/${appId}/api/rule-sets/${ruleSetId}`);
834
2483
  }
835
- async updateRuleSet(appId, ruleSetId, data) {
836
- return this.patch(`/app/${appId}/api/rule-sets/${ruleSetId}`, data);
2484
+ async updateRuleSet(appId, ruleSetId, data, expectedModifiedAt) {
2485
+ const body = expectedModifiedAt ? { ...data, expectedModifiedAt } : data;
2486
+ return this.patch(`/app/${appId}/api/rule-sets/${ruleSetId}`, body);
837
2487
  }
838
2488
  async deleteRuleSet(appId, ruleSetId) {
839
2489
  return this.delete(`/app/${appId}/api/rule-sets/${ruleSetId}`);
840
2490
  }
2491
+ async getRuleSetSchema(appId) {
2492
+ return this.get(`/app/${appId}/api/rule-sets/schema`);
2493
+ }
2494
+ async getRuleSetResourceTypes(appId) {
2495
+ return this.get(`/app/${appId}/api/rule-sets/resource-types`);
2496
+ }
2497
+ async testRuleSet(appId, ruleSetId, data) {
2498
+ return this.post(`/app/${appId}/api/rule-sets/${ruleSetId}/test`, data);
2499
+ }
2500
+ async debugRuleSet(appId, data) {
2501
+ return this.post(`/app/${appId}/api/rule-sets/debug`, data);
2502
+ }
2503
+ // ============================================
2504
+ // GROUP TYPE CONFIGS
2505
+ // ============================================
2506
+ async listGroupTypeConfigs(appId) {
2507
+ return this.get(`/app/${appId}/api/group-type-configs`);
2508
+ }
2509
+ async getGroupTypeConfig(appId, groupType) {
2510
+ return this.get(`/app/${appId}/api/group-type-configs/${groupType}`);
2511
+ }
2512
+ async createGroupTypeConfig(appId, data) {
2513
+ return this.post(`/app/${appId}/api/group-type-configs`, data);
2514
+ }
2515
+ async updateGroupTypeConfig(appId, groupType, data, expectedModifiedAt) {
2516
+ const body = expectedModifiedAt ? { ...data, expectedModifiedAt } : data;
2517
+ return this.patch(`/app/${appId}/api/group-type-configs/${groupType}`, body);
2518
+ }
2519
+ async deleteGroupTypeConfig(appId, groupType) {
2520
+ return this.delete(`/app/${appId}/api/group-type-configs/${groupType}`);
2521
+ }
2522
+ // ============================================
2523
+ // DOCUMENT EXPORT / IMPORT
2524
+ // ============================================
2525
+ async exportDocumentState(appId, documentId) {
2526
+ return this.get(`/app/${appId}/api/documents/${documentId}/export/state`);
2527
+ }
2528
+ /**
2529
+ * The export chain of a large document (#2816, behavior 20): the latest
2530
+ * completed snapshot, the sealed overlays after its epoch, and the open
2531
+ * epoch's overlay inline. Every other artifact arrives as an expiring
2532
+ * signature, read through {@link downloadDocumentArtifact}.
2533
+ */
2534
+ async exportDocumentChain(appId, documentId) {
2535
+ return this.get(`/app/${appId}/api/documents/${documentId}/export/chain`);
2536
+ }
2537
+ /**
2538
+ * Read one granted artifact of a large document.
2539
+ *
2540
+ * The path comes from the chain and is origin-relative — the room is a
2541
+ * Durable Object and has no reliable idea which host the caller reached it
2542
+ * through — and the signature in it is the whole authorization, so no key is
2543
+ * ever composed here.
2544
+ */
2545
+ async downloadDocumentArtifact(_appId, grantedPath) {
2546
+ const credentials = await this.ensureAuthenticated();
2547
+ const url = `${credentials.serverUrl}${grantedPath}`;
2548
+ const response = await fetchWithTLS(url);
2549
+ if (!response.ok) {
2550
+ // #3403 — through the shared parser: the refusal this reads is the app
2551
+ // API's coded envelope, and `statusText` carried none of it.
2552
+ throw await blobFailure(response, "Failed to download document artifact: ");
2553
+ }
2554
+ return Buffer.from(await response.arrayBuffer());
2555
+ }
2556
+ async importDocumentState(appId, documentId, stateBase64) {
2557
+ return this.post(`/app/${appId}/api/documents/${documentId}/import/state`, { state: stateBase64 });
2558
+ }
2559
+ /**
2560
+ * Upload one artifact of a large document's import chain (#2816,
2561
+ * behavior 20).
2562
+ *
2563
+ * The bytes travel raw and unmodified: the manifest's digest is over the
2564
+ * STORED bytes, so re-encoding a chunk here would fail its own verification
2565
+ * on install. The query says which artifact it is — the server derives the
2566
+ * key from the document it belongs to, so nothing here composes one.
2567
+ */
2568
+ async uploadDocumentChainArtifact(appId, documentId, query, body) {
2569
+ const credentials = await this.ensureAuthenticated();
2570
+ const search = new URLSearchParams();
2571
+ for (const [key, value] of Object.entries(query)) {
2572
+ search.set(key, String(value));
2573
+ }
2574
+ const url = `${credentials.serverUrl}/app/${appId}/api/documents/${documentId}` +
2575
+ `/import/chain/artifact?${search.toString()}`;
2576
+ const headers = {
2577
+ Authorization: `Bearer ${credentials.accessToken}`,
2578
+ "Content-Type": "application/octet-stream",
2579
+ };
2580
+ if (credentials.globalAdminAppId) {
2581
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
2582
+ }
2583
+ const response = await fetchWithTLS(url, {
2584
+ method: "POST",
2585
+ headers,
2586
+ body: body,
2587
+ });
2588
+ if (!response.ok) {
2589
+ // #3403 — through the shared parser: reading `error` alone dropped the
2590
+ // envelope's `code` and `details`, so the refusal reached the operator
2591
+ // (and `primitive documents import`) with nothing to branch on.
2592
+ throw await blobFailure(response, "Failed to upload import artifact: ");
2593
+ }
2594
+ return await response.json().catch(() => ({}));
2595
+ }
2596
+ /** Start installing an uploaded chain (#2816, behavior 20). */
2597
+ async installDocumentChain(appId, documentId, plan) {
2598
+ return this.post(`/app/${appId}/api/documents/${documentId}/import/chain`, plan);
2599
+ }
2600
+ /** How far a document's chain install has got (#2816, behavior 20). */
2601
+ async getDocumentChainInstall(appId, documentId) {
2602
+ return this.get(`/app/${appId}/api/documents/${documentId}/import/chain`);
2603
+ }
2604
+ async getDocument(appId, documentId) {
2605
+ return this.get(`/app/${appId}/api/documents/${documentId}`);
2606
+ }
2607
+ /**
2608
+ * Delete a document and everything hanging off it (#2756). The server route
2609
+ * runs the same cascade the client SDK's `documents.delete()` triggers —
2610
+ * Yjs state and update history, blob rows and objects, aliases, user/group
2611
+ * permissions, invitations, collection memberships — and returns
2612
+ * `{ success, message }`, which callers pass through under `--json`.
2613
+ */
2614
+ async deleteDocument(appId, documentId) {
2615
+ return this.delete(`/app/${appId}/api/documents/${documentId}`);
2616
+ }
2617
+ /**
2618
+ * Introspect a document's Yjs schema (model names, per-model fields and
2619
+ * indexes). Backs `documents records models` and `documents records
2620
+ * describe`. Reuses the existing `GET documents/:id/schema` endpoint.
2621
+ */
2622
+ async getDocumentSchema(appId, documentId) {
2623
+ return this.get(`/app/${appId}/api/documents/${documentId}/schema`);
2624
+ }
2625
+ /**
2626
+ * The `documentFormat` a records call states, as a query string to APPEND to
2627
+ * a path (#3764).
2628
+ *
2629
+ * `post`, `patch` and `delete` take no params object — only `get` does — so
2630
+ * for every verb but the reads the parameter rides the path. Empty when the
2631
+ * caller states nothing, so an unparameterised call's URL is byte-identical
2632
+ * to what it was.
2633
+ */
2634
+ documentFormatQuery(documentFormat) {
2635
+ return documentFormat === undefined ? "" : `?documentFormat=${documentFormat}`;
2636
+ }
2637
+ /**
2638
+ * Query records in a document model (issue #1964 Phase 3). Reuses the
2639
+ * server-side `GET documents/:id/records/:model` endpoint, which runs
2640
+ * through the caller's document permission (reader+) or the app-admin arm.
2641
+ * Returns the unified `{ items, hasMore, nextCursor? }` envelope. The cursor
2642
+ * is an opaque token — feed `nextCursor` back as `cursor` for the next page.
2643
+ */
2644
+ async queryDocumentRecords(appId, documentId, modelName, queryOptions) {
2645
+ const query = {};
2646
+ if (queryOptions?.filter)
2647
+ query.filter = JSON.stringify(queryOptions.filter);
2648
+ if (queryOptions?.documentFormat !== undefined) {
2649
+ query.documentFormat = queryOptions.documentFormat;
2650
+ }
2651
+ // Forward `limit` whenever the caller supplied one (including an invalid
2652
+ // 0/negative) so the server validates and returns a clean 400 rather than
2653
+ // silently applying the default.
2654
+ if (queryOptions?.limit !== undefined)
2655
+ query.limit = queryOptions.limit;
2656
+ if (queryOptions?.cursor)
2657
+ query.cursor = queryOptions.cursor;
2658
+ const raw = await this.get(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}`, query);
2659
+ return normalizeCliListEnvelope(raw);
2660
+ }
2661
+ /**
2662
+ * Count records in a document model (issue #1964 Phase 3). Returns `{ count }`.
2663
+ */
2664
+ async countDocumentRecords(appId, documentId, modelName, queryOptions) {
2665
+ const query = {};
2666
+ if (queryOptions?.filter)
2667
+ query.filter = JSON.stringify(queryOptions.filter);
2668
+ if (queryOptions?.documentFormat !== undefined) {
2669
+ query.documentFormat = queryOptions.documentFormat;
2670
+ }
2671
+ return this.get(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}/count`, query);
2672
+ }
2673
+ /**
2674
+ * Aggregate records in a document model (issue #2437) — the documents twin
2675
+ * of {@link aggregateDatabaseRecords}. `POST documents/:id/records/:model/aggregate`
2676
+ * with `{ options: { operations, groupBy?, filter? } }`, answering `{ result }`
2677
+ * in the same shape as the database endpoint.
2678
+ *
2679
+ * `groupBy` takes plain field names only: StringSet facet grouping and
2680
+ * `{ field, contains }` membership grouping are database-only, which is why
2681
+ * this signature is narrower than the databases one.
2682
+ */
2683
+ async aggregateDocumentRecords(appId, documentId, modelName, options, extra) {
2684
+ return this.post(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}/aggregate` +
2685
+ this.documentFormatQuery(extra?.documentFormat), { options });
2686
+ }
2687
+ /**
2688
+ * Fetch platform-vocabulary document statistics (issue #1964 Phase 3):
2689
+ * record/model/blob counts, approximate size, and last-modified timestamp.
2690
+ */
2691
+ async getDocumentStats(appId, documentId) {
2692
+ return this.get(`/app/${appId}/api/documents/${documentId}/stats`);
2693
+ }
2694
+ /**
2695
+ * A large document's snapshot builds, newest first, one page (#3432).
2696
+ * `GET documents/:id/snapshots` → `{ items, hasMore, nextCursor? }`.
2697
+ */
2698
+ async listDocumentSnapshots(appId, documentId, options = {}) {
2699
+ const params = new URLSearchParams();
2700
+ if (options.limit !== undefined)
2701
+ params.set("limit", String(options.limit));
2702
+ if (options.cursor)
2703
+ params.set("cursor", options.cursor);
2704
+ const query = params.toString();
2705
+ return this.get(`/app/${appId}/api/documents/${documentId}/snapshots${query ? `?${query}` : ""}`);
2706
+ }
2707
+ /**
2708
+ * A large document's bulk-load sessions, newest first (#3434, criterion 9).
2709
+ *
2710
+ * Read-only, through the document read helper's app-admin arm — the same
2711
+ * door the snapshot readers use. The action verb `documents ingest` is
2712
+ * #3435's; these two are the operator's window onto what a session did.
2713
+ */
2714
+ async listDocumentIngests(appId, documentId, options = {}) {
2715
+ const params = new URLSearchParams();
2716
+ if (options.limit !== undefined)
2717
+ params.set("limit", String(options.limit));
2718
+ if (options.cursor)
2719
+ params.set("cursor", options.cursor);
2720
+ const query = params.toString();
2721
+ return this.get(`/app/${appId}/api/documents/${documentId}/ingest${query ? `?${query}` : ""}`);
2722
+ }
2723
+ /** One bulk-load session's status (#3434). */
2724
+ async getDocumentIngest(appId, documentId, sessionId) {
2725
+ return this.get(`/app/${appId}/api/documents/${documentId}/ingest/${encodeURIComponent(sessionId)}`);
2726
+ }
2727
+ /** Open a bulk-load session on a large document (#3435, criterion 9). */
2728
+ async createDocumentIngest(appId, documentId) {
2729
+ return this.post(`/app/${appId}/api/documents/${documentId}/ingest`, {});
2730
+ }
2731
+ /**
2732
+ * Upload one chunk of a bulk-load session's artifact (#3435).
2733
+ *
2734
+ * `multipart/form-data`: the eight descriptor fields as text parts and the
2735
+ * gzipped bytes as one file part named `chunk`. No `Content-Type` is set on
2736
+ * the request — fetch supplies the boundary, and a header written by hand
2737
+ * would name one the body does not use.
2738
+ */
2739
+ async uploadDocumentIngestChunk(appId, documentId, sessionId, chunk) {
2740
+ const credentials = await this.ensureAuthenticated();
2741
+ const form = new FormData();
2742
+ form.set("model", chunk.model);
2743
+ form.set("index", String(chunk.index));
2744
+ form.set("rows", String(chunk.rows));
2745
+ form.set("bytes", String(chunk.bytes));
2746
+ form.set("rawBytes", String(chunk.rawBytes));
2747
+ form.set("sha256", chunk.sha256);
2748
+ form.set("firstId", chunk.firstId);
2749
+ form.set("lastId", chunk.lastId);
2750
+ form.set("chunk", new Blob([chunk.body]), `${chunk.index}.ndjson.gz`);
2751
+ const headers = {
2752
+ Authorization: `Bearer ${credentials.accessToken}`,
2753
+ };
2754
+ if (credentials.globalAdminAppId) {
2755
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
2756
+ }
2757
+ const url = `${credentials.serverUrl}/app/${appId}/api/documents/${documentId}` +
2758
+ `/ingest/${encodeURIComponent(sessionId)}/chunks`;
2759
+ const response = await fetchWithTLS(url, {
2760
+ method: "POST",
2761
+ headers,
2762
+ body: form,
2763
+ });
2764
+ const text = await response.text();
2765
+ let result = {};
2766
+ try {
2767
+ result = text ? JSON.parse(text) : {};
2768
+ }
2769
+ catch {
2770
+ result = { error: text };
2771
+ }
2772
+ if (!response.ok) {
2773
+ throw new ApiError(result?.error || `Failed to upload chunk: ${response.statusText}`, response.status, result?.code, result?.details);
2774
+ }
2775
+ return result;
2776
+ }
2777
+ /** Freeze a session's manifest and hand it to the pipeline (#3435). */
2778
+ async commitDocumentIngest(appId, documentId, sessionId) {
2779
+ return this.post(`/app/${appId}/api/documents/${documentId}/ingest/${encodeURIComponent(sessionId)}/commit`, {});
2780
+ }
2781
+ /** Give a session up; allowed until the swap (#3435). */
2782
+ async abortDocumentIngest(appId, documentId, sessionId) {
2783
+ return this.post(`/app/${appId}/api/documents/${documentId}/ingest/${encodeURIComponent(sessionId)}/abort`, {});
2784
+ }
2785
+ /** One snapshot build with its verification result (#3432). */
2786
+ async getDocumentSnapshot(appId, documentId, buildId) {
2787
+ return this.get(`/app/${appId}/api/documents/${documentId}/snapshots/${encodeURIComponent(buildId)}`);
2788
+ }
2789
+ /**
2790
+ * Snapshot a large document now (#3666): seal the open epoch and start the
2791
+ * base build that seal arms.
2792
+ *
2793
+ * Answers either the epoch that was sealed with the build it armed, or
2794
+ * `{ sealed: false, reason: "empty" }` for an epoch that carried nothing.
2795
+ */
2796
+ async requestDocumentSnapshot(appId, documentId) {
2797
+ return this.post(`/app/${appId}/api/documents/${documentId}/snapshots`, {});
2798
+ }
2799
+ /**
2800
+ * Create or replace a record in a document model (issue #1964 Phase 4).
2801
+ * `POST documents/:id/records/:model` with `{ id, data, options? }` —
2802
+ * server-side write through the document facade (Yjs-first, CRDT-safe,
2803
+ * broadcasts to connected clients). Requires read-write+ on the document
2804
+ * or the app-admin arm. Returns `{ record }`.
2805
+ */
2806
+ async saveDocumentRecord(appId, documentId, modelName, body, extra) {
2807
+ return this.post(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}` +
2808
+ this.documentFormatQuery(extra?.documentFormat), body);
2809
+ }
2810
+ /**
2811
+ * Merge fields into an existing record (issue #1964 Phase 4).
2812
+ * `PATCH documents/:id/records/:model/:recordId` with `{ data, options? }`.
2813
+ * Returns `{ record }`.
2814
+ */
2815
+ async patchDocumentRecord(appId, documentId, modelName, recordId, body, extra) {
2816
+ return this.patch(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}/${encodeURIComponent(recordId)}` +
2817
+ this.documentFormatQuery(extra?.documentFormat), body);
2818
+ }
2819
+ /**
2820
+ * Delete a record from a document model (issue #1964 Phase 4).
2821
+ * `DELETE documents/:id/records/:model/:recordId`. A missing record id is
2822
+ * a silent no-op per the facade contract. Returns `{ deleted: true }`.
2823
+ */
2824
+ async deleteDocumentRecord(appId, documentId, modelName, recordId, extra) {
2825
+ return this.delete(`/app/${appId}/api/documents/${documentId}/records/${encodeURIComponent(modelName)}/${encodeURIComponent(recordId)}` +
2826
+ this.documentFormatQuery(extra?.documentFormat));
2827
+ }
2828
+ /**
2829
+ * Apply an ordered multi-model create/patch/delete blob atomically (issue
2830
+ * #1964 Phase 4, wrapping the #1517 `bulkUpdate` facade). All-or-nothing:
2831
+ * a validation failure commits nothing. Returns the facade's
2832
+ * `{ applied, added, updated, deleted }`.
2833
+ */
2834
+ async bulkDocumentRecords(appId, documentId, operations, extra) {
2835
+ return this.post(`/app/${appId}/api/documents/${documentId}/records/bulk` +
2836
+ this.documentFormatQuery(extra?.documentFormat), { operations });
2837
+ }
2838
+ async createDocument(appId, data) {
2839
+ return this.post(`/app/${appId}/api/documents`, data);
2840
+ }
2841
+ async listDocumentPermissions(appId, documentId) {
2842
+ return this.get(`/app/${appId}/api/documents/${documentId}/permissions`);
2843
+ }
2844
+ async grantDocumentPermission(appId, documentId, permissions) {
2845
+ return this.put(`/app/${appId}/api/documents/${documentId}/permissions`, { permissions });
2846
+ }
2847
+ /**
2848
+ * Revoke a user's permission on a document. Mirrors the published client's
2849
+ * `documents.removePermission` wire behavior (`src/client/api/documentsApi.ts`):
2850
+ * a userId targets the path route `DELETE .../permissions/:userId`, while an
2851
+ * email targets the query-param route `DELETE .../permissions?email=...`
2852
+ * (unified email removal, #452). This duplication of the client's wire shape
2853
+ * is deliberate and parity-tested (issue #1964 amendment 8).
2854
+ */
2855
+ async revokeDocumentPermission(appId, documentId, target) {
2856
+ if (target.email) {
2857
+ const email = encodeURIComponent(target.email);
2858
+ return this.delete(`/app/${appId}/api/documents/${documentId}/permissions?email=${email}`);
2859
+ }
2860
+ if (!target.userId) {
2861
+ throw new Error("revokeDocumentPermission: userId or email is required");
2862
+ }
2863
+ return this.delete(`/app/${appId}/api/documents/${documentId}/permissions/${target.userId}`);
2864
+ }
2865
+ /**
2866
+ * Resolve a NAMED user's effective access to a document (#3658).
2867
+ *
2868
+ * The admin token is admitted to name a subject (it can already read every
2869
+ * grant, group permission and membership the answer derives from), which is
2870
+ * what makes this an operator read rather than a per-user one.
2871
+ */
2872
+ async validateDocumentAccessForUser(appId, documentId, userId) {
2873
+ return this.post(`/app/${appId}/api/documents/${documentId}/validate-access`, { userId });
2874
+ }
2875
+ async getDocumentLinkAccess(appId, documentId) {
2876
+ return this.get(`/app/${appId}/api/documents/${documentId}/link-access`);
2877
+ }
2878
+ async setDocumentLinkAccess(appId, documentId, level) {
2879
+ return this.put(`/app/${appId}/api/documents/${documentId}/link-access`, { level });
2880
+ }
2881
+ async clearDocumentLinkAccess(appId, documentId) {
2882
+ return this.delete(`/app/${appId}/api/documents/${documentId}/link-access`);
2883
+ }
2884
+ /**
2885
+ * Pending deferred grants for a document (#2951 — replaces the removed
2886
+ * legacy `GET /documents/:id/invitations`). Returns the `{ items }`
2887
+ * envelope; rows are already filtered server-side to unresolved, unexpired
2888
+ * grants whose app invitation is still outstanding.
2889
+ */
2890
+ async listDocumentPendingInvitations(appId, documentId) {
2891
+ return this.get(`/app/${appId}/api/documents/${documentId}/pending-invitations`);
2892
+ }
2893
+ async listDocumentBlobs(appId, documentId) {
2894
+ return this.get(`/app/${appId}/api/documents/${documentId}/blobs`);
2895
+ }
2896
+ async downloadBlob(appId, documentId, blobId) {
2897
+ const credentials = await this.ensureAuthenticated();
2898
+ const url = `${credentials.serverUrl}/app/${appId}/api/documents/${documentId}/blobs/${blobId}/download`;
2899
+ const headers = {
2900
+ Authorization: `Bearer ${credentials.accessToken}`,
2901
+ };
2902
+ if (credentials.globalAdminAppId) {
2903
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
2904
+ }
2905
+ const response = await fetchWithTLS(url, { headers });
2906
+ if (!response.ok) {
2907
+ throw await blobFailure(response, "Failed to download blob: ");
2908
+ }
2909
+ const arrayBuffer = await response.arrayBuffer();
2910
+ return Buffer.from(arrayBuffer);
2911
+ }
2912
+ async uploadBlob(appId, documentId, blobId, data, meta) {
2913
+ const credentials = await this.ensureAuthenticated();
2914
+ const url = `${credentials.serverUrl}/app/${appId}/api/documents/${documentId}/blobs/${blobId}`;
2915
+ const headers = {
2916
+ Authorization: `Bearer ${credentials.accessToken}`,
2917
+ "Content-Type": meta.contentType,
2918
+ "X-Blob-Filename": encodeURIComponent(meta.filename),
2919
+ "X-Blob-Size": String(data.length),
2920
+ "X-Blob-Sha256": meta.sha256,
2921
+ };
2922
+ if (credentials.globalAdminAppId) {
2923
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
2924
+ }
2925
+ const response = await fetchWithTLS(url, {
2926
+ method: "PUT",
2927
+ headers,
2928
+ body: data,
2929
+ });
2930
+ if (!response.ok) {
2931
+ throw await blobFailure(response, "Failed to upload blob: ");
2932
+ }
2933
+ return response.json();
2934
+ }
2935
+ async listDocumentAliases(appId, documentId) {
2936
+ return this.get(`/app/${appId}/api/documents/${documentId}/aliases`);
2937
+ }
2938
+ async setDocumentAlias(appId, aliasScope, aliasKey, documentId, ownerUserId, mustNotExist) {
2939
+ return this.put(`/app/${appId}/api/document-aliases/${aliasScope}/${encodeURIComponent(aliasKey)}`, {
2940
+ documentId,
2941
+ userId: ownerUserId,
2942
+ mustNotExist,
2943
+ });
2944
+ }
2945
+ /**
2946
+ * Resolve an app user by exact email — the single email → userId lookup in
2947
+ * the CLI (issue #2763). It reads the member-accessible `users/lookup`
2948
+ * endpoint rather than the admin-only `GET /users` list, and returns the
2949
+ * server's `{ exists, user? }` envelope as-is: a 403 or a transport failure
2950
+ * rejects instead of being flattened into "no such user", which is exactly
2951
+ * how the deleted admin-list helper misreported permission problems.
2952
+ */
2953
+ async lookupUserByEmail(appId, email) {
2954
+ return this.get(`/app/${appId}/api/users/lookup`, { email });
2955
+ }
2956
+ /**
2957
+ * The admin inventory of one user's documents, followed to the end (#3399).
2958
+ *
2959
+ * The endpoint speaks the standard list contract (`{ items, hasMore,
2960
+ * nextCursor }`) and caps a page, so one request reads one page: reading it
2961
+ * would truncate a heavy user's inventory at the page size, which is the
2962
+ * bug this issue is about with a smaller number on it. `documents list
2963
+ * --user-id` and `documents export-all` both read this, and both mean "all
2964
+ * of them". `paginateAll` carries the repeat-cursor and max-page guards, so
2965
+ * a server handing out a non-advancing cursor fails loudly instead of
2966
+ * looping forever.
2967
+ */
2968
+ async listAdminDocuments(appId, userId) {
2969
+ return paginateAll(async (cursor) => {
2970
+ const page = await this.listAdminDocumentsPage(appId, userId, {
2971
+ limit: ADMIN_INVENTORY_PAGE_SIZE,
2972
+ cursor,
2973
+ });
2974
+ return { items: page.items, nextCursor: page.nextCursor };
2975
+ });
2976
+ }
2977
+ /**
2978
+ * One page of the admin inventory of a user's documents (#3646).
2979
+ *
2980
+ * `documents list --user-id` prints exactly this — the page the caller's
2981
+ * `--limit`/`--cursor` asked for, with the server's own page boundary
2982
+ * beside it. `documents export-all`, which really does mean every document,
2983
+ * keeps the walking `listAdminDocuments()` above.
2984
+ */
2985
+ async listAdminDocumentsPage(appId, userId, options = {}) {
2986
+ const params = new URLSearchParams({ userId });
2987
+ if (options.limit !== undefined)
2988
+ params.set("limit", String(options.limit));
2989
+ if (options.cursor)
2990
+ params.set("cursor", options.cursor);
2991
+ const result = await this.get(`/admin/api/apps/${appId}/documents?${params.toString()}`);
2992
+ return {
2993
+ items: result?.items ?? [],
2994
+ hasMore: result?.hasMore,
2995
+ nextCursor: result?.nextCursor ?? null,
2996
+ };
2997
+ }
2998
+ /**
2999
+ * The document `AppUser.rootDocId` points at, or null when the user has none
3000
+ * yet (#3135). A user who is not a member of the app is a 404, which
3001
+ * `documents import` reads as "this export has no target here" — distinct
3002
+ * from "this user has no root document yet".
3003
+ */
3004
+ async getUserRootDocument(appId, userId) {
3005
+ return this.get(`/admin/api/apps/${appId}/users/${userId}/root-document`);
3006
+ }
3007
+ /**
3008
+ * Get or create the user's root document (#3135).
3009
+ *
3010
+ * The server runs the same idempotent get-or-create sign-in uses, so this
3011
+ * never mints a second root. `created` is true only when this call's claim
3012
+ * won — an import must not report "created", or merge without `--overwrite`,
3013
+ * for a root a concurrent sign-in minted first.
3014
+ */
3015
+ async ensureUserRootDocument(appId, userId) {
3016
+ return this.post(`/admin/api/apps/${appId}/users/${userId}/root-document`, {});
3017
+ }
3018
+ // ============================================
3019
+ // DATABASE EXPORT / IMPORT
3020
+ // ============================================
3021
+ // `saveDatabaseRecord` lives with the other record verbs under
3022
+ // "DATABASE RECORDS & SCHEMA" above.
3023
+ /**
3024
+ * Apply an ordered batch of record operations via `records/batch`.
3025
+ *
3026
+ * `atomic` (default off, matching the DatabaseDO) makes the whole batch
3027
+ * all-or-nothing: the DO rolls every write back at the first failed
3028
+ * operation and answers with that operation's status. `databases records
3029
+ * bulk` sends `atomic: true` so it matches the documents twin's
3030
+ * all-or-nothing contract (#2437); the CSV/import paths keep the default
3031
+ * partial-success behavior.
3032
+ */
3033
+ async batchDatabaseRecords(appId, databaseId, operations, options) {
3034
+ const body = { operations };
3035
+ if (options?.atomic)
3036
+ body.atomic = true;
3037
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/batch`, body);
3038
+ }
3039
+ async deleteDatabaseRecord(appId, databaseId, modelName, id) {
3040
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/delete`, { modelName, id });
3041
+ }
3042
+ async batchDeleteDatabaseRecords(appId, databaseId, operations) {
3043
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/batch`, { operations });
3044
+ }
3045
+ async listDatabaseUniqueConstraints(appId, databaseId) {
3046
+ const result = await this.get(`/app/${appId}/api/databases/${databaseId}/records/unique-constraints`);
3047
+ return result?.constraints || result || [];
3048
+ }
3049
+ async registerDatabaseUniqueConstraint(appId, databaseId, constraint) {
3050
+ return this.post(`/app/${appId}/api/databases/${databaseId}/records/unique-constraint/register`, constraint);
3051
+ }
3052
+ // ============================================
3053
+ // BLOB BUCKETS
3054
+ // ============================================
3055
+ async listBlobBuckets(appId) {
3056
+ return this.get(`/app/${appId}/api/blob-buckets`);
3057
+ }
3058
+ async createBlobBucket(appId, payload) {
3059
+ return this.post(`/app/${appId}/api/blob-buckets`, payload);
3060
+ }
3061
+ async getBlobBucket(appId, bucketIdOrKey) {
3062
+ return this.get(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}`);
3063
+ }
3064
+ async updateBlobBucket(appId, bucketIdOrKey, payload) {
3065
+ return this.patch(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}`, payload);
3066
+ }
3067
+ async deleteBlobBucket(appId, bucketIdOrKey) {
3068
+ return this.delete(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}`);
3069
+ }
3070
+ async listBucketBlobs(appId, bucketIdOrKey, params) {
3071
+ const result = await this.get(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs`, params);
3072
+ const nextCursor = result?.nextCursor;
3073
+ return {
3074
+ items: result?.items ?? [],
3075
+ nextCursor,
3076
+ hasMore: result?.hasMore ?? nextCursor != null,
3077
+ };
3078
+ }
3079
+ async uploadBucketBlob(appId, bucketIdOrKey, data, meta) {
3080
+ const credentials = await this.ensureAuthenticated();
3081
+ const url = `${credentials.serverUrl}/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs`;
3082
+ const headers = {
3083
+ Authorization: `Bearer ${credentials.accessToken}`,
3084
+ "Content-Type": meta.contentType,
3085
+ "X-Blob-Filename": encodeURIComponent(meta.filename),
3086
+ };
3087
+ if (meta.tags && meta.tags.length > 0) {
3088
+ headers["X-Blob-Tags"] = JSON.stringify(meta.tags);
3089
+ }
3090
+ if (credentials.globalAdminAppId) {
3091
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
3092
+ }
3093
+ const response = await fetchWithTLS(url, {
3094
+ method: "POST",
3095
+ headers,
3096
+ body: data,
3097
+ });
3098
+ if (!response.ok) {
3099
+ throw await blobFailure(response, "Failed to upload blob: ");
3100
+ }
3101
+ return response.json();
3102
+ }
3103
+ async downloadBucketBlob(appId, bucketIdOrKey, blobId) {
3104
+ const credentials = await this.ensureAuthenticated();
3105
+ const url = `${credentials.serverUrl}/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/${blobId}`;
3106
+ const headers = {
3107
+ Authorization: `Bearer ${credentials.accessToken}`,
3108
+ };
3109
+ if (credentials.globalAdminAppId) {
3110
+ headers["X-Global-Admin-App-Id"] = credentials.globalAdminAppId;
3111
+ }
3112
+ const response = await fetchWithTLS(url, { headers });
3113
+ if (!response.ok) {
3114
+ throw await blobFailure(response, "Failed to download blob: ");
3115
+ }
3116
+ const arrayBuffer = await response.arrayBuffer();
3117
+ return Buffer.from(arrayBuffer);
3118
+ }
3119
+ async deleteBucketBlob(appId, bucketIdOrKey, blobId) {
3120
+ return this.delete(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/${blobId}`);
3121
+ }
3122
+ // Batch delete (#1455): one round-trip for N ids via POST .../blobs/delete.
3123
+ async deleteBucketBlobs(appId, bucketIdOrKey, blobIds) {
3124
+ return this.post(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/delete`, { blobIds });
3125
+ }
3126
+ async getBucketBlobSignedUrl(appId, bucketIdOrKey, blobId, expiresInSeconds) {
3127
+ return this.post(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/${blobId}/signed-url`, {
3128
+ expiresInSeconds: expiresInSeconds || 300,
3129
+ });
3130
+ }
3131
+ // Blob metadata (#1966): head a single blob without downloading its bytes.
3132
+ // Mirrors listBucketBlobs/downloadBucketBlob addressing; the server heads the
3133
+ // R2 object and returns the serialized BlobInfo shape.
3134
+ async getBucketBlobMetadata(appId, bucketIdOrKey, blobId) {
3135
+ return this.get(`/app/${appId}/api/blob-buckets/${encodeURIComponent(bucketIdOrKey)}/blobs/${blobId}/metadata`);
3136
+ }
841
3137
  }
842
- // Export a singleton instance
843
- export const apiClient = new ApiClient();
844
3138
  //# sourceMappingURL=api-client.js.map