@lucern/sdk 0.2.0-alpha.7 → 0.2.0-alpha.9

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 (257) hide show
  1. package/dist/adminClient.d.ts +409 -0
  2. package/dist/adminClient.js +755 -0
  3. package/dist/adminClient.js.map +1 -0
  4. package/dist/answersClient.d.ts +23 -0
  5. package/dist/answersClient.js +333 -0
  6. package/dist/answersClient.js.map +1 -0
  7. package/dist/audiencesClient.d.ts +99 -0
  8. package/dist/audiencesClient.js +472 -0
  9. package/dist/audiencesClient.js.map +1 -0
  10. package/dist/auditClient.d.ts +29 -0
  11. package/dist/auditClient.js +386 -0
  12. package/dist/auditClient.js.map +1 -0
  13. package/dist/beliefsClient.d.ts +162 -0
  14. package/dist/beliefsClient.js +477 -0
  15. package/dist/beliefsClient.js.map +1 -0
  16. package/dist/client.d.ts +2378 -0
  17. package/dist/client.js +6134 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/contextClient.d.ts +27 -0
  20. package/dist/contextClient.js +396 -0
  21. package/dist/contextClient.js.map +1 -0
  22. package/dist/contextFacade.d.ts +2 -0
  23. package/dist/contextFacade.js +73 -0
  24. package/dist/contextFacade.js.map +1 -0
  25. package/dist/contextPackCompiler.d.ts +102 -0
  26. package/dist/contextPackCompiler.js +1091 -0
  27. package/dist/contextPackCompiler.js.map +1 -0
  28. package/dist/contextPackPolicy.d.ts +84 -0
  29. package/dist/contextPackPolicy.js +347 -0
  30. package/dist/contextPackPolicy.js.map +1 -0
  31. package/dist/contextPackSchema.d.ts +7 -0
  32. package/{src/contextPackSchema.ts → dist/contextPackSchema.js} +22 -70
  33. package/dist/contextPackSchema.js.map +1 -0
  34. package/dist/contextTypes.d.ts +135 -0
  35. package/dist/contextTypes.js +3 -0
  36. package/dist/contextTypes.js.map +1 -0
  37. package/dist/contracts/api-enums.contract.d.ts +81 -0
  38. package/dist/contracts/api-enums.contract.js +92 -0
  39. package/dist/contracts/api-enums.contract.js.map +1 -0
  40. package/dist/contracts/auth-session.contract.d.ts +55 -0
  41. package/dist/contracts/auth-session.contract.js +48 -0
  42. package/dist/contracts/auth-session.contract.js.map +1 -0
  43. package/dist/contracts/context-pack.contract.d.ts +492 -0
  44. package/dist/contracts/context-pack.contract.js +98 -0
  45. package/dist/contracts/context-pack.contract.js.map +1 -0
  46. package/dist/contracts/contextPack.d.ts +1 -0
  47. package/dist/contracts/contextPack.js +98 -0
  48. package/dist/contracts/contextPack.js.map +1 -0
  49. package/dist/contracts/index.d.ts +9 -0
  50. package/dist/contracts/index.js +4892 -0
  51. package/dist/contracts/index.js.map +1 -0
  52. package/dist/contracts/lens-filter.contract.d.ts +72 -0
  53. package/dist/contracts/lens-filter.contract.js +71 -0
  54. package/dist/contracts/lens-filter.contract.js.map +1 -0
  55. package/dist/contracts/lens-workflow.contract.d.ts +87 -0
  56. package/dist/contracts/lens-workflow.contract.js +123 -0
  57. package/dist/contracts/lens-workflow.contract.js.map +1 -0
  58. package/dist/contracts/lensFilter.d.ts +1 -0
  59. package/dist/contracts/lensFilter.js +71 -0
  60. package/dist/contracts/lensFilter.js.map +1 -0
  61. package/dist/contracts/lensWorkflow.d.ts +2 -0
  62. package/dist/contracts/lensWorkflow.js +123 -0
  63. package/dist/contracts/lensWorkflow.js.map +1 -0
  64. package/dist/contracts/mcp-tools.contract.d.ts +1 -0
  65. package/dist/contracts/mcp-tools.contract.js +2986 -0
  66. package/dist/contracts/mcp-tools.contract.js.map +1 -0
  67. package/dist/contracts/mcpTools.d.ts +1 -0
  68. package/dist/contracts/mcpTools.js +2986 -0
  69. package/dist/contracts/mcpTools.js.map +1 -0
  70. package/dist/contracts/prompt.contract.d.ts +26 -0
  71. package/dist/contracts/prompt.contract.js +12 -0
  72. package/dist/contracts/prompt.contract.js.map +1 -0
  73. package/dist/contracts/prompt.d.ts +1 -0
  74. package/dist/contracts/prompt.js +12 -0
  75. package/dist/contracts/prompt.js.map +1 -0
  76. package/dist/contracts/sdk-tools.contract.d.ts +2 -0
  77. package/dist/contracts/sdk-tools.contract.js +4134 -0
  78. package/dist/contracts/sdk-tools.contract.js.map +1 -0
  79. package/dist/contracts/sdkTools.d.ts +2 -0
  80. package/dist/contracts/sdkTools.js +4134 -0
  81. package/dist/contracts/sdkTools.js.map +1 -0
  82. package/dist/contracts/workflow-runtime.contract.d.ts +163 -0
  83. package/dist/contracts/workflow-runtime.contract.js +245 -0
  84. package/dist/contracts/workflow-runtime.contract.js.map +1 -0
  85. package/dist/contracts/workflowRuntime.d.ts +1 -0
  86. package/dist/contracts/workflowRuntime.js +245 -0
  87. package/dist/contracts/workflowRuntime.js.map +1 -0
  88. package/dist/controlObjectOwnership.d.ts +310 -0
  89. package/{src/controlObjectOwnership.ts → dist/controlObjectOwnership.js} +53 -124
  90. package/dist/controlObjectOwnership.js.map +1 -0
  91. package/dist/coreClient.d.ts +144 -0
  92. package/dist/coreClient.js +339 -0
  93. package/dist/coreClient.js.map +1 -0
  94. package/dist/customTools.d.ts +88 -0
  95. package/dist/customTools.js +248 -0
  96. package/dist/customTools.js.map +1 -0
  97. package/dist/decisionsClient.d.ts +111 -0
  98. package/dist/decisionsClient.js +522 -0
  99. package/dist/decisionsClient.js.map +1 -0
  100. package/dist/domainContext.d.ts +1 -0
  101. package/dist/domainContext.js +3 -0
  102. package/dist/domainContext.js.map +1 -0
  103. package/dist/events.d.ts +178 -0
  104. package/dist/events.js +249 -0
  105. package/dist/events.js.map +1 -0
  106. package/dist/eventsCore.d.ts +49 -0
  107. package/dist/eventsCore.js +429 -0
  108. package/dist/eventsCore.js.map +1 -0
  109. package/dist/facade/context.d.ts +18 -0
  110. package/dist/facade/context.js +73 -0
  111. package/dist/facade/context.js.map +1 -0
  112. package/dist/gatewayFacades.d.ts +591 -0
  113. package/dist/gatewayFacades.js +1953 -0
  114. package/dist/gatewayFacades.js.map +1 -0
  115. package/dist/graphClient.d.ts +271 -0
  116. package/dist/graphClient.js +698 -0
  117. package/dist/graphClient.js.map +1 -0
  118. package/dist/harnessClient.d.ts +314 -0
  119. package/dist/harnessClient.js +607 -0
  120. package/dist/harnessClient.js.map +1 -0
  121. package/dist/identityClient.d.ts +140 -0
  122. package/dist/identityClient.js +497 -0
  123. package/dist/identityClient.js.map +1 -0
  124. package/dist/index.d.ts +42 -0
  125. package/dist/index.js +11381 -0
  126. package/dist/index.js.map +1 -0
  127. package/dist/learningClient.d.ts +46 -0
  128. package/dist/learningClient.js +409 -0
  129. package/dist/learningClient.js.map +1 -0
  130. package/dist/mcpParityClient.d.ts +74 -0
  131. package/dist/mcpParityClient.js +516 -0
  132. package/dist/mcpParityClient.js.map +1 -0
  133. package/dist/mcpParitySurface.d.ts +12 -0
  134. package/{src/mcpParitySurface.ts → dist/mcpParitySurface.js} +9 -14
  135. package/dist/mcpParitySurface.js.map +1 -0
  136. package/dist/mcpTools-DPZxowDX.d.ts +254 -0
  137. package/dist/ontologyClient.d.ts +137 -0
  138. package/dist/ontologyClient.js +513 -0
  139. package/dist/ontologyClient.js.map +1 -0
  140. package/dist/packRuntime.d.ts +2 -0
  141. package/dist/packRuntime.js +3 -0
  142. package/dist/packRuntime.js.map +1 -0
  143. package/dist/packsClient.d.ts +131 -0
  144. package/dist/packsClient.js +525 -0
  145. package/dist/packsClient.js.map +1 -0
  146. package/dist/policyClient.d.ts +299 -0
  147. package/dist/policyClient.js +625 -0
  148. package/dist/policyClient.js.map +1 -0
  149. package/dist/realtime/index.d.ts +29 -0
  150. package/dist/realtime/index.js +23 -0
  151. package/dist/realtime/index.js.map +1 -0
  152. package/{src/realtime/refs.ts → dist/realtime/refs.d.ts} +5 -5
  153. package/dist/realtime/refs.js +9 -0
  154. package/dist/realtime/refs.js.map +1 -0
  155. package/dist/reportsClient.d.ts +41 -0
  156. package/dist/reportsClient.js +418 -0
  157. package/dist/reportsClient.js.map +1 -0
  158. package/dist/schemaClient.d.ts +64 -0
  159. package/dist/schemaClient.js +434 -0
  160. package/dist/schemaClient.js.map +1 -0
  161. package/dist/sdkSurface.d.ts +61 -0
  162. package/dist/sdkSurface.js +112 -0
  163. package/dist/sdkSurface.js.map +1 -0
  164. package/dist/sdkTools-CwXJDACb.d.ts +150 -0
  165. package/dist/topicsClient.d.ts +84 -0
  166. package/dist/topicsClient.js +492 -0
  167. package/dist/topicsClient.js.map +1 -0
  168. package/dist/types.d.ts +696 -0
  169. package/dist/types.js +3 -0
  170. package/dist/types.js.map +1 -0
  171. package/dist/version.d.ts +4 -0
  172. package/dist/version.js +6 -0
  173. package/dist/version.js.map +1 -0
  174. package/dist/workflowClient.d.ts +316 -0
  175. package/dist/workflowClient.js +830 -0
  176. package/dist/workflowClient.js.map +1 -0
  177. package/package.json +39 -7
  178. package/.turbo/turbo-build.log +0 -7
  179. package/.turbo/turbo-typecheck.log +0 -4
  180. package/examples/README.md +0 -69
  181. package/examples/contradiction.ts +0 -94
  182. package/examples/investigation-context.ts +0 -118
  183. package/examples/questions-and-tasks.ts +0 -55
  184. package/examples/quickstart.ts +0 -97
  185. package/examples/shared.ts +0 -318
  186. package/examples/strict-public-types.ts +0 -143
  187. package/examples/worktree-lifecycle.ts +0 -79
  188. package/src/README.md +0 -6
  189. package/src/adminClient.ts +0 -789
  190. package/src/answersClient.ts +0 -29
  191. package/src/audiencesClient.ts +0 -209
  192. package/src/auditClient.ts +0 -50
  193. package/src/beliefsClient.ts +0 -319
  194. package/src/client.ts +0 -2647
  195. package/src/contextClient.ts +0 -130
  196. package/src/contextFacade.ts +0 -15
  197. package/src/contextPackCompiler.ts +0 -828
  198. package/src/contextTypes.ts +0 -153
  199. package/src/contracts/api-enums.contract.ts +0 -202
  200. package/src/contracts/auth-session.contract.ts +0 -109
  201. package/src/contracts/context-pack.contract.ts +0 -700
  202. package/src/contracts/contextPack.ts +0 -1
  203. package/src/contracts/index.ts +0 -10
  204. package/src/contracts/lens-filter.contract.ts +0 -183
  205. package/src/contracts/lens-workflow.contract.ts +0 -162
  206. package/src/contracts/lensFilter.ts +0 -1
  207. package/src/contracts/lensWorkflow.ts +0 -1
  208. package/src/contracts/mcp-tools.contract.ts +0 -3636
  209. package/src/contracts/mcpTools.ts +0 -1
  210. package/src/contracts/prompt.contract.ts +0 -50
  211. package/src/contracts/prompt.ts +0 -1
  212. package/src/contracts/sdk-tools.contract.ts +0 -1457
  213. package/src/contracts/sdkTools.ts +0 -1
  214. package/src/contracts/workflow-runtime.contract.ts +0 -440
  215. package/src/contracts/workflowRuntime.ts +0 -1
  216. package/src/coreClient.ts +0 -570
  217. package/src/customTools.ts +0 -398
  218. package/src/decisionsClient.ts +0 -286
  219. package/src/domainContext.ts +0 -15
  220. package/src/events.ts +0 -531
  221. package/src/eventsCore.ts +0 -168
  222. package/src/facade/beliefs.ts +0 -83
  223. package/src/facade/context.ts +0 -110
  224. package/src/facade/contradictions.ts +0 -29
  225. package/src/facade/edges.ts +0 -30
  226. package/src/facade/events.ts +0 -23
  227. package/src/facade/evidence.ts +0 -41
  228. package/src/facade/graph.ts +0 -38
  229. package/src/facade/identity.ts +0 -16
  230. package/src/facade/ontologies.ts +0 -34
  231. package/src/facade/questions.ts +0 -59
  232. package/src/facade/search.ts +0 -16
  233. package/src/facade/tasks.ts +0 -37
  234. package/src/facade/topics.ts +0 -42
  235. package/src/facade/webhooks.ts +0 -58
  236. package/src/facade/worktrees.ts +0 -51
  237. package/src/gatewayFacades.ts +0 -1666
  238. package/src/graphClient.ts +0 -529
  239. package/src/harnessClient.ts +0 -585
  240. package/src/identityClient.ts +0 -278
  241. package/src/index.ts +0 -49
  242. package/src/learningClient.ts +0 -95
  243. package/src/mcpParityClient.ts +0 -240
  244. package/src/ontologyClient.ts +0 -275
  245. package/src/packRuntime.ts +0 -3
  246. package/src/packsClient.ts +0 -260
  247. package/src/policyClient.ts +0 -572
  248. package/src/promptCatalog.ts +0 -1
  249. package/src/realtime/index.ts +0 -51
  250. package/src/reportsClient.ts +0 -99
  251. package/src/schemaClient.ts +0 -129
  252. package/src/sdkSurface.ts +0 -190
  253. package/src/topicsClient.ts +0 -243
  254. package/src/types.ts +0 -807
  255. package/src/version.ts +0 -2
  256. package/src/workflowClient.ts +0 -826
  257. package/tsconfig.json +0 -9
