@lucern/sdk 1.0.11 → 1.0.12

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 (330) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/dist/.generated +2 -0
  3. package/dist/accessControl.d.ts +19 -26
  4. package/dist/accessControl.js +195 -1423
  5. package/dist/adminClient.d.ts +52 -59
  6. package/dist/adminClient.js +364 -1142
  7. package/dist/answersClient.d.ts +5 -14
  8. package/dist/answersClient.js +19 -737
  9. package/dist/audience/index.d.ts +18 -18
  10. package/dist/audience/index.js +87 -90
  11. package/dist/audiencesClient.d.ts +19 -27
  12. package/dist/audiencesClient.js +107 -868
  13. package/dist/auditClient.d.ts +8 -15
  14. package/dist/auditClient.js +18 -791
  15. package/dist/authContext.d.ts +11 -16
  16. package/dist/authContext.js +122 -154
  17. package/dist/authDeviceClient.d.ts +8 -17
  18. package/dist/authDeviceClient.js +113 -102
  19. package/dist/beliefs/index.d.ts +15 -67
  20. package/dist/beliefs/index.js +17 -10181
  21. package/dist/beliefs/lifecycle.d.ts +10 -11
  22. package/dist/beliefs/lifecycle.js +78 -80
  23. package/dist/beliefsClient.d.ts +26 -32
  24. package/dist/beliefsClient.js +250 -990
  25. package/dist/boundaryClientSurface.d.ts +11 -16
  26. package/dist/boundaryClientSurface.js +49 -68
  27. package/dist/client.d.ts +64 -112
  28. package/dist/client.js +232 -10155
  29. package/dist/clientAssemblyTypes.d.ts +3 -3
  30. package/dist/clientAssemblyTypes.js +1 -2
  31. package/dist/clientConfig.d.ts +45 -59
  32. package/dist/clientConfig.js +1 -2
  33. package/dist/clientEvidenceCompat.d.ts +7 -14
  34. package/dist/clientEvidenceCompat.js +50 -64
  35. package/dist/clientGraphNamespaces.d.ts +3 -5
  36. package/dist/clientGraphNamespaces.js +170 -245
  37. package/dist/clientHelpers.d.ts +20 -25
  38. package/dist/clientHelpers.js +104 -127
  39. package/dist/clientKnowledgeNamespaces.d.ts +6 -53
  40. package/dist/clientKnowledgeNamespaces.js +502 -506
  41. package/dist/clientLocalHelpers.d.ts +11 -56
  42. package/dist/clientLocalHelpers.js +503 -732
  43. package/dist/clientPlatformNamespaces.d.ts +5 -53
  44. package/dist/clientPlatformNamespaces.js +229 -323
  45. package/dist/clientRuntime.d.ts +5 -53
  46. package/dist/clientRuntime.js +26 -30
  47. package/dist/clientWorkflowNamespaces.d.ts +6 -15
  48. package/dist/clientWorkflowNamespaces.js +529 -596
  49. package/dist/contextClient.d.ts +9 -17
  50. package/dist/contextClient.js +92 -805
  51. package/dist/contextFacade.d.ts +11 -2
  52. package/dist/contextFacade.js +10 -81
  53. package/dist/contextPackCompiler.d.ts +10 -11
  54. package/dist/contextPackCompiler.js +494 -1040
  55. package/dist/contextPackPolicy.d.ts +14 -15
  56. package/dist/contextPackPolicy.js +227 -305
  57. package/dist/contextPackSchema.d.ts +3 -3
  58. package/dist/contextPackSchema.js +169 -176
  59. package/dist/contextTypes.d.ts +14 -15
  60. package/dist/contextTypes.js +1 -2
  61. package/dist/contracts/api-enums.contract.d.ts +29 -30
  62. package/dist/contracts/api-enums.contract.js +162 -88
  63. package/dist/contracts/auth-session.contract.d.ts +13 -14
  64. package/dist/contracts/auth-session.contract.js +55 -52
  65. package/dist/contracts/context-pack.contract.d.ts +54 -55
  66. package/dist/contracts/context-pack.contract.js +160 -88
  67. package/dist/contracts/contextPack.d.ts +2 -1
  68. package/dist/contracts/contextPack.js +1 -97
  69. package/dist/contracts/index.d.ts +11 -12
  70. package/dist/contracts/index.js +10 -854
  71. package/dist/contracts/lens-filter.contract.d.ts +9 -10
  72. package/dist/contracts/lens-filter.contract.js +82 -58
  73. package/dist/contracts/lens-workflow.contract.d.ts +21 -23
  74. package/dist/contracts/lens-workflow.contract.js +48 -117
  75. package/dist/contracts/lensFilter.d.ts +2 -1
  76. package/dist/contracts/lensFilter.js +1 -71
  77. package/dist/contracts/lensWorkflow.d.ts +2 -2
  78. package/dist/contracts/lensWorkflow.js +1 -123
  79. package/dist/contracts/mcpTools.d.ts +16 -18
  80. package/dist/contracts/mcpTools.js +89 -123
  81. package/dist/contracts/prompt.contract.d.ts +4 -5
  82. package/dist/contracts/prompt.contract.js +23 -10
  83. package/dist/contracts/prompt.d.ts +2 -1
  84. package/dist/contracts/prompt.js +1 -11
  85. package/dist/contracts/sdk-tools.contract.d.ts +2 -1
  86. package/dist/contracts/sdk-tools.contract.js +1 -2
  87. package/dist/contracts/sdkTools.d.ts +2 -1
  88. package/dist/contracts/sdkTools.js +1 -26
  89. package/dist/contracts/tool-contracts.d.ts +2 -1
  90. package/dist/contracts/tool-contracts.js +1 -2
  91. package/dist/contracts/workflow-runtime.contract.d.ts +45 -46
  92. package/dist/contracts/workflow-runtime.contract.js +241 -228
  93. package/dist/contracts/workflowRuntime.d.ts +2 -1
  94. package/dist/contracts/workflowRuntime.js +1 -244
  95. package/dist/contradictions/index.d.ts +8 -60
  96. package/dist/contradictions/index.js +11 -10175
  97. package/dist/control-plane.d.ts +17 -24
  98. package/dist/control-plane.js +124 -840
  99. package/dist/controlObjectOwnership.d.ts +19 -20
  100. package/dist/controlObjectOwnership.js +207 -201
  101. package/dist/coreClient.d.ts +23 -28
  102. package/dist/coreClient.js +567 -692
  103. package/dist/customTools.d.ts +17 -21
  104. package/dist/customTools.js +221 -221
  105. package/dist/decisions/index.d.ts +7 -58
  106. package/dist/decisions/index.js +14 -10177
  107. package/dist/decisionsClient.d.ts +25 -32
  108. package/dist/decisionsClient.js +113 -913
  109. package/dist/domainContext.d.ts +2 -1
  110. package/dist/domainContext.js +1 -2
  111. package/dist/edges/index.d.ts +21 -73
  112. package/dist/edges/index.js +12 -10176
  113. package/dist/embeddingsClient.d.ts +22 -30
  114. package/dist/embeddingsClient.js +73 -922
  115. package/dist/eventingClient.d.ts +23 -31
  116. package/dist/eventingClient.js +89 -918
  117. package/dist/events.d.ts +48 -49
  118. package/dist/events.js +257 -241
  119. package/dist/eventsCore.d.ts +20 -29
  120. package/dist/eventsCore.js +86 -830
  121. package/dist/evidence/index.d.ts +9 -60
  122. package/dist/evidence/index.js +13 -10176
  123. package/dist/evidenceClient.d.ts +13 -22
  124. package/dist/evidenceClient.js +34 -751
  125. package/dist/facade/context.d.ts +7 -8
  126. package/dist/facade/context.js +73 -72
  127. package/dist/functionSurface.d.ts +2 -156
  128. package/dist/functionSurface.js +1 -1460
  129. package/dist/functionSurfaceClient.d.ts +2 -9
  130. package/dist/functionSurfaceClient.js +1 -1460
  131. package/dist/gatewayFacades.d.ts +79 -296
  132. package/dist/gatewayFacades.factories.d.ts +209 -14
  133. package/dist/gatewayFacades.factories.js +561 -2227
  134. package/dist/gatewayFacades.js +284 -2627
  135. package/dist/generated/functionSurface.d.ts +149 -0
  136. package/dist/generated/functionSurface.js +749 -0
  137. package/dist/graphAnalysisClient.d.ts +41 -49
  138. package/dist/graphAnalysisClient.js +185 -974
  139. package/dist/graphClient.d.ts +53 -60
  140. package/dist/graphClient.js +219 -1090
  141. package/dist/graphIntel.d.ts +2 -4
  142. package/dist/graphIntel.js +1 -2
  143. package/dist/graphIntelligence.d.ts +4 -2
  144. package/dist/graphIntelligence.js +2 -46
  145. package/dist/graphRecommendationsClient.d.ts +15 -23
  146. package/dist/graphRecommendationsClient.js +70 -849
  147. package/dist/graphStateClassifierClient.d.ts +17 -25
  148. package/dist/graphStateClassifierClient.js +67 -908
  149. package/dist/harnessClient.d.ts +40 -47
  150. package/dist/harnessClient.js +198 -993
  151. package/dist/identityClient.d.ts +25 -33
  152. package/dist/identityClient.js +245 -1186
  153. package/dist/index.d.ts +73 -69
  154. package/dist/index.js +72 -13313
  155. package/dist/infisicalRuntime.d.ts +12 -14
  156. package/dist/infisicalRuntime.js +290 -297
  157. package/dist/jobsClient.d.ts +24 -32
  158. package/dist/jobsClient.js +101 -916
  159. package/dist/learningClient.d.ts +8 -16
  160. package/dist/learningClient.js +45 -809
  161. package/dist/lenses/index.d.ts +13 -65
  162. package/dist/lenses/index.js +11 -10175
  163. package/dist/mcpClient.d.ts +14 -23
  164. package/dist/mcpClient.js +115 -856
  165. package/dist/modelRuntimeClient.d.ts +18 -26
  166. package/dist/modelRuntimeClient.js +74 -894
  167. package/dist/nodes/index.d.ts +7 -58
  168. package/dist/nodes/index.js +14 -10177
  169. package/dist/ontologies/index.d.ts +21 -73
  170. package/dist/ontologies/index.js +14 -10178
  171. package/dist/ontologyClient.d.ts +23 -31
  172. package/dist/ontologyClient.js +138 -924
  173. package/dist/ontologyLinksClient.d.ts +16 -24
  174. package/dist/ontologyLinksClient.js +76 -886
  175. package/dist/opinion.d.ts +5 -6
  176. package/dist/opinion.js +21 -25
  177. package/dist/orgGraphSearchClient.d.ts +19 -27
  178. package/dist/orgGraphSearchClient.js +89 -857
  179. package/dist/packRuntime.d.ts +2 -2
  180. package/dist/packRuntime.js +1 -2
  181. package/dist/packsClient.d.ts +30 -37
  182. package/dist/packsClient.js +131 -906
  183. package/dist/policyClient.d.ts +21 -29
  184. package/dist/policyClient.js +267 -1026
  185. package/dist/proof-attestation.json +1 -1
  186. package/dist/questions/index.d.ts +9 -60
  187. package/dist/questions/index.js +15 -10178
  188. package/dist/realtime/index.d.ts +20 -16
  189. package/dist/realtime/index.js +30 -19
  190. package/dist/realtime/refs.d.ts +4 -6
  191. package/dist/realtime/refs.js +12 -7
  192. package/dist/realtime-refs.d.ts +1 -0
  193. package/dist/realtime-refs.js +1 -0
  194. package/dist/realtime.d.ts +1 -0
  195. package/dist/realtime.js +1 -0
  196. package/dist/reportsClient.d.ts +10 -19
  197. package/dist/reportsClient.js +48 -836
  198. package/dist/schemaClient.d.ts +16 -23
  199. package/dist/schemaClient.js +62 -832
  200. package/dist/sdkSurface.d.ts +18 -25
  201. package/dist/sdkSurface.js +135 -106
  202. package/dist/secrets.d.ts +2 -1
  203. package/dist/secrets.js +1 -2
  204. package/dist/sourcesClient.d.ts +11 -18
  205. package/dist/sourcesClient.js +18 -741
  206. package/dist/telemetryClient.d.ts +22 -30
  207. package/dist/telemetryClient.js +107 -931
  208. package/dist/toolRegistryClient.d.ts +27 -35
  209. package/dist/toolRegistryClient.js +116 -954
  210. package/dist/topics/index.d.ts +13 -64
  211. package/dist/topics/index.js +15 -10178
  212. package/dist/topicsClient.d.ts +19 -27
  213. package/dist/topicsClient.js +106 -894
  214. package/dist/types.d.ts +84 -87
  215. package/dist/types.js +1 -2
  216. package/dist/version.d.ts +2 -3
  217. package/dist/version.js +2 -5
  218. package/dist/workflowClient.d.ts +60 -65
  219. package/dist/workflowClient.js +343 -1219
  220. package/dist/worktrees/index.d.ts +16 -68
  221. package/dist/worktrees/index.js +14 -10178
  222. package/package.json +6 -6
  223. package/dist/accessControl.js.map +0 -1
  224. package/dist/adminClient.js.map +0 -1
  225. package/dist/answersClient.js.map +0 -1
  226. package/dist/audience/index.js.map +0 -1
  227. package/dist/audiencesClient.js.map +0 -1
  228. package/dist/auditClient.js.map +0 -1
  229. package/dist/authContext.js.map +0 -1
  230. package/dist/authDeviceClient.js.map +0 -1
  231. package/dist/beliefs/index.js.map +0 -1
  232. package/dist/beliefs/lifecycle.js.map +0 -1
  233. package/dist/beliefsClient.js.map +0 -1
  234. package/dist/boundaryClientSurface.js.map +0 -1
  235. package/dist/client.js.map +0 -1
  236. package/dist/clientAssemblyTypes.js.map +0 -1
  237. package/dist/clientConfig.js.map +0 -1
  238. package/dist/clientEvidenceCompat.js.map +0 -1
  239. package/dist/clientGraphNamespaces.js.map +0 -1
  240. package/dist/clientHelpers.js.map +0 -1
  241. package/dist/clientKnowledgeNamespaces.js.map +0 -1
  242. package/dist/clientLocalHelpers.js.map +0 -1
  243. package/dist/clientPlatformNamespaces.js.map +0 -1
  244. package/dist/clientRuntime.js.map +0 -1
  245. package/dist/clientWorkflowNamespaces.js.map +0 -1
  246. package/dist/contextClient.js.map +0 -1
  247. package/dist/contextFacade.js.map +0 -1
  248. package/dist/contextPackCompiler.js.map +0 -1
  249. package/dist/contextPackPolicy.js.map +0 -1
  250. package/dist/contextPackSchema.js.map +0 -1
  251. package/dist/contextTypes.js.map +0 -1
  252. package/dist/contracts/api-enums.contract.js.map +0 -1
  253. package/dist/contracts/auth-session.contract.js.map +0 -1
  254. package/dist/contracts/context-pack.contract.js.map +0 -1
  255. package/dist/contracts/contextPack.js.map +0 -1
  256. package/dist/contracts/index.js.map +0 -1
  257. package/dist/contracts/lens-filter.contract.js.map +0 -1
  258. package/dist/contracts/lens-workflow.contract.js.map +0 -1
  259. package/dist/contracts/lensFilter.js.map +0 -1
  260. package/dist/contracts/lensWorkflow.js.map +0 -1
  261. package/dist/contracts/mcpTools.js.map +0 -1
  262. package/dist/contracts/prompt.contract.js.map +0 -1
  263. package/dist/contracts/prompt.js.map +0 -1
  264. package/dist/contracts/sdk-tools.contract.js.map +0 -1
  265. package/dist/contracts/sdkTools.js.map +0 -1
  266. package/dist/contracts/tool-contracts.js.map +0 -1
  267. package/dist/contracts/workflow-runtime.contract.js.map +0 -1
  268. package/dist/contracts/workflowRuntime.js.map +0 -1
  269. package/dist/contradictions/index.js.map +0 -1
  270. package/dist/control-plane.js.map +0 -1
  271. package/dist/controlObjectOwnership.js.map +0 -1
  272. package/dist/coreClient.js.map +0 -1
  273. package/dist/customTools.js.map +0 -1
  274. package/dist/decisions/index.js.map +0 -1
  275. package/dist/decisionsClient.js.map +0 -1
  276. package/dist/domainContext.js.map +0 -1
  277. package/dist/edges/index.js.map +0 -1
  278. package/dist/embeddingsClient.js.map +0 -1
  279. package/dist/eventingClient.js.map +0 -1
  280. package/dist/events.js.map +0 -1
  281. package/dist/eventsCore.js.map +0 -1
  282. package/dist/evidence/index.js.map +0 -1
  283. package/dist/evidenceClient.js.map +0 -1
  284. package/dist/facade/context.js.map +0 -1
  285. package/dist/functionSurface.js.map +0 -1
  286. package/dist/functionSurfaceClient.js.map +0 -1
  287. package/dist/gatewayFacades.factories.js.map +0 -1
  288. package/dist/gatewayFacades.js.map +0 -1
  289. package/dist/graphAnalysisClient.js.map +0 -1
  290. package/dist/graphClient.js.map +0 -1
  291. package/dist/graphIntel.js.map +0 -1
  292. package/dist/graphIntelligence.js.map +0 -1
  293. package/dist/graphRecommendationsClient.js.map +0 -1
  294. package/dist/graphStateClassifierClient.js.map +0 -1
  295. package/dist/harnessClient.js.map +0 -1
  296. package/dist/identityClient.js.map +0 -1
  297. package/dist/index.js.map +0 -1
  298. package/dist/infisicalRuntime.js.map +0 -1
  299. package/dist/jobsClient.js.map +0 -1
  300. package/dist/learningClient.js.map +0 -1
  301. package/dist/lenses/index.js.map +0 -1
  302. package/dist/mcpClient.js.map +0 -1
  303. package/dist/modelRuntimeClient.js.map +0 -1
  304. package/dist/nodes/index.js.map +0 -1
  305. package/dist/ontologies/index.js.map +0 -1
  306. package/dist/ontologyClient.js.map +0 -1
  307. package/dist/ontologyLinksClient.js.map +0 -1
  308. package/dist/opinion.js.map +0 -1
  309. package/dist/orgGraphSearchClient.js.map +0 -1
  310. package/dist/packRuntime.js.map +0 -1
  311. package/dist/packsClient.js.map +0 -1
  312. package/dist/policyClient.js.map +0 -1
  313. package/dist/questions/index.js.map +0 -1
  314. package/dist/realtime/index.js.map +0 -1
  315. package/dist/realtime/refs.js.map +0 -1
  316. package/dist/reportsClient.js.map +0 -1
  317. package/dist/schemaClient.js.map +0 -1
  318. package/dist/sdk-tools.contract-B4c1Zr1o.d.ts +0 -22
  319. package/dist/sdkSurface.js.map +0 -1
  320. package/dist/secrets.js.map +0 -1
  321. package/dist/sourcesClient.js.map +0 -1
  322. package/dist/telemetryClient.js.map +0 -1
  323. package/dist/tool-contracts-BUiL9P6z.d.ts +0 -22
  324. package/dist/toolRegistryClient.js.map +0 -1
  325. package/dist/topics/index.js.map +0 -1
  326. package/dist/topicsClient.js.map +0 -1
  327. package/dist/types.js.map +0 -1
  328. package/dist/version.js.map +0 -1
  329. package/dist/workflowClient.js.map +0 -1
  330. package/dist/worktrees/index.js.map +0 -1
