@dbx-tools/shared-genie 0.1.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.
@@ -0,0 +1,554 @@
1
+ /**
2
+ * Wire-format zod schemas + types and high-level event vocabulary
3
+ * for the Genie chat driver.
4
+ *
5
+ * Two related layers live here:
6
+ *
7
+ * 1. Genie wire shapes derived from `@dbx-tools/shared-sdk-model`'s
8
+ * generated `dashboards` schemas (regenerated from the upstream
9
+ * `@databricks/sdk-experimental` `apis/dashboards/model.d.ts`
10
+ * by `dbxtools codegen`). We extend the SDK schemas where Genie
11
+ * ships fields on the wire that the SDK doesn't currently type:
12
+ *
13
+ * - `GenieMessage.auto_regenerate_count: number` (stamped
14
+ * on every wire message, omitted from the SDK shape).
15
+ * - `GenieQueryAttachment.thoughts: GenieThought[]` (the
16
+ * streamed reasoning payload with `DESCRIPTION`,
17
+ * `DATA_SOURCING`, `STEPS`, and `UNDERSTANDING` thought
18
+ * kinds).
19
+ * - `GenieAttachment.attachment_type: AttachmentType`
20
+ * (an optional discriminator literal so callers can
21
+ * `switch (att.attachment_type)` instead of probing
22
+ * which sub-key is populated; compute it with
23
+ * {@link detectAttachmentType}).
24
+ *
25
+ * 2. Event vocabulary for the high-level `genieEventChat`
26
+ * driver. Each event is a flat `z.object` with a `type`
27
+ * literal discriminator and snake_case payload fields hoisted
28
+ * to the top level (no `payload` wrapper). Events that share
29
+ * the attachment-scoped location use
30
+ * {@link GenieChatLocationSchema} as a base; events that
31
+ * don't carry an `attachment_id` (status, result) omit it.
32
+ * {@link GenieChatEventSchema} bundles the variants into one
33
+ * discriminated union.
34
+ *
35
+ * Pure types: no runtime imports beyond zod + the generated
36
+ * sdk-type schemas, no Node-only code, safe for browser bundles.
37
+ */
38
+
39
+ import { string } from "@dbx-tools/shared-core";
40
+ import { dashboards } from "@dbx-tools/shared-sdk-model";
41
+ import { z } from "zod";
42
+
43
+ // The generated SDK schemas live under the `dashboards` namespace of
44
+ // @dbx-tools/shared-sdk-model. Alias the handful Genie extends so the
45
+ // widened schemas below read against short, local names.
46
+ const {
47
+ messageStatusSchema: MessageStatusSchema,
48
+ genieAttachmentSchema: SDKGenieAttachmentSchema,
49
+ genieMessageSchema: SDKGenieMessageSchema,
50
+ genieQueryAttachmentSchema: SDKGenieQueryAttachmentSchema,
51
+ genieSpaceSchema: SDKGenieSpaceSchema,
52
+ } = dashboards;
53
+
54
+ /**
55
+ * The SDK's `MessageStatus` type, re-exported so consumers of the
56
+ * Genie contract get the full wire vocabulary from a single import
57
+ * path - mirrors the re-exports of the other SDK-derived schemas
58
+ * below.
59
+ */
60
+ export type MessageStatus = dashboards.MessageStatus;
61
+
62
+ // Re-export the SDK's `MessageStatus` schema so callers can parse a
63
+ // raw status without reaching back into the generated namespace.
64
+ export { MessageStatusSchema };
65
+
66
+ /* ----------------------------- thoughts ---------------------------- */
67
+
68
+ /**
69
+ * Genie's per-query "thoughts" surface. These appear on the
70
+ * `/messages/{id}` wire under `attachments[i].query.thoughts[]` but
71
+ * are not typed on the SDK's `GenieQueryAttachment` at v0.17.
72
+ *
73
+ * Known thought types observed in production polls:
74
+ *
75
+ * - `THOUGHT_TYPE_DESCRIPTION`: a one-paragraph restatement of
76
+ * what the user asked. The final `query.description` field on
77
+ * the attachment carries the same text.
78
+ * - `THOUGHT_TYPE_DATA_SOURCING`: markdown bullets of the
79
+ * fully-qualified `catalog.schema.table` sources Genie chose.
80
+ * - `THOUGHT_TYPE_STEPS`: the high-level plan Genie wrote before
81
+ * running SQL (one bullet per step).
82
+ * - `THOUGHT_TYPE_UNDERSTANDING`: ambiguity / interpretation
83
+ * notes (e.g. "'revenue' could be interpreted as gross,
84
+ * net, or recognized revenue...").
85
+ *
86
+ * Open at the type level (`| (string & {})`) so a new server-side
87
+ * thought type doesn't break compilation; the four known types
88
+ * still narrow correctly under `switch`.
89
+ */
90
+ export type GenieThoughtType =
91
+ | "THOUGHT_TYPE_DESCRIPTION"
92
+ | "THOUGHT_TYPE_DATA_SOURCING"
93
+ | "THOUGHT_TYPE_STEPS"
94
+ | "THOUGHT_TYPE_UNDERSTANDING"
95
+ | (string & {});
96
+
97
+ /**
98
+ * One reasoning step on a query attachment. See
99
+ * {@link GenieThoughtType} for the known `thought_type` values.
100
+ */
101
+ export const GenieThoughtSchema = z.object({
102
+ thought_type: z.custom<GenieThoughtType>((v) => typeof v === "string"),
103
+ content: z.string(),
104
+ });
105
+ export type GenieThought = z.infer<typeof GenieThoughtSchema>;
106
+
107
+ /* ----------------------- attachment discriminator ---------------------- */
108
+
109
+ /**
110
+ * Discriminator for what's inside a `GenieAttachment`. Genie only
111
+ * ever populates one of `query` / `text` / `suggested_questions`
112
+ * per attachment. Open via `(string & {})` so a new server-side
113
+ * type doesn't break compilation; the three known types still
114
+ * narrow correctly under `switch`.
115
+ *
116
+ * Lifted into the schema as the optional
117
+ * {@link GenieAttachmentSchema}.`attachment_type` field (compute
118
+ * it with {@link detectAttachmentType}) so consumers can branch
119
+ * on a literal instead of probing which sub-object key is
120
+ * present. Also surfaced on {@link AttachmentEvent}'s payload as
121
+ * `attachment_type` (vs a bare `type`) to keep the field clear of
122
+ * the event-union discriminator key.
123
+ */
124
+ export const ATTACHMENT_TYPES = [
125
+ "query",
126
+ "text",
127
+ "suggested_questions",
128
+ ] as const satisfies readonly string[];
129
+ export type KnownAttachmentType = (typeof ATTACHMENT_TYPES)[number];
130
+ export type AttachmentType = KnownAttachmentType | (string & {});
131
+
132
+ /* ------------------- widened wire schemas + types ------------------ */
133
+
134
+ /**
135
+ * `GenieQueryAttachment` widened with the `thoughts[]` field the
136
+ * Genie wire exposes but the SDK doesn't currently type. Every
137
+ * other field (`description`, `query`, `statement_id`,
138
+ * `query_result_metadata`, `title`, `parameters`,
139
+ * `last_updated_timestamp`, `id`) flows through verbatim from
140
+ * the SDK schema.
141
+ */
142
+ export const GenieQueryAttachmentSchema = SDKGenieQueryAttachmentSchema.extend({
143
+ thoughts: z.array(GenieThoughtSchema).optional(),
144
+ });
145
+ export type GenieQueryAttachment = z.infer<typeof GenieQueryAttachmentSchema>;
146
+
147
+ /**
148
+ * `GenieAttachment` with:
149
+ *
150
+ * - `query` re-typed to the thoughts-aware
151
+ * {@link GenieQueryAttachmentSchema}.
152
+ * - `attachment_type` discriminator literal
153
+ * ({@link AttachmentType}) so consumers can `switch
154
+ * (att.attachment_type)` to narrow which sub-object is
155
+ * populated. Optional on the wire (Genie doesn't send it);
156
+ * callers compute it with {@link detectAttachmentType} when
157
+ * they want the literal up-front.
158
+ *
159
+ * `attachment_id`, `text`, and `suggested_questions` pass through
160
+ * unchanged. `attachment_id` is genuinely optional on the wire:
161
+ * the first text attachment Genie emits per turn (the "main
162
+ * answer text") arrives with no id, only the follow-up text
163
+ * attachment gets one.
164
+ */
165
+ export const GenieAttachmentSchema = SDKGenieAttachmentSchema.extend({
166
+ query: GenieQueryAttachmentSchema.optional(),
167
+ attachment_type: z.custom<AttachmentType>((v) => typeof v === "string").optional(),
168
+ });
169
+ export type GenieAttachment = z.infer<typeof GenieAttachmentSchema>;
170
+
171
+ /**
172
+ * `GenieMessage` widened with:
173
+ *
174
+ * - `auto_regenerate_count`: number stamped on every wire
175
+ * message that the SDK type omits at v0.17.
176
+ * - `attachments`: re-typed to the local
177
+ * {@link GenieAttachmentSchema} so
178
+ * `attachment.query?.thoughts` (and the
179
+ * `attachment_type` discriminator) is reachable without a
180
+ * cast.
181
+ *
182
+ * Every other field (`id`, `space_id`, `conversation_id`,
183
+ * `user_id`, `created_timestamp`, `last_updated_timestamp`,
184
+ * `status`, `content`, `message_id`, `query_result`, `error`,
185
+ * `feedback`) passes through from the SDK schema.
186
+ */
187
+ export const GenieMessageSchema = SDKGenieMessageSchema.extend({
188
+ attachments: z.array(GenieAttachmentSchema).optional(),
189
+ auto_regenerate_count: z.number().optional(),
190
+ });
191
+ export type GenieMessage = z.infer<typeof GenieMessageSchema>;
192
+
193
+ /**
194
+ * Domain projection of {@link GenieMessageSchema} that drops every
195
+ * turn-level field (`id`, `status`, `created_timestamp`,
196
+ * `query_result`, ...) and yields just the response payload as a
197
+ * flat `GenieAttachment[]`. Parses the same wire shape as
198
+ * {@link GenieMessageSchema}; missing `attachments` defaults to
199
+ * `[]` so the output is always an array.
200
+ *
201
+ * Use when consumers only care about the model's response
202
+ * attachments and not the surrounding message envelope.
203
+ */
204
+ export const GenieResponseSchema = GenieMessageSchema.transform((m) => m.attachments ?? []);
205
+ export type GenieResponse = z.infer<typeof GenieResponseSchema>;
206
+
207
+ /**
208
+ * `GenieSpace` widened with an optional `serialized_space` field
209
+ * carrying a JSON-string representation of the space's full
210
+ * definition (catalogs, schemas, tables, sample questions, prompts,
211
+ * etc.) as exported by the workspace export endpoint.
212
+ *
213
+ * The base SDK shape (`description`, `space_id`, `title`,
214
+ * `warehouse_id`) covers the directory-listing surface - enough to
215
+ * route a chat. `serialized_space` is opt-in so callers that need
216
+ * the full space schema (e.g. to seed a system prompt or to ship
217
+ * the definition to an agent) can attach it without a second type.
218
+ */
219
+ export const GenieSpaceSchema = SDKGenieSpaceSchema.extend({
220
+ serialized_space: z
221
+ .string()
222
+ .optional()
223
+ .describe(
224
+ "The contents of the Genie Space in serialized string form. This field is excluded in List Genie spaces responses. This field provides the structure of the JSON string that represents the space's layout and components.",
225
+ ),
226
+ });
227
+ export type GenieSpace = z.infer<typeof GenieSpaceSchema>;
228
+
229
+ /* ------------------------ terminal helpers ------------------------- */
230
+
231
+ /**
232
+ * Terminal Genie message statuses. The polling loop in the chat
233
+ * driver stops as soon as the latest message has one of these
234
+ * statuses.
235
+ */
236
+ export const TERMINAL_STATUSES = ["COMPLETED", "FAILED", "CANCELLED"] as const;
237
+ export type TerminalStatus = (typeof TERMINAL_STATUSES)[number];
238
+
239
+ /** Narrow `MessageStatus | undefined` to a {@link TerminalStatus}. */
240
+ export function isTerminalStatus(s: MessageStatus | undefined): s is TerminalStatus {
241
+ return s !== undefined && (TERMINAL_STATUSES as readonly string[]).includes(s);
242
+ }
243
+
244
+ /**
245
+ * Convert a raw Genie wire status (`FETCHING_METADATA`,
246
+ * `ASKING_AI`, `EXECUTING_QUERY`, ...) into a short, sentence-cased
247
+ * label safe to drop into a UI pill. Known states get a curated
248
+ * label; unknown states fall back to `string.tokenizeWithOptions`
249
+ * so new states still render cleanly without code changes.
250
+ *
251
+ * Pure (no Node-only deps), safe for browser bundles. Both the
252
+ * Genie agent (server) and any UI that subscribes to status events
253
+ * call this so labels stay in lock-step across the wire.
254
+ */
255
+ export function humanizeStatus(status: MessageStatus): string {
256
+ switch (status) {
257
+ case "FETCHING_METADATA":
258
+ return "Fetching metadata";
259
+ case "ASKING_AI":
260
+ return "Asking Genie";
261
+ case "EXECUTING_QUERY":
262
+ return "Running SQL query";
263
+ case "FILTERING_CONTEXT":
264
+ return "Filtering context";
265
+ case "PENDING_WAREHOUSE":
266
+ return "Waiting for warehouse";
267
+ case "COMPLETED":
268
+ return "Completed";
269
+ case "FAILED":
270
+ return "Failed";
271
+ case "CANCELLED":
272
+ return "Cancelled";
273
+ default:
274
+ return [...string.tokenizeWithOptions({ capitalize: true, lowerCase: true }, status)].join(
275
+ " ",
276
+ );
277
+ }
278
+ }
279
+
280
+ /* ----------------------- attachment type helper ---------------------- */
281
+
282
+ /**
283
+ * Inspect a {@link GenieAttachment} and return the
284
+ * {@link AttachmentType} of payload it carries. Returns the first
285
+ * known sub-object that's present; if none of the known ones are
286
+ * populated, falls back to the first non-bookkeeping key
287
+ * (forward-compat for types we don't model yet), else `"unknown"`.
288
+ *
289
+ * Honors a pre-set `attachment_type` if one is already on the
290
+ * value, so this is idempotent across re-detections.
291
+ */
292
+ export function detectAttachmentType(att: GenieAttachment): AttachmentType {
293
+ if (att.attachment_type) return att.attachment_type;
294
+ if (att.query) return "query";
295
+ if (att.text) return "text";
296
+ if (att.suggested_questions) return "suggested_questions";
297
+ for (const k of Object.keys(att)) {
298
+ if (k !== "attachment_id" && k !== "attachment_type") return k;
299
+ }
300
+ return "unknown";
301
+ }
302
+
303
+ /* ------------------------- GenieChat events ------------------------ */
304
+
305
+ /**
306
+ * Where on the wire an event was observed. Spread into every
307
+ * attachment-scoped event payload so subscribers can route, log,
308
+ * or correlate without re-walking the message.
309
+ *
310
+ * Fields:
311
+ * - `space_id`: the Genie space the conversation lives in.
312
+ * - `conversation_id`: conversation id once Genie has assigned one.
313
+ * - `message_id`: Genie message id for the active turn.
314
+ * - `attachment_id`: attachment the event came from. Optional
315
+ * because Genie sometimes emits an anonymous main-answer
316
+ * attachment without an id; those still get events, just with
317
+ * `attachment_id` undefined.
318
+ */
319
+ export const GenieChatLocationSchema = z.object({
320
+ space_id: z.string(),
321
+ conversation_id: z.string().optional(),
322
+ message_id: z.string().optional(),
323
+ attachment_id: z.string().optional(),
324
+ });
325
+ export type GenieChatLocation = z.infer<typeof GenieChatLocationSchema>;
326
+
327
+ /**
328
+ * Lifecycle event: the question this turn is asking Genie. Fires
329
+ * once per `genieEventChat` call, the first time the underlying
330
+ * `genieChat` loop yields a `GenieMessage`. Carries the prompt
331
+ * text Genie echoed back on `message.content` and the assigned
332
+ * `message_id` so subscribers can group every subsequent event
333
+ * for this turn under one stable key. `conversation_id` is
334
+ * populated for both opening and follow-up turns (Genie assigns
335
+ * it on `startConversation`).
336
+ *
337
+ * Deferred (instead of fired synchronously on entry) so the
338
+ * `message_id` is available when the event lands - that one round
339
+ * trip costs ~200ms but lets UIs render question / thinking /
340
+ * query / text as a single grouped block per Genie call instead
341
+ * of a flat stream.
342
+ *
343
+ * `attachment_id` is intentionally absent - questions are turn
344
+ * scoped, not attachment scoped.
345
+ */
346
+ export const QuestionEventSchema = GenieChatLocationSchema.omit({
347
+ attachment_id: true,
348
+ }).extend({
349
+ type: z.literal("question"),
350
+ content: z.string(),
351
+ });
352
+ export type QuestionEvent = z.infer<typeof QuestionEventSchema>;
353
+
354
+ /**
355
+ * Lifecycle event: raw `GenieMessage` snapshot for the active
356
+ * turn. Fires once per poll yield. The full message shape
357
+ * (including the widened thought / regen / attachment-type
358
+ * fields) is exposed inline as `message`; consumers narrow on
359
+ * `event.type === "message"` and reach for `event.message`.
360
+ */
361
+ export const MessageEventSchema = GenieChatLocationSchema.omit({
362
+ attachment_id: true,
363
+ }).extend({
364
+ type: z.literal("message"),
365
+ message: GenieMessageSchema,
366
+ });
367
+ export type MessageEvent = z.infer<typeof MessageEventSchema>;
368
+
369
+ /**
370
+ * Top-level `message.status` transitioned. Fires for every
371
+ * distinct status seen on the wire (e.g. `SUBMITTED` ->
372
+ * `FILTERING_CONTEXT` -> `ASKING_AI` -> `PENDING_WAREHOUSE` ->
373
+ * `ASKING_AI` -> `COMPLETED`).
374
+ */
375
+ export const StatusEventSchema = GenieChatLocationSchema.omit({
376
+ attachment_id: true,
377
+ }).extend({
378
+ type: z.literal("status"),
379
+ status: MessageStatusSchema,
380
+ previous_status: MessageStatusSchema.optional(),
381
+ });
382
+ export type StatusEvent = z.infer<typeof StatusEventSchema>;
383
+
384
+ /**
385
+ * A new attachment slot appeared in `message.attachments[]`.
386
+ * Fires exactly once per attachment (matched by `attachment_id`,
387
+ * positionally for anonymous attachments) the first time we see
388
+ * it. The slot's payload kind lands in `attachment_type` so the
389
+ * outer `type` discriminator stays unambiguous.
390
+ */
391
+ export const AttachmentEventSchema = GenieChatLocationSchema.extend({
392
+ type: z.literal("attachment"),
393
+ index: z.number(),
394
+ attachment_type: z.custom<AttachmentType>((v) => typeof v === "string"),
395
+ });
396
+ export type AttachmentEvent = z.infer<typeof AttachmentEventSchema>;
397
+
398
+ /**
399
+ * A new reasoning step appeared on a query attachment
400
+ * (`attachments[i].query.thoughts[i]`). Deduplicated per
401
+ * `(thought_type, content)` tuple within an attachment so
402
+ * subscribers don't see the same thought multiple times - Genie
403
+ * sometimes mutates existing thought slots in place, so the diff
404
+ * is value-based rather than positional.
405
+ */
406
+ export const ThinkingEventSchema = GenieChatLocationSchema.extend({
407
+ type: z.literal("thinking"),
408
+ text: z.string(),
409
+ thought_type: z.custom<GenieThoughtType>((v) => typeof v === "string"),
410
+ });
411
+ export type ThinkingEvent = z.infer<typeof ThinkingEventSchema>;
412
+
413
+ /**
414
+ * A text-attachment `content` field appeared or changed
415
+ * (`attachments[i].text.content`). Fires whenever the snapshot
416
+ * value differs from the previous one for the same attachment.
417
+ */
418
+ export const TextEventSchema = GenieChatLocationSchema.extend({
419
+ type: z.literal("text"),
420
+ text: z.string(),
421
+ });
422
+ export type TextEvent = z.infer<typeof TextEventSchema>;
423
+
424
+ /**
425
+ * SQL was finalized on a query attachment
426
+ * (`attachments[i].query.query`). Fires once when the SQL string
427
+ * transitions from undefined to defined, and again if Genie ever
428
+ * rewrites it. `title` and `description` are denormalised off the
429
+ * attachment's `query.title` / `query.description` so consumers
430
+ * can label the SQL pill without re-walking the message.
431
+ */
432
+ export const QueryEventSchema = GenieChatLocationSchema.extend({
433
+ type: z.literal("query"),
434
+ sql: z.string(),
435
+ title: z.string().optional(),
436
+ description: z.string().optional(),
437
+ });
438
+ export type QueryEvent = z.infer<typeof QueryEventSchema>;
439
+
440
+ /**
441
+ * SQL was submitted to a SQL warehouse and a statement id was
442
+ * assigned (`attachments[i].query.statement_id`). Fires when the
443
+ * statement id transitions from undefined to defined - this is the
444
+ * point at which `client.statementExecution.getStatement({ statement_id })`
445
+ * becomes a valid call.
446
+ */
447
+ export const StatementEventSchema = GenieChatLocationSchema.extend({
448
+ type: z.literal("statement"),
449
+ statement_id: z.string(),
450
+ });
451
+ export type StatementEvent = z.infer<typeof StatementEventSchema>;
452
+
453
+ /**
454
+ * Row count for a query attachment's result changed
455
+ * (`attachments[i].query.query_result_metadata.row_count`). Fires
456
+ * on every change, including the initial `undefined -> 0` and the
457
+ * later `0 -> N` once the warehouse finishes execution.
458
+ */
459
+ export const RowsEventSchema = GenieChatLocationSchema.extend({
460
+ type: z.literal("rows"),
461
+ row_count: z.number(),
462
+ previous_row_count: z.number().optional(),
463
+ statement_id: z.string().optional(),
464
+ });
465
+ export type RowsEvent = z.infer<typeof RowsEventSchema>;
466
+
467
+ /**
468
+ * Genie produced a follow-up suggested-questions list
469
+ * (`attachments[i].suggested_questions.questions[]`). Fires once
470
+ * when the list appears, and again if Genie rewrites it.
471
+ */
472
+ export const SuggestedQuestionsEventSchema = GenieChatLocationSchema.extend({
473
+ type: z.literal("suggested_questions"),
474
+ questions: z.array(z.string()),
475
+ });
476
+ export type SuggestedQuestionsEvent = z.infer<typeof SuggestedQuestionsEventSchema>;
477
+
478
+ /**
479
+ * The active turn reached a terminal status. Always fires once
480
+ * per turn (immediately after the terminal `message` event).
481
+ * Carries the final `GenieMessage` snapshot inline so subscribers
482
+ * don't need to keep their own copy of the last message.
483
+ */
484
+ export const ResultEventSchema = GenieChatLocationSchema.omit({
485
+ attachment_id: true,
486
+ }).extend({
487
+ type: z.literal("result"),
488
+ status: z.enum(TERMINAL_STATUSES),
489
+ message: GenieMessageSchema,
490
+ });
491
+ export type ResultEvent = z.infer<typeof ResultEventSchema>;
492
+
493
+ /**
494
+ * Discriminated union yielded by `genieEventChat`. Each variant
495
+ * is a single flat object with `type` as the discriminator and
496
+ * the payload fields hoisted directly to the top level - no
497
+ * `payload` wrapper. Consumers narrow on `type` and read fields
498
+ * inline:
499
+ *
500
+ * @example
501
+ * for await (const event of genieEventChat(spaceId, "Top stores?")) {
502
+ * switch (event.type) {
503
+ * case "thinking":
504
+ * console.log(event.thought_type, event.text);
505
+ * break;
506
+ * case "result":
507
+ * console.log("done:", event.status);
508
+ * break;
509
+ * }
510
+ * }
511
+ *
512
+ * Stream order per turn:
513
+ *
514
+ * 1. `question`, emitted with the first `message` yield (deferred so
515
+ * the assigned `message_id` is available), carrying the prompt
516
+ * this turn sent to Genie.
517
+ * 2. `message` for every poll yield (raw `GenieMessage` on
518
+ * `event.message`).
519
+ * 3. Any derived events the snapshot diff produced (`status`,
520
+ * `attachment`, `thinking`, `text`, `query`, `statement`,
521
+ * `rows`, `suggested_questions`) in that fixed order.
522
+ * 4. On the terminal snapshot, a final `result` event.
523
+ *
524
+ * Errors propagate via the generator throwing (`try`/`catch` the
525
+ * `for await`), not via an `error` variant on this union.
526
+ */
527
+ export const GenieChatEventSchema = z.discriminatedUnion("type", [
528
+ QuestionEventSchema,
529
+ MessageEventSchema,
530
+ StatusEventSchema,
531
+ AttachmentEventSchema,
532
+ ThinkingEventSchema,
533
+ TextEventSchema,
534
+ QueryEventSchema,
535
+ StatementEventSchema,
536
+ RowsEventSchema,
537
+ SuggestedQuestionsEventSchema,
538
+ ResultEventSchema,
539
+ ]);
540
+ export type GenieChatEvent = z.infer<typeof GenieChatEventSchema>;
541
+
542
+ /** Discriminator type for {@link GenieChatEvent}. */
543
+ export type GenieChatEventType = GenieChatEvent["type"];
544
+
545
+ /**
546
+ * Field set for a given {@link GenieChatEventType} - the variant
547
+ * with the `type` discriminator stripped. Used by detectors in
548
+ * `event.ts` so each detector returns just the payload fields and
549
+ * the orchestrator stamps `type` at yield time.
550
+ */
551
+ export type GenieChatEventFields<T extends GenieChatEventType> = Omit<
552
+ Extract<GenieChatEvent, { type: T }>,
553
+ "type"
554
+ >;