package/src/events.ts DELETED
@@ -1,531 +0,0 @@
1
- export const DOMAIN_EVENT_VERSION = "1.0" as const;
2
- export const EVENT_RETENTION_DEFAULT_DAYS = 30;
3
- export const WEBHOOK_MAX_ATTEMPTS = 5;
4
- export const WEBHOOK_RETRY_DELAYS_MS = [1_000, 5_000, 30_000, 300_000] as const;
5
-
6
- export const DOMAIN_EVENT_TYPES = [
7
- "belief.created",
8
- "belief.forked",
9
- "belief.confidence_updated",
10
- "belief.archived",
11
- "belief.refined",
12
- "belief.contract_created",
13
- "belief.contract_evaluated",
14
- "belief.lineage_queried",
15
- "evidence.created",
16
- "evidence.linked",
17
- "evidence.search_executed",
18
- "question.created",
19
- "question.answered",
20
- "question.refined",
21
- "question.status_updated",
22
- "question.archived",
23
- "edge.created",
24
- "contradiction.flagged",
25
- "worktree.created",
26
- "worktree.activated",
27
- "worktree.merged",
28
- "worktree.targets_updated",
29
- "worktree.metadata_updated",
30
- "topic.created",
31
- "topic.updated",
32
- "topic.archived",
33
- "task.created",
34
- "task.completed",
35
- "task.updated",
36
- "ontology.bound",
37
- "context.compiled",
38
- "identity.key_created",
39
- "identity.key_rotated",
40
- "identity.key_revoked",
41
- "webhook.test",
42
- ] as const;
43
-
44
- export type DomainEventType = (typeof DOMAIN_EVENT_TYPES)[number];
45
-
46
- export type DomainResourceType =
47
- | "belief"
48
- | "evidence"
49
- | "question"
50
- | "edge"
51
- | "contradiction"
52
- | "worktree"
53
- | "topic"
54
- | "task"
55
- | "ontology"
56
- | "context"
57
- | "identity"
58
- | "webhook";
59
-
60
- export type DomainActorType = "human" | "agent" | "service";
61
- export type DomainEventData = Record<string, unknown>;
62
-
63
- export type DomainEvent = {
64
- eventId: string;
65
- type: DomainEventType | string;
66
- version: typeof DOMAIN_EVENT_VERSION;
67
- timestamp: number;
68
- tenantId?: string;
69
- workspaceId?: string;
70
- topicId: string;
71
- resourceId: string;
72
- resourceType: DomainResourceType | string;
73
- actorId: string;
74
- actorType: DomainActorType;
75
- data: DomainEventData;
76
- correlationId?: string;
77
- expiresAt: number;
78
- };
79
-
80
- export type CreateDomainEventInput = {
81
- eventId?: string;
82
- timestamp?: number;
83
- tenantId?: string;
84
- workspaceId?: string;
85
- topicId: string;
86
- type: DomainEventType | string;
87
- resourceId: string;
88
- resourceType: DomainResourceType | string;
89
- actorId: string;
90
- actorType: DomainActorType;
91
- data?: DomainEventData;
92
- correlationId?: string;
93
- retentionDays?: number;
94
- };
95
-
96
- export type EventCursor = {
97
- timestamp: number;
98
- eventId: string;
99
- };
100
-
101
- export type EventListQuery = {
102
- topicId?: string;
103
- after?: string;
104
- types?: string[];
105
- startTime?: number;
106
- endTime?: number;
107
- limit?: number;
108
- };
109
-
110
- export type EventListResult = {
111
- events: DomainEvent[];
112
- nextCursor: string | null;
113
- };
114
-
115
- export type WebhookSecretMode = "configured";
116
-
117
- export type WebhookRecord = {
118
- id: string;
119
- webhookId: string;
120
- tenantId?: string;
121
- workspaceId?: string;
122
- topicId?: string;
123
- url: string;
124
- events: string[];
125
- active: boolean;
126
- secretConfigured: boolean;
127
- createdAt: number;
128
- updatedAt: number;
129
- createdBy: string;
130
- updatedBy: string;
131
- lastDeliveryAt?: number;
132
- lastSuccessfulDeliveryAt?: number;
133
- };
134
-
135
- export type WebhookCreateInput = {
136
- url: string;
137
- events: string[];
138
- secret: string;
139
- topicId?: string;
140
- active?: boolean;
141
- };
142
-
143
- export type WebhookUpdateInput = {
144
- url?: string;
145
- events?: string[];
146
- secret?: string;
147
- topicId?: string | null;
148
- active?: boolean;
149
- };
150
-
151
- export type WebhookDeliveryStatus =
152
- | "pending"
153
- | "delivering"
154
- | "succeeded"
155
- | "failed"
156
- | "dead_letter";
157
-
158
- export type WebhookDeliveryRecord = {
159
- id: string;
160
- deliveryId: string;
161
- webhookId: string;
162
- eventId: string;
163
- eventType: string;
164
- topicId: string;
165
- status: WebhookDeliveryStatus;
166
- attemptCount: number;
167
- maxAttempts: number;
168
- nextAttemptAt?: number;
169
- lastAttemptAt?: number;
170
- lastStatusCode?: number;
171
- lastError?: string;
172
- deliveredAt?: number;
173
- createdAt: number;
174
- updatedAt: number;
175
- };
176
-
177
- export type WebhookDeliveryAttemptRecord = {
178
- id: string;
179
- attemptId: string;
180
- deliveryId: string;
181
- webhookId: string;
182
- eventId: string;
183
- eventType: string;
184
- attemptNumber: number;
185
- status: "succeeded" | "failed";
186
- statusCode?: number;
187
- error?: string;
188
- responseBody?: string;
189
- durationMs?: number;
190
- createdAt: number;
191
- };
192
-
193
- export type WebhookDeliveriesResult = {
194
- deliveries: Array<
195
- WebhookDeliveryRecord & {
196
- attempts?: WebhookDeliveryAttemptRecord[];
197
- }
198
- >;
199
- };
200
-
201
- export type WebhookHealthResult = {
202
- webhookId: string;
203
- totalAttempts: number;
204
- successfulAttempts: number;
205
- failedAttempts: number;
206
- successRate: number;
207
- pendingDeliveries: number;
208
- deadLetterDeliveries: number;
209
- lastDeliveryAt?: number;
210
- lastSuccessfulDeliveryAt?: number;
211
- };
212
-
213
- export type WebhookTestResult = {
214
- webhookId: string;
215
- deliveryId: string;
216
- status: WebhookDeliveryStatus;
217
- attempts: number;
218
- };
219
-
220
- export type ReplayEventsInput = EventListQuery & {
221
- webhookId?: string;
222
- };
223
-
224
- export type ReplayEventsResult = EventListResult & {
225
- replayedDeliveries?: number;
226
- replayedWebhookId?: string;
227
- };
228
-
229
- function escapeRegex(value: string): string {
230
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
231
- }
232
-
233
- export function eventPatternToRegExp(pattern: string): RegExp {
234
- const normalized = pattern.trim();
235
- if (!normalized) {
236
- return /^$/;
237
- }
238
- if (normalized === "*") {
239
- return /^.*$/;
240
- }
241
- const source = escapeRegex(normalized).replace(/\\\*/g, ".*");
242
- return new RegExp(`^${source}$`);
243
- }
244
-
245
- export function matchesEventPattern(
246
- eventType: string,
247
- pattern: string
248
- ): boolean {
249
- return eventPatternToRegExp(pattern).test(eventType.trim());
250
- }
251
-
252
- export function matchesAnyEventPattern(
253
- eventType: string,
254
- patterns: readonly string[]
255
- ): boolean {
256
- if (patterns.length === 0) {
257
- return true;
258
- }
259
- return patterns.some((pattern) => matchesEventPattern(eventType, pattern));
260
- }
261
-
262
- function toBase64(value: string): string {
263
- if (typeof Buffer !== "undefined") {
264
- return Buffer.from(value, "utf8").toString("base64url");
265
- }
266
- return btoa(unescape(encodeURIComponent(value)))
267
- .replace(/\+/g, "-")
268
- .replace(/\//g, "_")
269
- .replace(/=+$/g, "");
270
- }
271
-
272
- function fromBase64(value: string): string {
273
- if (typeof Buffer !== "undefined") {
274
- return Buffer.from(value, "base64url").toString("utf8");
275
- }
276
- const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
277
- return decodeURIComponent(escape(atob(normalized)));
278
- }
279
-
280
- export function createEventId(): string {
281
- const random =
282
- typeof globalThis.crypto?.randomUUID === "function"
283
- ? globalThis.crypto.randomUUID().replace(/-/g, "")
284
- : Array.from(
285
- typeof globalThis.crypto?.getRandomValues === "function"
286
- ? globalThis.crypto.getRandomValues(new Uint8Array(16))
287
- : Array.from({ length: 16 }, () => Math.floor(Math.random() * 256)),
288
- (value) => value.toString(16).padStart(2, "0")
289
- ).join("");
290
- return `evt_${random}`;
291
- }
292
-
293
- export function normalizeRetentionDays(value: number | undefined): number {
294
- if (!Number.isFinite(value) || typeof value !== "number" || value <= 0) {
295
- return EVENT_RETENTION_DEFAULT_DAYS;
296
- }
297
- return Math.max(1, Math.trunc(value));
298
- }
299
-
300
- export function buildDomainEvent(input: CreateDomainEventInput): DomainEvent {
301
- const timestamp = input.timestamp ?? Date.now();
302
- const retentionDays = normalizeRetentionDays(input.retentionDays);
303
- return {
304
- eventId: input.eventId?.trim() || createEventId(),
305
- type: input.type.trim(),
306
- version: DOMAIN_EVENT_VERSION,
307
- timestamp,
308
- tenantId: input.tenantId?.trim() || undefined,
309
- workspaceId: input.workspaceId?.trim() || undefined,
310
- topicId: input.topicId.trim(),
311
- resourceId: input.resourceId.trim(),
312
- resourceType: input.resourceType.trim(),
313
- actorId: input.actorId.trim(),
314
- actorType: input.actorType,
315
- data: input.data ?? {},
316
- correlationId: input.correlationId?.trim() || undefined,
317
- expiresAt: timestamp + retentionDays * 24 * 60 * 60 * 1000,
318
- };
319
- }
320
-
321
- export function compareEventCursor(left: EventCursor, right: EventCursor): number {
322
- if (left.timestamp !== right.timestamp) {
323
- return left.timestamp - right.timestamp;
324
- }
325
- return left.eventId.localeCompare(right.eventId);
326
- }
327
-
328
- export function encodeEventCursor(cursor: EventCursor): string {
329
- return toBase64(JSON.stringify(cursor));
330
- }
331
-
332
- export function decodeEventCursor(cursor: string | undefined): EventCursor | null {
333
- if (!cursor || cursor.trim().length === 0) {
334
- return null;
335
- }
336
- try {
337
- const parsed = JSON.parse(fromBase64(cursor.trim())) as Partial<EventCursor>;
338
- if (
339
- typeof parsed.timestamp !== "number" ||
340
- !Number.isFinite(parsed.timestamp) ||
341
- typeof parsed.eventId !== "string" ||
342
- parsed.eventId.trim().length === 0
343
- ) {
344
- return null;
345
- }
346
- return {
347
- timestamp: parsed.timestamp,
348
- eventId: parsed.eventId.trim(),
349
- };
350
- } catch {
351
- return null;
352
- }
353
- }
354
-
355
- export function isAfterCursor(
356
- event: Pick<DomainEvent, "timestamp" | "eventId">,
357
- cursor: EventCursor | null
358
- ): boolean {
359
- if (!cursor) {
360
- return true;
361
- }
362
- return compareEventCursor(event, cursor) > 0;
363
- }
364
-
365
- export function sortEventsByCursor<T extends Pick<DomainEvent, "timestamp" | "eventId">>(
366
- events: readonly T[]
367
- ): T[] {
368
- return [...events].sort((left, right) => compareEventCursor(left, right));
369
- }
370
-
371
- export function inferActorType(args: {
372
- sessionType?: "agent" | "user";
373
- authMode?: string;
374
- principalType?: string;
375
- }): DomainActorType {
376
- if (args.sessionType === "agent") {
377
- return "agent";
378
- }
379
- if (
380
- args.authMode === "service_principal" ||
381
- args.authMode === "tenant_api_key" ||
382
- args.principalType === "service"
383
- ) {
384
- return "service";
385
- }
386
- return "human";
387
- }
388
-
389
- export async function emitDomainEvent(
390
- invokeMutation: (reference: any, args: CreateDomainEventInput) => Promise<unknown>,
391
- input: CreateDomainEventInput
392
- ): Promise<unknown> {
393
- return await invokeMutation("events:recordEvent" as any, input);
394
- }
395
-
396
- const LOCALHOST_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
397
-
398
- function normalizeUrl(url: string): URL {
399
- try {
400
- return new URL(url.trim());
401
- } catch {
402
- throw new Error("Webhook URL must be a valid absolute URL.");
403
- }
404
- }
405
-
406
- export function assertValidWebhookUrl(url: string): string {
407
- const parsed = normalizeUrl(url);
408
- const hostname = parsed.hostname.trim().toLowerCase();
409
- const nodeEnv =
410
- typeof process !== "undefined" ? process.env?.NODE_ENV : undefined;
411
- const allowLocalHttp =
412
- nodeEnv === "test" || LOCALHOST_HOSTS.has(hostname);
413
-
414
- if (parsed.protocol !== "https:" && !(allowLocalHttp && parsed.protocol === "http:")) {
415
- throw new Error("Webhook URL must use HTTPS.");
416
- }
417
-
418
- return parsed.toString();
419
- }
420
-
421
- export function normalizeWebhookPatterns(patterns: readonly string[]): string[] {
422
- const normalized = Array.from(
423
- new Set(
424
- patterns
425
- .map((pattern) => pattern.trim())
426
- .filter((pattern) => pattern.length > 0)
427
- )
428
- );
429
-
430
- if (normalized.length === 0) {
431
- throw new Error("At least one webhook event pattern is required.");
432
- }
433
-
434
- return normalized;
435
- }
436
-
437
- export function assertValidWebhookSecret(secret: string): string {
438
- const normalized = secret.trim();
439
- if (normalized.length < 8) {
440
- throw new Error("Webhook secret must be at least 8 characters.");
441
- }
442
- return normalized;
443
- }
444
-
445
- export async function computeWebhookSignature(
446
- payload: string,
447
- secret: string
448
- ): Promise<string> {
449
- const encoder = new TextEncoder();
450
- const key = await crypto.subtle.importKey(
451
- "raw",
452
- encoder.encode(secret),
453
- { name: "HMAC", hash: "SHA-256" },
454
- false,
455
- ["sign"]
456
- );
457
- const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
458
- return Array.from(new Uint8Array(signature))
459
- .map((byte) => byte.toString(16).padStart(2, "0"))
460
- .join("");
461
- }
462
-
463
- export function nextDeliveryAttemptAt(
464
- currentAttemptCount: number,
465
- now = Date.now()
466
- ): number | undefined {
467
- if (currentAttemptCount >= WEBHOOK_MAX_ATTEMPTS) {
468
- return undefined;
469
- }
470
- const retryIndex = currentAttemptCount - 1;
471
- const delay = WEBHOOK_RETRY_DELAYS_MS[retryIndex];
472
- return typeof delay === "number" ? now + delay : undefined;
473
- }
474
-
475
- export function resolveDeliveryFailureStatus(
476
- attemptCount: number
477
- ): WebhookDeliveryStatus {
478
- return attemptCount >= WEBHOOK_MAX_ATTEMPTS ? "dead_letter" : "failed";
479
- }
480
-
481
- export function sanitizeWebhookRecord(
482
- value: Record<string, unknown>
483
- ): WebhookRecord {
484
- return {
485
- id: String(value.id ?? value.webhookId ?? value._id ?? ""),
486
- webhookId: String(value.webhookId ?? value.id ?? value._id ?? ""),
487
- tenantId:
488
- typeof value.tenantId === "string" && value.tenantId.trim().length > 0
489
- ? value.tenantId
490
- : undefined,
491
- workspaceId:
492
- typeof value.workspaceId === "string" && value.workspaceId.trim().length > 0
493
- ? value.workspaceId
494
- : undefined,
495
- topicId:
496
- typeof value.topicId === "string" && value.topicId.trim().length > 0
497
- ? value.topicId
498
- : undefined,
499
- url: String(value.url ?? ""),
500
- events: Array.isArray(value.events)
501
- ? value.events
502
- .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
503
- .filter(Boolean)
504
- : [],
505
- active: value.active !== false,
506
- secretConfigured: true,
507
- createdAt: Number(value.createdAt ?? Date.now()),
508
- updatedAt: Number(value.updatedAt ?? value.createdAt ?? Date.now()),
509
- createdBy: String(value.createdBy ?? ""),
510
- updatedBy: String(value.updatedBy ?? value.createdBy ?? ""),
511
- lastDeliveryAt:
512
- typeof value.lastDeliveryAt === "number" ? value.lastDeliveryAt : undefined,
513
- lastSuccessfulDeliveryAt:
514
- typeof value.lastSuccessfulDeliveryAt === "number"
515
- ? value.lastSuccessfulDeliveryAt
516
- : undefined,
517
- };
518
- }
519
-
520
- export function truncateWebhookResponseBody(
521
- responseBody: string | undefined,
522
- maxLength = 2_000
523
- ): string | undefined {
524
- if (!responseBody) {
525
- return undefined;
526
- }
527
- if (responseBody.length <= maxLength) {
528
- return responseBody;
529
- }
530
- return `${responseBody.slice(0, maxLength - 3)}...`;
531
- }
package/src/eventsCore.ts DELETED
@@ -1,168 +0,0 @@
1
- import {
2
- createGatewayRequestClient,
3
- randomIdempotencyKey,
4
- toQueryString,
5
- type GatewayClientConfig,
6
- type PlatformGatewaySuccess,
7
- } from "./coreClient";
8
- import type {
9
- EventListQuery,
10
- EventListResult,
11
- ReplayEventsInput,
12
- ReplayEventsResult,
13
- WebhookCreateInput,
14
- WebhookDeliveriesResult,
15
- WebhookHealthResult,
16
- WebhookRecord,
17
- WebhookTestResult,
18
- WebhookUpdateInput,
19
- } from "./events";
20
- import type { JsonObject } from "./types";
21
-
22
- export type EventsClientCoreConfig = GatewayClientConfig;
23
- export type EventsListResponse = PlatformGatewaySuccess<EventListResult>;
24
- export type EventsReplayResponse = PlatformGatewaySuccess<ReplayEventsResult>;
25
-
26
- export type WebhooksClientCoreConfig = GatewayClientConfig;
27
- export type WebhookListQuery = {
28
- topicId?: string;
29
- };
30
- export type WebhookDeliveriesQuery = {
31
- limit?: number;
32
- };
33
- export type WebhookDeleteResult = {
34
- webhookId: string;
35
- deleted: boolean;
36
- };
37
- export type WebhooksCreateResponse = PlatformGatewaySuccess<WebhookRecord>;
38
- export type WebhooksListResponse = PlatformGatewaySuccess<{ webhooks: WebhookRecord[] }>;
39
- export type WebhooksGetResponse = PlatformGatewaySuccess<WebhookRecord>;
40
- export type WebhooksUpdateResponse = PlatformGatewaySuccess<WebhookRecord>;
41
- export type WebhooksDeleteResponse = PlatformGatewaySuccess<WebhookDeleteResult>;
42
- export type WebhooksTestResponse = PlatformGatewaySuccess<WebhookTestResult>;
43
- export type WebhooksDeliveriesResponse =
44
- PlatformGatewaySuccess<WebhookDeliveriesResult>;
45
- export type WebhooksHealthResponse = PlatformGatewaySuccess<WebhookHealthResult>;
46
-
47
- function serializeTypes(types: string[] | undefined) {
48
- return Array.isArray(types) && types.length > 0 ? types.join(",") : undefined;
49
- }
50
-
51
- export function createEventsClientCore(config: EventsClientCoreConfig = {}) {
52
- const gateway = createGatewayRequestClient(config);
53
-
54
- return {
55
- async list(query: EventListQuery = {}): Promise<EventsListResponse> {
56
- return gateway.request<EventListResult>({
57
- path: `/v1/events${toQueryString({
58
- topicId: query.topicId,
59
- after: query.after,
60
- types: serializeTypes(query.types),
61
- startTime: query.startTime,
62
- endTime: query.endTime,
63
- limit: query.limit,
64
- })}`,
65
- });
66
- },
67
-
68
- async replay(
69
- input: ReplayEventsInput,
70
- idempotencyKey = randomIdempotencyKey()
71
- ): Promise<EventsReplayResponse> {
72
- return gateway.request<ReplayEventsResult>({
73
- path: "/v1/events/replay",
74
- method: "POST",
75
- body: input as JsonObject,
76
- idempotencyKey,
77
- });
78
- },
79
- };
80
- }
81
-
82
- export function createWebhooksClientCore(
83
- config: WebhooksClientCoreConfig = {}
84
- ) {
85
- const gateway = createGatewayRequestClient(config);
86
-
87
- return {
88
- async create(
89
- input: WebhookCreateInput,
90
- idempotencyKey = randomIdempotencyKey()
91
- ): Promise<WebhooksCreateResponse> {
92
- return gateway.request<WebhookRecord>({
93
- path: "/v1/webhooks",
94
- method: "POST",
95
- body: input as JsonObject,
96
- idempotencyKey,
97
- });
98
- },
99
-
100
- async list(query: WebhookListQuery = {}): Promise<WebhooksListResponse> {
101
- return gateway.request<{ webhooks: WebhookRecord[] }>({
102
- path: `/v1/webhooks${toQueryString({
103
- topicId: query.topicId,
104
- })}`,
105
- });
106
- },
107
-
108
- async get(id: string): Promise<WebhooksGetResponse> {
109
- return gateway.request<WebhookRecord>({
110
- path: `/v1/webhooks/${encodeURIComponent(id)}`,
111
- });
112
- },
113
-
114
- async update(
115
- id: string,
116
- input: WebhookUpdateInput,
117
- idempotencyKey = randomIdempotencyKey()
118
- ): Promise<WebhooksUpdateResponse> {
119
- return gateway.request<WebhookRecord>({
120
- path: `/v1/webhooks/${encodeURIComponent(id)}`,
121
- method: "PATCH",
122
- body: input as JsonObject,
123
- idempotencyKey,
124
- });
125
- },
126
-
127
- async delete(
128
- id: string,
129
- idempotencyKey = randomIdempotencyKey()
130
- ): Promise<WebhooksDeleteResponse> {
131
- return gateway.request<WebhookDeleteResult>({
132
- path: `/v1/webhooks/${encodeURIComponent(id)}`,
133
- method: "DELETE",
134
- idempotencyKey,
135
- });
136
- },
137
-
138
- async test(
139
- id: string,
140
- input: { topicId?: string } = {},
141
- idempotencyKey = randomIdempotencyKey()
142
- ): Promise<WebhooksTestResponse> {
143
- return gateway.request<WebhookTestResult>({
144
- path: `/v1/webhooks/${encodeURIComponent(id)}/test`,
145
- method: "POST",
146
- body: input as JsonObject,
147
- idempotencyKey,
148
- });
149
- },
150
-
151
- async deliveries(
152
- id: string,
153
- query: WebhookDeliveriesQuery = {}
154
- ): Promise<WebhooksDeliveriesResponse> {
155
- return gateway.request<WebhookDeliveriesResult>({
156
- path: `/v1/webhooks/${encodeURIComponent(id)}/deliveries${toQueryString({
157
- limit: query.limit,
158
- })}`,
159
- });
160
- },
161
-
162
- async health(id: string): Promise<WebhooksHealthResponse> {
163
- return gateway.request<WebhookHealthResult>({
164
- path: `/v1/webhooks/${encodeURIComponent(id)}/health`,
165
- });
166
- },
167
- };
168
- }