@@ -1,1225 +1,349 @@
1
- import { createTelemetryExporterFromEnv, emitTelemetrySignal } from '@lucern/transport-core';
2
- import { redactDiagnosticValue } from '@lucern/transport-core/redaction';
3
- import { classifyRetry } from '@lucern/transport-core/transport';
4
- import { Effect, Exit, Cause } from 'effect';
5
-
6
- // src/coreClient.ts
7
-
8
- // src/authContext.ts
9
- var LucernSdkAuthContextError = class extends Error {
10
- reason;
11
- constructor(reason, message) {
12
- super(message);
13
- this.name = "LucernSdkAuthContextError";
14
- this.reason = reason;
15
- }
16
- };
17
- function cleanString(value) {
18
- const normalized = value?.trim();
19
- return normalized ? normalized : void 0;
20
- }
21
- function cleanStringList(values) {
22
- if (!values) {
23
- return [];
24
- }
25
- return values.map((value) => value.trim()).filter(
26
- (value, index, list) => value.length > 0 && list.indexOf(value) === index
27
- );
28
- }
29
- function requireString(value, reason, label) {
30
- const normalized = cleanString(value);
31
- if (!normalized) {
32
- throw new LucernSdkAuthContextError(
33
- reason,
34
- `Canonical Lucern SDK auth context is missing ${label}.`
35
- );
36
- }
37
- return normalized;
38
- }
39
- function requirePrincipalType(principalType) {
40
- if (!principalType) {
41
- throw new LucernSdkAuthContextError(
42
- "principal_missing",
43
- "Canonical Lucern SDK auth context is missing principalType."
44
- );
45
- }
46
- return principalType;
47
- }
48
- function requireAuthMode(authMode) {
49
- if (!authMode) {
50
- throw new LucernSdkAuthContextError(
51
- "principal_missing",
52
- "Canonical Lucern SDK auth context is missing authMode."
53
- );
54
- }
55
- return authMode;
56
- }
57
- function ensurePermitMatch(args) {
58
- const actual = cleanString(args.actual);
59
- if (actual && actual !== args.expected) {
60
- throw new LucernSdkAuthContextError(
61
- "policy_denied",
62
- `Canonical Lucern SDK auth context has conflicting Permit ${args.field}.`
63
- );
64
- }
65
- }
66
- function normalizeCanonicalLucernAuthContext(input) {
67
- if (!input) {
68
- throw new LucernSdkAuthContextError(
69
- "principal_missing",
70
- "Canonical Lucern SDK auth context is required."
71
- );
72
- }
73
- if (input.policyDecision === "deny") {
74
- throw new LucernSdkAuthContextError(
75
- "policy_denied",
76
- "Canonical Lucern SDK auth context carries a denied policy decision."
77
- );
78
- }
79
- const principalId = requireString(
80
- input.principalId,
81
- "principal_missing",
82
- "principalId"
83
- );
84
- const tenantId = requireString(input.tenantId, "tenant_missing", "tenantId");
85
- const workspaceId = requireString(
86
- input.workspaceId,
87
- "workspace_missing",
88
- "workspaceId"
89
- );
90
- const roles = cleanStringList(input.roles);
91
- const scopes = cleanStringList(input.scopes);
92
- const principalType = requirePrincipalType(input.principalType);
93
- const authMode = requireAuthMode(input.authMode);
94
- const roleBasedInteractiveAuth = authMode === "interactive_user" && roles.length > 0;
95
- if (roles.length === 0 || scopes.length === 0 && !roleBasedInteractiveAuth) {
96
- throw new LucernSdkAuthContextError(
97
- "membership_missing",
98
- "Canonical Lucern SDK auth context requires non-empty roles and scopes."
99
- );
100
- }
101
- const subject = cleanString(input.permit?.subject) ?? principalId;
102
- const tenant = cleanString(input.permit?.tenant) ?? tenantId;
103
- const workspace = cleanString(input.permit?.workspace) ?? workspaceId;
104
- ensurePermitMatch({
105
- field: "subject",
106
- expected: principalId,
107
- actual: subject
108
- });
109
- ensurePermitMatch({ field: "tenant", expected: tenantId, actual: tenant });
110
- ensurePermitMatch({
111
- field: "workspace",
112
- expected: workspaceId,
113
- actual: workspace
114
- });
115
- const context = input.permit?.context ? { ...input.permit.context } : void 0;
116
- return {
117
- clerkId: cleanString(input.clerkId),
118
- principalId,
119
- tenantId,
120
- workspaceId,
121
- principalType,
122
- authMode,
123
- roles,
124
- scopes,
125
- delegationChain: input.delegationChain ? [...input.delegationChain] : [],
126
- policyTraceId: cleanString(input.policyTraceId),
127
- correlationId: cleanString(input.correlationId),
128
- membershipId: cleanString(input.membershipId),
129
- permit: {
130
- subject,
131
- tenant,
132
- workspace,
133
- resource: cleanString(input.permit?.resource),
134
- action: cleanString(input.permit?.action),
135
- relation: cleanString(input.permit?.relation),
136
- context
137
- }
138
- };
139
- }
140
- function createCanonicalAuthHeaders(authContext) {
141
- const headers = {
142
- "x-lucern-principal-id": authContext.principalId,
143
- "x-lucern-principal-type": authContext.principalType,
144
- "x-lucern-tenant": authContext.tenantId,
145
- "x-lucern-tenant-id": authContext.tenantId,
146
- "x-lucern-workspace": authContext.workspaceId,
147
- "x-lucern-workspace-id": authContext.workspaceId,
148
- "x-lucern-auth-mode": authContext.authMode,
149
- "x-lucern-roles": authContext.roles.join(","),
150
- "x-lucern-scopes": authContext.scopes.join(","),
151
- "x-lucern-permit-context": JSON.stringify(authContext.permit)
152
- };
153
- if (authContext.clerkId) {
154
- headers["x-lucern-clerk-id"] = authContext.clerkId;
155
- headers["x-lucern-user-id"] = authContext.clerkId;
156
- }
157
- if (authContext.delegationChain.length > 0) {
158
- headers["x-lucern-delegation-chain"] = JSON.stringify(
159
- authContext.delegationChain
160
- );
161
- }
162
- if (authContext.policyTraceId) {
163
- headers["x-lucern-policy-trace-id"] = authContext.policyTraceId;
164
- }
165
- if (authContext.correlationId) {
166
- headers["x-correlation-id"] = authContext.correlationId;
167
- headers["x-lucern-correlation-id"] = authContext.correlationId;
168
- }
169
- if (authContext.membershipId) {
170
- headers["x-lucern-membership-id"] = authContext.membershipId;
171
- }
172
- return headers;
173
- }
174
-
175
- // src/coreClient.ts
176
- var DEFAULT_GATEWAY_TIMEOUT_MS = 15e3;
177
- var DEFAULT_GATEWAY_MAX_RETRIES = 2;
178
- var DEFAULT_ENV_TIMEOUT_MS = "LUCERN_REQUEST_TIMEOUT_MS";
179
- var DEFAULT_ENV_MAX_RETRIES = "LUCERN_GATEWAY_MAX_RETRIES";
180
- var ENV_TIMEOUT_BY_METHOD_PREFIX = "LUCERN_REQUEST_TIMEOUT_MS_";
181
- var GatewayTimeoutError = class extends Error {
182
- retryable = true;
183
- timeoutMs;
184
- constructor(timeoutMs) {
185
- super(`Request timed out after ${timeoutMs}ms`);
186
- this.name = "AbortError";
187
- this.timeoutMs = timeoutMs;
188
- }
189
- };
190
- var GatewayTransportError = class extends Error {
191
- retryable;
192
- cause;
193
- constructor(message, options) {
194
- super(message);
195
- this.name = "GatewayTransportError";
196
- this.retryable = options?.retryable ?? true;
197
- this.cause = options?.cause;
198
- }
199
- };
200
- function isGatewayRetryableError(error) {
201
- return error instanceof GatewayTimeoutError && error.retryable || error instanceof GatewayTransportError && error.retryable || false;
202
- }
203
- var LucernApiError = class extends Error {
204
- code;
205
- status;
206
- invariant;
207
- suggestion;
208
- details;
209
- requestId;
210
- correlationId;
211
- policyTraceId;
212
- constructor(args) {
213
- super(args.message);
214
- this.name = "LucernApiError";
215
- this.code = args.code;
216
- this.status = args.status;
217
- this.invariant = args.invariant;
218
- this.suggestion = args.suggestion;
219
- this.details = args.details;
220
- this.requestId = args.requestId;
221
- this.correlationId = args.correlationId;
222
- this.policyTraceId = args.policyTraceId;
223
- }
224
- };
225
- function toQueryString(scope) {
226
- const params = new URLSearchParams();
227
- if (scope.tenantId) {
228
- params.set("tenantId", scope.tenantId);
229
- }
230
- if (scope.workspaceId) {
231
- params.set("workspaceId", scope.workspaceId);
232
- }
233
- for (const [key, value] of Object.entries(scope)) {
234
- if (key === "tenantId" || key === "workspaceId") {
235
- continue;
236
- }
237
- if (value === void 0) {
238
- continue;
239
- }
240
- params.set(key, String(value));
241
- }
242
- const serialized = params.toString();
243
- return serialized.length > 0 ? `?${serialized}` : "";
244
- }
245
- function fillRandomBytes(length) {
246
- const bytes = new Uint8Array(length);
247
- if (typeof globalThis.crypto?.getRandomValues === "function") {
248
- globalThis.crypto.getRandomValues(bytes);
249
- return bytes;
250
- }
251
- for (let index = 0; index < length; index += 1) {
252
- bytes[index] = Math.floor(Math.random() * 256);
253
- }
254
- return bytes;
255
- }
256
- function generatePortableRequestId() {
257
- if (typeof globalThis.crypto?.randomUUID === "function") {
258
- return globalThis.crypto.randomUUID();
259
- }
260
- const bytes = fillRandomBytes(16);
261
- bytes[6] = bytes[6] & 15 | 64;
262
- bytes[8] = bytes[8] & 63 | 128;
263
- const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0"));
264
- return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(
265
- 6,
266
- 8
267
- ).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
268
- }
269
- function resolveEnvironment() {
270
- const processEnv = typeof globalThis === "object" && globalThis !== null && "process" in globalThis ? globalThis.process : void 0;
271
- const env = processEnv !== void 0 && typeof processEnv === "object" && processEnv !== null && typeof processEnv.env === "object" ? processEnv.env : void 0;
272
- return {
273
- get: (name) => {
274
- const value = env?.[name];
275
- return typeof value === "string" && value.length > 0 ? value : void 0;
276
- }
277
- };
278
- }
279
- function telemetryEnvironmentRecord(environment) {
280
- const names = [
281
- "LUCERN_TELEMETRY_ENABLED",
282
- "AXIOM_TELEMETRY_ENABLED",
283
- "LUCERN_AXIOM_TOKEN",
284
- "AXIOM_TOKEN",
285
- "LUCERN_AXIOM_EVENTS_DATASET",
286
- "LUCERN_AXIOM_DATASET",
287
- "AXIOM_EVENTS_DATASET",
288
- "AXIOM_DATASET",
289
- "LUCERN_AXIOM_API_URL",
290
- "AXIOM_URL",
291
- "LUCERN_ENVIRONMENT",
292
- "NODE_ENV",
293
- "LUCERN_RELEASE",
294
- "SENTRY_RELEASE",
295
- "VERCEL_GIT_COMMIT_SHA"
296
- ];
297
- return Object.fromEntries(
298
- names.map((name) => [name, environment.get(name)])
299
- );
300
- }
301
- function resolveRequestProfile(config, environment) {
302
- const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
303
- const parsedMaxRetries = parseIntegerFromString(
304
- config.maxRetries,
305
- environment.get(DEFAULT_ENV_MAX_RETRIES)
306
- );
307
- const parsedTimeoutMs = parseIntegerFromString(
308
- config.timeoutMs,
309
- environment.get(DEFAULT_ENV_TIMEOUT_MS)
310
- );
311
- const methodTimeouts = {
312
- ...config.timeoutMsByMethod
313
- };
314
- for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE"]) {
315
- const envKey = `${ENV_TIMEOUT_BY_METHOD_PREFIX}${method}`;
316
- const raw = environment.get(envKey);
317
- if (!raw || methodTimeouts[method] !== void 0) {
318
- continue;
319
- }
320
- const parsed = parseIntegerFromString(void 0, raw);
321
- if (typeof parsed === "number") {
322
- methodTimeouts[method] = parsed;
323
- }
324
- }
325
- return {
326
- maxRetries: parsedMaxRetries ?? DEFAULT_GATEWAY_MAX_RETRIES,
327
- timeoutMs: parsedTimeoutMs ?? DEFAULT_GATEWAY_TIMEOUT_MS,
328
- timeoutMsByMethod: methodTimeouts,
329
- requestIdFactory
330
- };
331
- }
332
- function createGatewayRuntime(config, environment) {
333
- return {
334
- fetch: config.fetchImpl ?? fetch,
335
- now: () => Date.now(),
336
- sleep: (ms) => delay(ms),
337
- env: environment,
338
- redaction: resolveRequestRedactionValue,
339
- profile: resolveRequestProfile(config, environment)
340
- };
341
- }
342
- function parseIntegerFromString(value, rawValue) {
343
- if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
344
- return value;
345
- }
346
- if (typeof rawValue !== "string" || !rawValue.trim()) {
347
- return void 0;
348
- }
349
- const parsed = Number.parseInt(rawValue, 10);
350
- return Number.isInteger(parsed) && parsed >= 0 ? parsed : void 0;
351
- }
352
- function resolveRequestRedactionValue(value) {
353
- return redactDiagnosticValue(value);
354
- }
355
- function resolveGatewayBaseUrl(configBaseUrl, environment) {
356
- const envBaseUrl = environment.get("LUCERN_API_URL") ?? environment.get("LUCERN_BASE_URL") ?? environment.get("LUCERN_GATEWAY_BASE_URL");
357
- return (configBaseUrl ?? envBaseUrl ?? "").replace(/\/+$/, "");
358
- }
359
- function normalizeGatewayEnvironment(value) {
360
- return value === "sandbox" || value === "production" ? value : void 0;
361
- }
362
- var randomIdempotencyKey = generatePortableRequestId;
363
- function fallbackErrorCode(status) {
364
- if (status === 401) {
365
- return "AUTHENTICATION_REQUIRED";
366
- }
367
- if (status === 403) {
368
- return "FORBIDDEN";
369
- }
370
- if (status === 404) {
371
- return "NOT_FOUND";
372
- }
373
- if (status === 408) {
374
- return "UPSTREAM_ERROR";
375
- }
376
- if (status === 409) {
377
- return "CONFLICT";
378
- }
379
- if (status === 429) {
380
- return "RATE_LIMIT_EXCEEDED";
381
- }
382
- if (status >= 500) {
383
- return "UPSTREAM_ERROR";
384
- }
385
- return "INTERNAL_ERROR";
386
- }
387
- function delay(ms) {
388
- return new Promise((resolve) => setTimeout(resolve, ms));
389
- }
390
- function computeRetryDelayMs(args) {
391
- const baseDelay = args.status === 429 ? Math.max(
392
- args.retryAfterMs ?? 0,
393
- Math.min(1e3 * 2 ** args.attempt, 1e4)
394
- ) : Math.min(1e3 * 2 ** args.attempt, 4e3);
395
- if (args.status !== 429) {
396
- return baseDelay;
397
- }
398
- const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));
399
- return baseDelay + Math.round(Math.random() * jitterWindow);
400
- }
401
- function classifyGatewayErrorForRetry(error) {
402
- return isGatewayRetryableError(error) || classifyRetry({ error }).retryable;
403
- }
404
- function isRecord(value) {
405
- return value !== null && typeof value === "object" && !Array.isArray(value);
406
- }
407
- function readPolicySummaryFromDetails(details) {
408
- if (!isRecord(details)) {
409
- return null;
410
- }
411
- const directSummary = details.summary;
412
- if (typeof directSummary === "string" && directSummary.trim().length > 0) {
413
- return directSummary.trim();
414
- }
415
- const policy = details.policy;
416
- if (!isRecord(policy)) {
417
- return null;
418
- }
419
- const explanation = policy.explanation;
420
- if (!isRecord(explanation)) {
421
- return null;
422
- }
423
- const nestedSummary = explanation.summary;
424
- if (typeof nestedSummary === "string" && nestedSummary.trim().length > 0) {
425
- return nestedSummary.trim();
426
- }
427
- return null;
428
- }
429
- function redactJsonDiagnosticValue(value) {
430
- return value === void 0 ? void 0 : redactDiagnosticValue(value);
431
- }
432
- async function resolveConfiguredAuthContext(authContext) {
433
- if (typeof authContext === "function") {
434
- return await authContext();
435
- }
436
- return authContext;
437
- }
438
- function mergeHeaderRecord(base, addition) {
439
- const headers = new Headers(base);
440
- for (const [key, value] of Object.entries(addition)) {
441
- const existing = headers.get(key);
442
- if (existing !== null && existing !== value) {
443
- throw new LucernSdkAuthContextError(
444
- "policy_denied",
445
- `Canonical Lucern SDK auth context conflicts with existing ${key} header.`
446
- );
447
- }
448
- headers.set(key, value);
449
- }
450
- return Object.fromEntries(headers.entries());
451
- }
452
- function cleanHeaderValue(value) {
453
- const normalized = value?.trim();
454
- return normalized ? normalized : void 0;
455
- }
456
- function createGatewayRequestClient(config = {}) {
457
- const env = resolveEnvironment();
458
- const runtime = createGatewayRuntime(config, env);
459
- const baseUrl = resolveGatewayBaseUrl(config.baseUrl, env);
460
- const maxRetries = runtime.profile.maxRetries;
461
- const requestIdFactory = runtime.profile.requestIdFactory;
462
- const requestTimeoutByMethod = runtime.profile.timeoutMsByMethod;
463
- const defaultRequestTimeoutMs = runtime.profile.timeoutMs;
464
- const normalizedEnvironment = normalizeGatewayEnvironment(config.environment);
465
- const telemetryExporter = config.telemetryEnabled === false ? null : config.telemetryExporter ?? createTelemetryExporterFromEnv(telemetryEnvironmentRecord(env), {
466
- service: "lucern-sdk",
467
- environment: normalizedEnvironment
468
- });
469
- async function resolveAuthHeaders() {
470
- const provided = config.getAuthHeaders ? await config.getAuthHeaders() : {};
471
- const headers = new Headers(provided);
472
- const setIfAbsent = (name, value) => {
473
- const normalized = cleanHeaderValue(value);
474
- if (normalized && !headers.has(name)) {
475
- headers.set(name, normalized);
476
- }
477
- };
478
- setIfAbsent("x-lucern-key", config.apiKey);
479
- setIfAbsent("x-lucern-session-token", config.userToken);
480
- setIfAbsent("x-lucern-environment", normalizedEnvironment);
481
- setIfAbsent("x-lucern-clerk-id", config.clerkId);
482
- setIfAbsent("x-lucern-user-id", config.userId ?? config.clerkId);
483
- setIfAbsent("x-lucern-deployment-host", config.deploymentHost);
484
- const base = Object.fromEntries(headers.entries());
485
- const authContextInput = await resolveConfiguredAuthContext(
486
- config.authContext
487
- );
488
- if (!authContextInput && !config.requireCanonicalAuthContext) {
489
- return base;
490
- }
491
- const authContext = normalizeCanonicalLucernAuthContext(authContextInput);
492
- return mergeHeaderRecord(base, createCanonicalAuthHeaders(authContext));
493
- }
494
- async function fetchWithTimeout(url, init, timeoutMs) {
495
- const normalizeTransportError = (error, isTimeout) => {
496
- if (isTimeout) {
497
- return new GatewayTimeoutError(timeoutMs);
498
- }
499
- return error instanceof GatewayTimeoutError || error instanceof GatewayTransportError ? error : new GatewayTransportError(
500
- error instanceof Error ? error.message : "Gateway transport error",
501
- {
502
- cause: error,
503
- retryable: classifyGatewayErrorForRetry(error)
504
- }
505
- );
506
- };
507
- const controller = new AbortController();
508
- const timer = setTimeout(() => controller.abort(), timeoutMs);
509
- const requestEffect = Effect.tryPromise({
510
- try: () => runtime.fetch(url, { ...init, signal: controller.signal }),
511
- catch: (error) => normalizeTransportError(error, controller.signal.aborted)
512
- });
513
- try {
514
- const exit = await Effect.runPromiseExit(requestEffect);
515
- if (Exit.isSuccess(exit)) {
516
- return exit.value;
517
- }
518
- const failure = Array.from(Cause.failures(exit.cause))[0];
519
- if (failure !== void 0) {
520
- throw failure;
521
- }
522
- throw Cause.squash(exit.cause);
523
- } finally {
524
- clearTimeout(timer);
525
- }
526
- }
527
- async function emitSdkResponseTelemetry(context) {
528
- const retry = classifyRetry({
529
- status: context.status,
530
- error: context.error,
531
- retryAfter: context.retryAfterMs !== null && context.retryAfterMs !== void 0 ? String(context.retryAfterMs / 1e3) : void 0
532
- });
533
- await emitTelemetrySignal(telemetryExporter, {
534
- signalType: "trace",
535
- surface: "sdk-retry",
536
- eventName: context.willRetry ? "sdk.retry" : context.error ? "sdk.request.error" : "sdk.request.complete",
537
- severity: context.error ? context.willRetry ? "warn" : "error" : "info",
538
- durationMs: context.durationMs,
539
- metricName: "sdk.request.duration_ms",
540
- metricValue: context.durationMs,
541
- correlationId: context.correlationId ?? context.requestId,
542
- policyTraceId: context.policyTraceId ?? null,
543
- tenantId: context.headers.get("x-lucern-tenant-id") ?? context.headers.get("x-lucern-tenant") ?? void 0,
544
- workspaceId: context.headers.get("x-lucern-workspace-id") ?? context.headers.get("x-lucern-workspace") ?? void 0,
545
- attributes: {
546
- service: "lucern-sdk",
547
- operation: "gateway.request",
548
- path: context.path,
549
- httpMethod: context.method,
550
- httpStatus: context.status,
551
- attempt: context.attempt,
552
- maxRetries: context.maxRetries,
553
- retryReason: retry.reason,
554
- retryAfterMs: context.retryAfterMs ?? retry.retryAfterMs,
555
- willRetry: context.willRetry,
556
- retryable: retry.retryable,
557
- errorName: context.error instanceof Error ? context.error.name : void 0,
558
- errorMessage: context.error instanceof Error ? context.error.message : void 0
559
- }
560
- });
561
- }
562
- async function parsePayload(response) {
563
- const text = await response.text();
564
- if (!text) {
565
- return null;
566
- }
567
- const parsed = tryParseGatewayEnvelopeJson(text);
568
- if (!parsed.ok) {
569
- return null;
570
- }
571
- return isRecord(parsed.value) ? parsed.value : null;
572
- }
573
- function resolveTimeoutMs(method, requestTimeoutMs) {
574
- if (typeof requestTimeoutMs === "number") {
575
- return requestTimeoutMs;
576
- }
577
- const methodTimeoutMs = requestTimeoutByMethod?.[method];
578
- if (typeof methodTimeoutMs === "number") {
579
- return methodTimeoutMs;
580
- }
581
- return defaultRequestTimeoutMs;
582
- }
583
- function tryParseGatewayEnvelopeJson(text) {
584
- const trimmed = text.trim();
585
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
586
- return { ok: false, reason: "non-json" };
587
- }
588
- try {
589
- return { ok: true, value: JSON.parse(trimmed) };
590
- } catch (error) {
591
- if (error instanceof SyntaxError) {
592
- return { ok: false, reason: "invalid-json", error };
593
- }
594
- throw error;
595
- }
596
- }
597
- function buildApiError(args) {
598
- const failure = args.failure;
599
- const legacyError = failure && isRecord(failure.error) ? failure.error : failure?.legacyError;
600
- const correlationId = failure?.correlationId ?? args.response.headers.get("x-lucern-correlation-id")?.trim() ?? args.requestId;
601
- const policyTraceId = failure?.policyTraceId ?? args.response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null;
602
- const details = runtime.redaction(
603
- redactJsonDiagnosticValue(failure?.details ?? legacyError?.details)
604
- );
605
- const policySummary = readPolicySummaryFromDetails(details);
606
- const failureMessage = typeof failure?.error === "string" ? failure.error : legacyError?.message;
607
- return new LucernApiError({
608
- code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
609
- message: policySummary ?? failureMessage ?? (args.response.ok ? "Platform API returned an invalid success payload." : "Platform API request failed."),
610
- status: args.response.status,
611
- invariant: failure?.invariant,
612
- suggestion: failure?.suggestion,
613
- details,
614
- requestId: args.requestId,
615
- correlationId,
616
- policyTraceId
617
- });
618
- }
619
- async function request(args) {
620
- const authHeaders = await resolveAuthHeaders();
621
- const method = args.method ?? "GET";
622
- const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);
623
- const headers = new Headers({
624
- "content-type": "application/json",
625
- ...authHeaders
626
- });
627
- if (args.idempotencyKey) {
628
- headers.set("idempotency-key", args.idempotencyKey);
629
- }
630
- const requestId = headers.get("x-correlation-id")?.trim() || headers.get("x-request-id")?.trim() || args.requestId || requestIdFactory();
631
- if (!headers.has("x-correlation-id") && !headers.has("x-request-id")) {
632
- headers.set("x-correlation-id", requestId);
633
- }
634
- const url = `${baseUrl}${args.path}`;
635
- const serializedBody = args.body ? JSON.stringify(args.body) : void 0;
636
- const init = {
637
- method,
638
- headers,
639
- body: serializedBody
640
- };
641
- let lastError;
642
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
643
- const hookRequestContext = {
644
- requestId,
645
- attempt,
646
- maxRetries,
647
- method,
648
- path: args.path,
649
- url,
650
- headers: new Headers(headers),
651
- body: serializedBody,
652
- timeoutMs
653
- };
654
- await config.onRequest?.(hookRequestContext);
655
- const startedAt = Date.now();
656
- try {
657
- const response = await fetchWithTimeout(url, init, timeoutMs);
658
- const responseClone = response.clone();
659
- const payload = await parsePayload(response);
660
- const retry = classifyRetry({
661
- status: response.status,
662
- retryAfter: response.headers.get("Retry-After")
663
- });
664
- const retryAfterMs = retry.retryAfterMs ?? null;
665
- if (!response.ok || !payload?.success) {
666
- const failure = payload && !payload.success ? payload : null;
667
- const apiError = buildApiError({
668
- requestId,
669
- response,
670
- failure
671
- });
672
- const willRetry = attempt < maxRetries && retry.retryable;
673
- const responseContext2 = {
674
- ...hookRequestContext,
675
- durationMs: Date.now() - startedAt,
676
- status: response.status,
677
- response: responseClone,
678
- error: apiError,
679
- correlationId: apiError.correlationId ?? requestId,
680
- policyTraceId: apiError.policyTraceId ?? null,
681
- retryAfterMs,
682
- willRetry
683
- };
684
- await config.onResponse?.(responseContext2);
685
- await emitSdkResponseTelemetry(responseContext2);
686
- if (willRetry) {
687
- lastError = apiError;
688
- await delay(
689
- computeRetryDelayMs({
690
- attempt,
691
- status: response.status,
692
- retryAfterMs
693
- })
694
- );
695
- continue;
696
- }
697
- throw apiError;
698
- }
699
- const successPayload = payload;
700
- const responseContext = {
701
- ...hookRequestContext,
702
- durationMs: Date.now() - startedAt,
703
- status: response.status,
704
- response: responseClone,
705
- correlationId: successPayload.correlationId ?? response.headers.get("x-lucern-correlation-id")?.trim() ?? requestId,
706
- policyTraceId: successPayload.policyTraceId ?? response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null,
707
- idempotentReplay: successPayload.idempotentReplay,
708
- retryAfterMs,
709
- willRetry: false
710
- };
711
- await config.onResponse?.(responseContext);
712
- await emitSdkResponseTelemetry(responseContext);
713
- return successPayload;
714
- } catch (fetchError) {
715
- if (fetchError instanceof LucernApiError) {
716
- throw fetchError;
717
- }
718
- const willRetry = attempt < maxRetries && classifyGatewayErrorForRetry(fetchError);
719
- const responseContext = {
720
- ...hookRequestContext,
721
- durationMs: Date.now() - startedAt,
722
- error: fetchError,
723
- correlationId: requestId,
724
- policyTraceId: null,
725
- willRetry
726
- };
727
- await config.onResponse?.(responseContext);
728
- await emitSdkResponseTelemetry(responseContext);
729
- lastError = fetchError;
730
- if (willRetry) {
731
- await delay(computeRetryDelayMs({ attempt }));
732
- }
733
- }
734
- }
735
- throw lastError instanceof Error ? lastError : new Error("Platform API request failed after retries.");
736
- }
737
- return {
738
- request
739
- };
740
- }
741
-
742
- // src/sdkSurface.ts
743
- function isRecord2(value) {
744
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
745
- }
746
- function asRecord(value) {
747
- return isRecord2(value) ? value : {};
748
- }
749
- function cleanString2(value) {
750
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
751
- }
752
- function cloneWith(value, patch) {
753
- return { ...value, ...patch };
754
- }
755
- function resolveTopicId(value) {
756
- return cleanString2(value.topicId);
757
- }
758
- function withTopicAlias(value) {
759
- const topicId = cleanString2(value.topicId) ?? void 0;
760
- if (!topicId) {
761
- return value;
762
- }
763
- return cloneWith(value, { topicId });
764
- }
765
- function withTextAlias(value) {
766
- const text = cleanString2(value.text) ?? cleanString2(value.canonicalText) ?? void 0;
767
- if (!text) {
768
- return value;
769
- }
770
- return cloneWith(value, { text, canonicalText: text });
771
- }
772
- function withSdkAliases(value) {
773
- return withTopicAlias(withTextAlias(value));
774
- }
775
- function normalizeTopicQuery(value) {
776
- const topicId = cleanString2(value.topicId);
777
- if (!topicId) {
778
- return value;
779
- }
780
- return { ...value, topicId };
781
- }
782
- function asListItems(data, legacyKey) {
783
- if (Array.isArray(data)) {
784
- return data;
785
- }
786
- const record = asRecord(data);
787
- if (Array.isArray(record.items)) {
788
- return record.items;
789
- }
790
- if (legacyKey && Array.isArray(record[legacyKey])) {
791
- return record[legacyKey];
792
- }
793
- return [];
794
- }
795
- function createListResult(items, legacyKey) {
796
- const result = {
797
- items,
798
- total: items.length
799
- };
800
- if (legacyKey) {
1
+ import { createGatewayRequestClient, LucernApiError, randomIdempotencyKey, toQueryString, } from "./coreClient.js";
2
+ import { asListItems, createListResult, mapAliasedList, mapGatewayData, normalizeTopicQuery, resolveTopicId, withTopicAlias, } from "./sdkSurface.js";
3
+ export { LucernApiError };
4
+ function normalizeLensQuery(value) {
5
+ const topicId = resolveTopicId(value);
801
6
  return {
802
- ...result,
803
- [legacyKey]: items
7
+ ...value,
8
+ ...(topicId ? { topicId } : {}),
804
9
  };
805
- }
806
- return result;
807
10
  }
808
- function mapGatewayData(response, mapper) {
809
- return {
810
- ...response,
811
- data: mapper(response.data)
812
- };
813
- }
814
- function mapAliasedList(data, legacyKey) {
815
- const items = asListItems(data, legacyKey).map(
816
- (item) => withSdkAliases(item)
817
- );
818
- return createListResult(items, legacyKey);
819
- }
820
-
821
- // src/workflowClient.ts
822
- function normalizeLensQuery(value) {
823
- const topicId = resolveTopicId(value);
824
- return {
825
- ...value,
826
- ...topicId ? { topicId } : {}
827
- };
828
- }
829
- function createWorkflowClient(config = {}) {
830
- const gateway = createGatewayRequestClient(config);
831
- const client = {
832
- /**
833
- * List workflow branches for a topic scope.
834
- */
835
- async listBranches(query) {
836
- return gateway.request({
837
- path: `/api/platform/v1/workflow/branches${toQueryString(
838
- normalizeTopicQuery(query)
839
- )}`
840
- }).then(
841
- (response) => mapGatewayData(
842
- response,
843
- (data) => mapAliasedList(data, "branches")
844
- )
845
- );
846
- },
847
- /**
848
- * Create a workflow branch.
849
- */
850
- async createBranch(input, idempotencyKey) {
851
- return gateway.request({
852
- path: "/api/platform/v1/workflow/branches",
853
- method: "POST",
854
- body: normalizeTopicQuery(input),
855
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
856
- }).then(
857
- (response) => mapGatewayData(
858
- response,
859
- (data) => withTopicAlias(data)
860
- )
861
- );
862
- },
863
- /**
864
- * List reusable lenses for a workspace or topic scope.
865
- */
866
- async listLenses(query) {
867
- return gateway.request({
868
- path: `/api/platform/v1/workflow/lenses${toQueryString(
869
- normalizeLensQuery(query)
870
- )}`
871
- }).then(
872
- (response) => mapGatewayData(
873
- response,
874
- (data) => mapAliasedList(data, "lenses")
875
- )
876
- );
877
- },
878
- /**
879
- * Create a reusable workflow lens.
880
- */
881
- async createLens(input, idempotencyKey) {
882
- const payload = normalizeLensQuery(input);
883
- return gateway.request({
884
- path: "/api/platform/v1/workflow/lenses",
885
- method: "POST",
886
- body: payload,
887
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
888
- }).then(
889
- (response) => mapGatewayData(
890
- response,
891
- (data) => withTopicAlias(data)
892
- )
893
- );
894
- },
895
- /**
896
- * Apply an existing lens to a topic.
897
- */
898
- async applyLensToTopic(input, idempotencyKey) {
899
- const payload = normalizeLensQuery(input);
900
- return gateway.request({
901
- path: "/api/platform/v1/workflow/lens-bindings",
902
- method: "POST",
903
- body: payload,
904
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
905
- }).then(
906
- (response) => mapGatewayData(
907
- response,
908
- (data) => withTopicAlias(data)
909
- )
910
- );
911
- },
912
- /**
913
- * Remove an applied lens from a topic.
914
- */
915
- async removeLensFromTopic(input, idempotencyKey) {
916
- const topicId = resolveTopicId(input);
917
- if (!topicId) {
918
- throw new LucernApiError({
919
- code: "INVALID_REQUEST",
920
- message: "topicId is required",
921
- status: 400
922
- });
923
- }
924
- return gateway.request({
925
- path: `/api/platform/v1/workflow/lens-bindings${toQueryString({
926
- lensId: input.lensId,
927
- topicId
928
- })}`,
929
- method: "DELETE",
930
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
931
- }).then(
932
- (response) => mapGatewayData(
933
- response,
934
- (data) => withTopicAlias(data)
935
- )
936
- );
937
- },
938
- /**
939
- * List worktrees for a topic scope.
940
- */
941
- async listWorktrees(query) {
942
- const normalized = normalizeTopicQuery(query);
943
- return gateway.request({
944
- path: `/api/platform/v1/worktrees${toQueryString({
945
- ...normalized,
946
- groupBy: query.groupBy,
947
- lane: query.lane,
948
- campaign: query.campaign,
949
- limit: query.limit
950
- })}`
951
- }).then(
952
- (response) => mapGatewayData(
953
- response,
954
- (data) => mapAliasedList(
955
- data,
956
- "worktrees"
957
- )
958
- )
959
- );
960
- },
961
- /**
962
- * List all worktrees across accessible topics.
963
- */
964
- async listAllWorktrees(query = {}) {
965
- return gateway.request({
966
- path: `/api/platform/v1/worktrees/all${toQueryString({
967
- status: query.status,
968
- groupBy: query.groupBy,
969
- lane: query.lane,
970
- campaign: query.campaign,
971
- limit: query.limit
972
- })}`
973
- }).then(
974
- (response) => mapGatewayData(response, (data) => {
975
- const record = data && typeof data === "object" && !Array.isArray(data) ? data : {};
976
- const list = mapAliasedList(
977
- data,
978
- "worktrees"
979
- );
980
- return {
981
- ...list,
982
- ...record.lanes && typeof record.lanes === "object" && !Array.isArray(record.lanes) ? { lanes: record.lanes } : {},
983
- ...record.campaigns && typeof record.campaigns === "object" && !Array.isArray(record.campaigns) ? { campaigns: record.campaigns } : {}
984
- };
985
- })
986
- );
987
- },
988
- /**
989
- * List compact pipeline campaigns with nested lanes.
990
- */
991
- async listCampaigns(query = {}) {
992
- return gateway.request({
993
- path: `/api/platform/v1/worktrees/campaigns${toQueryString(
994
- normalizeTopicQuery(query)
995
- )}`
996
- });
997
- },
998
- /**
999
- * Create a workflow worktree.
1000
- */
1001
- async createWorktree(input, idempotencyKey) {
1002
- return gateway.request({
1003
- path: "/api/platform/v1/worktrees",
1004
- method: "POST",
1005
- body: normalizeTopicQuery(input),
1006
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1007
- }).then(
1008
- (response) => mapGatewayData(
1009
- response,
1010
- (data) => withTopicAlias(data)
1011
- )
1012
- );
1013
- },
1014
- /**
1015
- * Merge a worktree into the main belief line.
1016
- */
1017
- async merge(worktreeId, input, idempotencyKey) {
1018
- return gateway.request({
1019
- path: `/api/platform/v1/worktrees/${encodeURIComponent(worktreeId)}/merge`,
1020
- method: "POST",
1021
- body: input,
1022
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1023
- });
1024
- },
1025
- /**
1026
- * Activate a planning worktree.
1027
- */
1028
- async activateWorktree(worktreeId, idempotencyKey) {
1029
- return gateway.request({
1030
- path: `/api/platform/v1/worktrees/${encodeURIComponent(worktreeId)}/activate`,
1031
- method: "POST",
1032
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1033
- }).then(
1034
- (response) => mapGatewayData(
1035
- response,
1036
- (data) => withTopicAlias(data)
1037
- )
1038
- );
1039
- },
1040
- /**
1041
- * Update targeted beliefs/questions for a worktree.
1042
- */
1043
- async updateWorktreeTargets(input, idempotencyKey) {
1044
- const { worktreeId, ...body } = input;
1045
- return gateway.request({
1046
- path: `/api/platform/v1/worktrees/${encodeURIComponent(worktreeId)}/targets`,
1047
- method: "POST",
1048
- body,
1049
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1050
- }).then(
1051
- (response) => mapGatewayData(
1052
- response,
1053
- (data) => withTopicAlias(data)
1054
- )
1055
- );
1056
- },
1057
- /**
1058
- * Mark a worktree record complete.
1059
- */
1060
- async completeWorktree(input, idempotencyKey) {
1061
- return gateway.request({
1062
- path: "/api/platform/v1/worktrees/complete",
1063
- method: "POST",
1064
- body: input,
1065
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1066
- });
1067
- },
1068
- /**
1069
- * Advance a worktree to its next lifecycle phase.
1070
- */
1071
- async advanceWorktreePhase(input, idempotencyKey) {
1072
- return gateway.request({
1073
- path: "/api/platform/v1/worktrees/advance-phase",
1074
- method: "POST",
1075
- body: input,
1076
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1077
- });
1078
- },
1079
- /**
1080
- * Force a worktree into a specific lifecycle phase.
1081
- */
1082
- async setWorktreePhase(input, idempotencyKey) {
1083
- return gateway.request({
1084
- path: "/api/platform/v1/worktrees/set-phase",
1085
- method: "POST",
1086
- body: input,
1087
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1088
- });
1089
- },
1090
- /**
1091
- * Patch opaque worktree state for orchestration flows.
1092
- */
1093
- async patchWorktreeState(input, idempotencyKey) {
1094
- return gateway.request({
1095
- path: "/api/platform/v1/worktrees/patch-state",
1096
- method: "POST",
1097
- body: input,
1098
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1099
- });
1100
- },
1101
- /**
1102
- * Batch create worktree records.
1103
- */
1104
- async bulkCreateWorktrees(input, idempotencyKey) {
1105
- return gateway.request({
1106
- path: "/api/platform/v1/worktrees/bulk",
1107
- method: "POST",
1108
- body: input,
1109
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1110
- });
1111
- },
1112
- /**
1113
- * Open a pull request for a worktree.
1114
- */
1115
- async openPullRequest(worktreeId, input, idempotencyKey) {
1116
- return gateway.request({
1117
- path: `/api/platform/v1/workflow/worktrees/${encodeURIComponent(worktreeId)}/pull-request`,
1118
- method: "POST",
1119
- body: input,
1120
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1121
- });
1122
- },
1123
- /**
1124
- * Push scored worktree findings into another context.
1125
- */
1126
- async push(worktreeId, input, idempotencyKey) {
1127
- return gateway.request({
1128
- path: `/api/platform/v1/workflow/worktrees/${encodeURIComponent(worktreeId)}/push`,
1129
- method: "POST",
1130
- body: input,
1131
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1132
- });
1133
- },
1134
- /**
1135
- * List accessible topic contexts.
1136
- */
1137
- async listTopics(query = {}) {
1138
- return gateway.request({
1139
- path: `/api/platform/v1/workflow/topics${toQueryString({
1140
- includeShared: typeof query.includeShared === "boolean" ? query.includeShared ? "true" : "false" : void 0,
1141
- limit: query.limit
1142
- })}`
1143
- }).then(
1144
- (response) => mapGatewayData(response, (data) => {
1145
- const items = asListItems(data, "topics").map(
1146
- (item) => withTopicAlias(
1147
- item
1148
- )
1149
- );
1150
- const record = data && typeof data === "object" ? data : {};
1151
- return {
1152
- ...record,
1153
- ...createListResult(items, "topics"),
1154
- total: typeof record.total === "number" ? record.total : items.length
1155
- };
1156
- })
1157
- );
1158
- },
1159
- /**
1160
- * Switch the active context by topic or project name.
1161
- */
1162
- async switchTopicContext(input, idempotencyKey) {
1163
- return gateway.request({
1164
- path: "/api/platform/v1/workflow/topics/switch",
1165
- method: "POST",
1166
- body: {
1167
- targetTopicName: input.targetTopicName
11
+ /**
12
+ * Create the workflow client for lenses, legacy branches, worktrees, context,
13
+ * and tasks.
14
+ * @param config - Gateway transport configuration.
15
+ * @returns An object with methods to manage branches, lenses, worktrees, topics, and tasks.
16
+ */
17
+ export function createWorkflowClient(config = {}) {
18
+ const gateway = createGatewayRequestClient(config);
19
+ const client = {
20
+ /**
21
+ * List workflow branches for a topic scope.
22
+ */
23
+ async listBranches(query) {
24
+ return gateway.request({
25
+ path: `/api/platform/v1/workflow/branches${toQueryString(normalizeTopicQuery(query))}`,
26
+ }).then((response) => mapGatewayData(response, (data) => mapAliasedList(data, "branches")));
27
+ },
28
+ /**
29
+ * Create a workflow branch.
30
+ */
31
+ async createBranch(input, idempotencyKey) {
32
+ return gateway.request({
33
+ path: "/api/platform/v1/workflow/branches",
34
+ method: "POST",
35
+ body: normalizeTopicQuery(input),
36
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
37
+ }).then((response) => mapGatewayData(response, (data) => withTopicAlias(data)));
38
+ },
39
+ /**
40
+ * List reusable lenses for a workspace or topic scope.
41
+ */
42
+ async listLenses(query) {
43
+ return gateway.request({
44
+ path: `/api/platform/v1/workflow/lenses${toQueryString(normalizeLensQuery(query))}`,
45
+ }).then((response) => mapGatewayData(response, (data) => mapAliasedList(data, "lenses")));
46
+ },
47
+ /**
48
+ * Create a reusable workflow lens.
49
+ */
50
+ async createLens(input, idempotencyKey) {
51
+ const payload = normalizeLensQuery(input);
52
+ return gateway.request({
53
+ path: "/api/platform/v1/workflow/lenses",
54
+ method: "POST",
55
+ body: payload,
56
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
57
+ }).then((response) => mapGatewayData(response, (data) => withTopicAlias(data)));
58
+ },
59
+ /**
60
+ * Apply an existing lens to a topic.
61
+ */
62
+ async applyLensToTopic(input, idempotencyKey) {
63
+ const payload = normalizeLensQuery(input);
64
+ return gateway.request({
65
+ path: "/api/platform/v1/workflow/lens-bindings",
66
+ method: "POST",
67
+ body: payload,
68
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
69
+ }).then((response) => mapGatewayData(response, (data) => withTopicAlias(data)));
70
+ },
71
+ /**
72
+ * Remove an applied lens from a topic.
73
+ */
74
+ async removeLensFromTopic(input, idempotencyKey) {
75
+ const topicId = resolveTopicId(input);
76
+ if (!topicId) {
77
+ throw new LucernApiError({
78
+ code: "INVALID_REQUEST",
79
+ message: "topicId is required",
80
+ status: 400,
81
+ });
82
+ }
83
+ return gateway.request({
84
+ path: `/api/platform/v1/workflow/lens-bindings${toQueryString({
85
+ lensId: input.lensId,
86
+ topicId,
87
+ })}`,
88
+ method: "DELETE",
89
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
90
+ }).then((response) => mapGatewayData(response, (data) => withTopicAlias(data)));
91
+ },
92
+ /**
93
+ * List worktrees for a topic scope.
94
+ */
95
+ async listWorktrees(query) {
96
+ const normalized = normalizeTopicQuery(query);
97
+ return gateway.request({
98
+ path: `/api/platform/v1/worktrees${toQueryString({
99
+ ...normalized,
100
+ groupBy: query.groupBy,
101
+ lane: query.lane,
102
+ campaign: query.campaign,
103
+ limit: query.limit,
104
+ })}`,
105
+ }).then((response) => mapGatewayData(response, (data) => mapAliasedList(data, "worktrees")));
1168
106
  },
1169
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1170
- }).then(
1171
- (response) => mapGatewayData(
1172
- response,
1173
- (data) => withTopicAlias(
1174
- data
1175
- )
1176
- )
1177
- );
1178
- },
1179
- /**
1180
- * Create a workflow task.
1181
- */
1182
- async createTask(input, idempotencyKey) {
1183
- return gateway.request({
1184
- path: "/api/platform/v1/workflow/tasks",
1185
- method: "POST",
1186
- body: normalizeTopicQuery(input),
1187
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1188
- });
1189
- },
1190
- /**
1191
- * Complete a workflow task.
1192
- */
1193
- async completeTask(taskId, input, idempotencyKey) {
1194
- return gateway.request({
1195
- path: `/api/platform/v1/workflow/tasks/${encodeURIComponent(taskId)}/complete`,
1196
- method: "POST",
1197
- body: input,
1198
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1199
- });
1200
- },
1201
- /**
1202
- * Update a workflow task.
1203
- */
1204
- async updateTask(taskId, input, idempotencyKey) {
1205
- return gateway.request({
1206
- path: `/api/platform/v1/workflow/tasks/${encodeURIComponent(taskId)}`,
1207
- method: "PATCH",
1208
- body: input,
1209
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1210
- });
1211
- }
1212
- };
1213
- return Object.assign(client, {
1214
- addWorktree: client.createWorktree,
1215
- createPillar: client.createBranch,
1216
- createSprint: client.createWorktree,
1217
- completeSprint: client.merge,
1218
- requestReview: client.openPullRequest,
1219
- publishFindings: client.push
1220
- });
107
+ /**
108
+ * List all worktrees across accessible topics.
109
+ */
110
+ async listAllWorktrees(query = {}) {
111
+ return gateway.request({
112
+ path: `/api/platform/v1/worktrees/all${toQueryString({
113
+ status: query.status,
114
+ groupBy: query.groupBy,
115
+ lane: query.lane,
116
+ campaign: query.campaign,
117
+ limit: query.limit,
118
+ })}`,
119
+ }).then((response) => mapGatewayData(response, (data) => {
120
+ const record = data && typeof data === "object" && !Array.isArray(data)
121
+ ? data
122
+ : {};
123
+ const list = mapAliasedList(data, "worktrees");
124
+ return {
125
+ ...list,
126
+ ...(record.lanes &&
127
+ typeof record.lanes === "object" &&
128
+ !Array.isArray(record.lanes)
129
+ ? { lanes: record.lanes }
130
+ : {}),
131
+ ...(record.campaigns &&
132
+ typeof record.campaigns === "object" &&
133
+ !Array.isArray(record.campaigns)
134
+ ? { campaigns: record.campaigns }
135
+ : {}),
136
+ };
137
+ }));
138
+ },
139
+ /**
140
+ * List compact pipeline campaigns with nested lanes.
141
+ */
142
+ async listCampaigns(query = {}) {
143
+ return gateway.request({
144
+ path: `/api/platform/v1/worktrees/campaigns${toQueryString(normalizeTopicQuery(query))}`,
145
+ });
146
+ },
147
+ /**
148
+ * Create a workflow worktree.
149
+ */
150
+ async createWorktree(input, idempotencyKey) {
151
+ return gateway.request({
152
+ path: "/api/platform/v1/worktrees",
153
+ method: "POST",
154
+ body: normalizeTopicQuery(input),
155
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
156
+ }).then((response) => mapGatewayData(response, (data) => withTopicAlias(data)));
157
+ },
158
+ /**
159
+ * Merge a worktree into the main belief line.
160
+ */
161
+ async merge(worktreeId, input, idempotencyKey) {
162
+ return gateway.request({
163
+ path: `/api/platform/v1/worktrees/${encodeURIComponent(worktreeId)}/merge`,
164
+ method: "POST",
165
+ body: input,
166
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
167
+ });
168
+ },
169
+ /**
170
+ * Activate a planning worktree.
171
+ */
172
+ async activateWorktree(worktreeId, idempotencyKey) {
173
+ return gateway.request({
174
+ path: `/api/platform/v1/worktrees/${encodeURIComponent(worktreeId)}/activate`,
175
+ method: "POST",
176
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
177
+ }).then((response) => mapGatewayData(response, (data) => withTopicAlias(data)));
178
+ },
179
+ /**
180
+ * Update targeted beliefs/questions for a worktree.
181
+ */
182
+ async updateWorktreeTargets(input, idempotencyKey) {
183
+ const { worktreeId, ...body } = input;
184
+ return gateway.request({
185
+ path: `/api/platform/v1/worktrees/${encodeURIComponent(worktreeId)}/targets`,
186
+ method: "POST",
187
+ body,
188
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
189
+ }).then((response) => mapGatewayData(response, (data) => withTopicAlias(data)));
190
+ },
191
+ /**
192
+ * Mark a worktree record complete.
193
+ */
194
+ async completeWorktree(input, idempotencyKey) {
195
+ return gateway.request({
196
+ path: "/api/platform/v1/worktrees/complete",
197
+ method: "POST",
198
+ body: input,
199
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
200
+ });
201
+ },
202
+ /**
203
+ * Advance a worktree to its next lifecycle phase.
204
+ */
205
+ async advanceWorktreePhase(input, idempotencyKey) {
206
+ return gateway.request({
207
+ path: "/api/platform/v1/worktrees/advance-phase",
208
+ method: "POST",
209
+ body: input,
210
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
211
+ });
212
+ },
213
+ /**
214
+ * Force a worktree into a specific lifecycle phase.
215
+ */
216
+ async setWorktreePhase(input, idempotencyKey) {
217
+ return gateway.request({
218
+ path: "/api/platform/v1/worktrees/set-phase",
219
+ method: "POST",
220
+ body: input,
221
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
222
+ });
223
+ },
224
+ /**
225
+ * Patch opaque worktree state for orchestration flows.
226
+ */
227
+ async patchWorktreeState(input, idempotencyKey) {
228
+ return gateway.request({
229
+ path: "/api/platform/v1/worktrees/patch-state",
230
+ method: "POST",
231
+ body: input,
232
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
233
+ });
234
+ },
235
+ /**
236
+ * Batch create worktree records.
237
+ */
238
+ async bulkCreateWorktrees(input, idempotencyKey) {
239
+ return gateway.request({
240
+ path: "/api/platform/v1/worktrees/bulk",
241
+ method: "POST",
242
+ body: input,
243
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
244
+ });
245
+ },
246
+ /**
247
+ * Open a pull request for a worktree.
248
+ */
249
+ async openPullRequest(worktreeId, input, idempotencyKey) {
250
+ return gateway.request({
251
+ path: `/api/platform/v1/workflow/worktrees/${encodeURIComponent(worktreeId)}/pull-request`,
252
+ method: "POST",
253
+ body: input,
254
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
255
+ });
256
+ },
257
+ /**
258
+ * Push scored worktree findings into another context.
259
+ */
260
+ async push(worktreeId, input, idempotencyKey) {
261
+ return gateway.request({
262
+ path: `/api/platform/v1/workflow/worktrees/${encodeURIComponent(worktreeId)}/push`,
263
+ method: "POST",
264
+ body: input,
265
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
266
+ });
267
+ },
268
+ /**
269
+ * List accessible topic contexts.
270
+ */
271
+ async listTopics(query = {}) {
272
+ return gateway.request({
273
+ path: `/api/platform/v1/workflow/topics${toQueryString({
274
+ includeShared: typeof query.includeShared === "boolean"
275
+ ? query.includeShared
276
+ ? "true"
277
+ : "false"
278
+ : undefined,
279
+ limit: query.limit,
280
+ })}`,
281
+ }).then((response) => mapGatewayData(response, (data) => {
282
+ const items = asListItems(data, "topics").map((item) => withTopicAlias(item));
283
+ const record = data && typeof data === "object"
284
+ ? data
285
+ : {};
286
+ return {
287
+ ...record,
288
+ ...createListResult(items, "topics"),
289
+ total: typeof record.total === "number" ? record.total : items.length,
290
+ };
291
+ }));
292
+ },
293
+ /**
294
+ * Switch the active context by topic or project name.
295
+ */
296
+ async switchTopicContext(input, idempotencyKey) {
297
+ return gateway.request({
298
+ path: "/api/platform/v1/workflow/topics/switch",
299
+ method: "POST",
300
+ body: {
301
+ targetTopicName: input.targetTopicName,
302
+ },
303
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
304
+ }).then((response) => mapGatewayData(response, (data) => withTopicAlias(data)));
305
+ },
306
+ /**
307
+ * Create a workflow task.
308
+ */
309
+ async createTask(input, idempotencyKey) {
310
+ return gateway.request({
311
+ path: "/api/platform/v1/workflow/tasks",
312
+ method: "POST",
313
+ body: normalizeTopicQuery(input),
314
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
315
+ });
316
+ },
317
+ /**
318
+ * Complete a workflow task.
319
+ */
320
+ async completeTask(taskId, input, idempotencyKey) {
321
+ return gateway.request({
322
+ path: `/api/platform/v1/workflow/tasks/${encodeURIComponent(taskId)}/complete`,
323
+ method: "POST",
324
+ body: input,
325
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
326
+ });
327
+ },
328
+ /**
329
+ * Update a workflow task.
330
+ */
331
+ async updateTask(taskId, input, idempotencyKey) {
332
+ return gateway.request({
333
+ path: `/api/platform/v1/workflow/tasks/${encodeURIComponent(taskId)}`,
334
+ method: "PATCH",
335
+ body: input,
336
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),
337
+ });
338
+ },
339
+ };
340
+ return Object.assign(client, {
341
+ addWorktree: client.createWorktree,
342
+ createPillar: client.createBranch,
343
+ createSprint: client.createWorktree,
344
+ completeSprint: client.merge,
345
+ requestReview: client.openPullRequest,
346
+ publishFindings: client.push,
347
+ });
1221
348
  }
1222
-
1223
- export { LucernApiError, createWorkflowClient };
1224
- //# sourceMappingURL=workflowClient.js.map
1225
349
  //# sourceMappingURL=workflowClient.js.map