@gravity-rail/sdk 4.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +4 -2
  2. package/dist/account-DLwJWX9b.d.cts +522 -0
  3. package/dist/account-DLwJWX9b.d.ts +522 -0
  4. package/dist/{path-CUY-Iw70.d.ts → agent_standing_job-D60O007y.d.cts} +1068 -140
  5. package/dist/{path-B3b3_El9.d.cts → agent_standing_job-DbKkPDyY.d.ts} +1068 -140
  6. package/dist/{chat-interaction-DXgKjFqZ.d.cts → chat-interaction-CCdK_MtC.d.ts} +13616 -9394
  7. package/dist/{chat-interaction-a7U-tHfQ.d.ts → chat-interaction-rktAADW0.d.cts} +13616 -9394
  8. package/dist/{chunk-D5VNVTUQ.js → chunk-P2MSMMMJ.js} +120 -2
  9. package/dist/chunk-P2MSMMMJ.js.map +1 -0
  10. package/dist/{chunk-ZLF3N3ZD.js → chunk-P2X5TOYY.js} +31 -5
  11. package/dist/chunk-P2X5TOYY.js.map +1 -0
  12. package/dist/{chunk-WHRIIBJ4.js → chunk-VFOWHCQ7.js} +1773 -475
  13. package/dist/chunk-VFOWHCQ7.js.map +1 -0
  14. package/dist/helpers.cjs.map +1 -1
  15. package/dist/helpers.d.cts +3 -2
  16. package/dist/helpers.d.ts +3 -2
  17. package/dist/helpers.js +1 -1
  18. package/dist/index.cjs +1961 -917
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +87 -249
  21. package/dist/index.d.ts +87 -249
  22. package/dist/index.js +171 -458
  23. package/dist/index.js.map +1 -1
  24. package/dist/internal.cjs +1928 -448
  25. package/dist/internal.cjs.map +1 -1
  26. package/dist/internal.d.cts +2449 -263
  27. package/dist/internal.d.ts +2449 -263
  28. package/dist/internal.js +146 -27
  29. package/dist/internal.js.map +1 -1
  30. package/dist/{member-import-BHtOru8g.d.cts → member-import-Bk2nh1YU.d.cts} +1 -1
  31. package/dist/{member-import-VOLKR5dY.d.ts → member-import-CybXt3PK.d.ts} +1 -1
  32. package/dist/realtime.cjs +250 -3
  33. package/dist/realtime.cjs.map +1 -1
  34. package/dist/realtime.d.cts +87 -4
  35. package/dist/realtime.d.ts +87 -4
  36. package/dist/realtime.js +245 -3
  37. package/dist/realtime.js.map +1 -1
  38. package/dist/schemas.cjs +154 -19
  39. package/dist/schemas.cjs.map +1 -1
  40. package/dist/schemas.d.cts +621 -69
  41. package/dist/schemas.d.ts +621 -69
  42. package/dist/schemas.js +72 -21
  43. package/dist/schemas.js.map +1 -1
  44. package/dist/{tasks-CgptqCsN.d.cts → tasks-CGiE1y_T.d.ts} +2243 -1979
  45. package/dist/{tasks-CgptqCsN.d.ts → tasks-DChznvPX.d.cts} +2243 -1979
  46. package/dist/{types-BXaWYGHj.d.cts → types-Bv6GtLZ2.d.cts} +25 -2
  47. package/dist/{types-BXaWYGHj.d.ts → types-Bv6GtLZ2.d.ts} +25 -2
  48. package/package.json +4 -4
  49. package/dist/chunk-D5VNVTUQ.js.map +0 -1
  50. package/dist/chunk-WHRIIBJ4.js.map +0 -1
  51. package/dist/chunk-ZLF3N3ZD.js.map +0 -1
@@ -106,6 +106,116 @@ var AttendeeResponseStatus = /* @__PURE__ */ ((AttendeeResponseStatus2) => {
106
106
  return AttendeeResponseStatus2;
107
107
  })(AttendeeResponseStatus || {});
108
108
 
109
+ // src/types/generated/chat.ts
110
+ var ActivitySubject = {
111
+ abilities: "abilities",
112
+ account_details: "account_details",
113
+ access: "access",
114
+ activity: "activity",
115
+ agents: "agents",
116
+ agent_tasks: "agent_tasks",
117
+ models: "models",
118
+ apps: "apps",
119
+ integrations: "integrations",
120
+ assignments: "assignments",
121
+ billing: "billing",
122
+ bundles: "bundles",
123
+ calendars: "calendars",
124
+ calendar_events: "calendar_events",
125
+ chats: "chats",
126
+ command_help: "command_help",
127
+ commands: "commands",
128
+ forms: "forms",
129
+ documentation: "documentation",
130
+ actions: "actions",
131
+ experiments: "experiments",
132
+ features: "features",
133
+ files: "files",
134
+ folders: "folders",
135
+ inboxes: "inboxes",
136
+ interventions: "interventions",
137
+ roles: "roles",
138
+ members: "members",
139
+ metrics: "metrics",
140
+ notifications: "notifications",
141
+ organizations: "organizations",
142
+ phone_numbers: "phone_numbers",
143
+ personas: "personas",
144
+ prompts: "prompts",
145
+ pronunciations: "pronunciations",
146
+ qualifications: "qualifications",
147
+ queries: "queries",
148
+ recordings: "recordings",
149
+ reports: "reports",
150
+ routines: "routines",
151
+ sites: "sites",
152
+ subscriptions: "subscriptions",
153
+ supervisors: "supervisors",
154
+ support: "support",
155
+ toolkits: "toolkits",
156
+ workflows: "workflows",
157
+ workspaces: "workspaces",
158
+ workspace_settings: "workspace_settings",
159
+ member_records: "member_records",
160
+ labels: "labels",
161
+ tasks: "tasks",
162
+ messages: "messages",
163
+ fields: "fields",
164
+ domains: "domains",
165
+ webhooks: "webhooks",
166
+ api_keys: "api_keys"
167
+ };
168
+ var ActivityVerb = {
169
+ find: "find",
170
+ read: "read",
171
+ analyze: "analyze",
172
+ export: "export",
173
+ create: "create",
174
+ update: "update",
175
+ send: "send",
176
+ start: "start",
177
+ import: "import",
178
+ connect: "connect",
179
+ download: "download",
180
+ delete: "delete",
181
+ revoke: "revoke"
182
+ };
183
+ var ChannelMessagesUnavailableReason = {
184
+ not_single_channel: "not_single_channel",
185
+ no_phone_number: "no_phone_number",
186
+ no_counterpart_phone: "no_counterpart_phone"
187
+ };
188
+ var ChatMuteReason = {
189
+ working: "working",
190
+ waiting_on_person: "waiting_on_person",
191
+ resolved_elsewhere: "resolved_elsewhere",
192
+ not_mine: "not_mine"
193
+ };
194
+
195
+ // src/types/generated/task.ts
196
+ var AbilityConfigIssueCode = {
197
+ missing_resource: "missing_resource",
198
+ invalid_state: "invalid_state",
199
+ feature_disabled: "feature_disabled",
200
+ missing_connection: "missing_connection",
201
+ external_drift: "external_drift",
202
+ no_qualification_scenarios: "no_qualification_scenarios",
203
+ check_truncated: "check_truncated"
204
+ };
205
+ var AbilityConfigIssueSeverity = {
206
+ warning: "warning",
207
+ error: "error"
208
+ };
209
+ var AiDisclosure = {
210
+ when_asked: "when_asked",
211
+ at_opening: "at_opening"
212
+ };
213
+ var ResponseLength = {
214
+ brief: "brief",
215
+ short: "short",
216
+ detailed: "detailed"
217
+ };
218
+
109
219
  export {
110
220
  DataRecordRetirementResponseReason,
111
221
  DataFieldType,
@@ -119,6 +229,14 @@ export {
119
229
  CalendarScheduleAvailabilityType,
120
230
  CalendarEventStatus,
121
231
  AttendeeStatus,
122
- AttendeeResponseStatus
232
+ AttendeeResponseStatus,
233
+ ActivitySubject,
234
+ ActivityVerb,
235
+ ChannelMessagesUnavailableReason,
236
+ ChatMuteReason,
237
+ AbilityConfigIssueCode,
238
+ AbilityConfigIssueSeverity,
239
+ AiDisclosure,
240
+ ResponseLength
123
241
  };
124
- //# sourceMappingURL=chunk-D5VNVTUQ.js.map
242
+ //# sourceMappingURL=chunk-P2MSMMMJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types/generated/data.ts","../src/types/data-types.ts","../src/types/calendar-types.ts","../src/types/generated/chat.ts","../src/types/generated/task.ts"],"sourcesContent":["/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: data\n */\n\nimport type { EventRuleResponse } from './event_rule';\nimport type { EnumOption } from './schema_field';\n\n/**\n * Response for bulk create data records operation.\n */\nexport interface BulkCreateDataRecordResponse {\n importedCount: number;\n totalCount: number;\n success: boolean;\n results: BulkRecordResult[];\n errors?: string[] | null;\n}\n\n/**\n * Result for a single record in a bulk import operation.\n */\nexport interface BulkRecordResult {\n index: number;\n status: BulkRecordResultStatus;\n recordId?: number | null;\n externalId?: string | null;\n error?: string | null;\n}\n\nexport type BulkRecordResultStatus = typeof BulkRecordResultStatus[keyof typeof BulkRecordResultStatus];\n\n\nexport const BulkRecordResultStatus = {\n created: 'created',\n updated: 'updated',\n failed: 'failed',\n} as const;\n\n/**\n * What an ordinary Form edit may change on one connector-owned field.\n *\n * Read-only and value-free: the field's slug, its connector Member field\n * key (``null`` for a field the connector declares in code), the kind of\n * ownership, the properties a customer may edit, and the closed reason\n * name and description are locked when they are. Every property not\n * listed -- slug, key, type, requiredness, computation, validation, adding\n * and removing the field -- changes only through the connection's sync.\n */\nexport interface ConnectorFieldCapabilityResponse {\n slug: string;\n connectorKey?: string | null;\n ownership: ConnectorFieldCapabilityResponseOwnership;\n editableProperties: ConnectorFieldCapabilityResponseEditablePropertiesItem[];\n lockReason?: 'connector_declared_field' | null;\n}\n\nexport type ConnectorFieldCapabilityResponseEditablePropertiesItem = typeof ConnectorFieldCapabilityResponseEditablePropertiesItem[keyof typeof ConnectorFieldCapabilityResponseEditablePropertiesItem];\n\n\nexport const ConnectorFieldCapabilityResponseEditablePropertiesItem = {\n name: 'name',\n description: 'description',\n position: 'position',\n sensitivity: 'sensitivity',\n categories: 'categories',\n} as const;\n\nexport type ConnectorFieldCapabilityResponseOwnership = typeof ConnectorFieldCapabilityResponseOwnership[keyof typeof ConnectorFieldCapabilityResponseOwnership];\n\n\nexport const ConnectorFieldCapabilityResponseOwnership = {\n declared: 'declared',\n retired: 'retired',\n member_field: 'member_field',\n} as const;\n\nexport type DataFieldType = typeof DataFieldType[keyof typeof DataFieldType];\n\n\nexport const DataFieldType = {\n enum: 'enum',\n email: 'email',\n phone: 'phone',\n text: 'text',\n longtext: 'longtext',\n number: 'number',\n integer: 'integer',\n boolean: 'boolean',\n date: 'date',\n datetime: 'datetime',\n time_of_day: 'time_of_day',\n us_zip_code: 'us_zip_code',\n array: 'array',\n object: 'object',\n function: 'function',\n reference: 'reference',\n} as const;\n\nexport interface DataRecordResponse {\n id: number;\n uuid: string;\n dataTypeId: number;\n memberId: number | null;\n memberName?: string | null;\n fieldValues: DataRecordResponseFieldValues;\n createdAt: string;\n updatedAt: string;\n createdByMemberId?: number | null;\n externalId?: string | null;\n accessMode?: number | null;\n retirement?: DataRecordRetirementResponse | null;\n}\n\nexport type DataRecordResponseFieldValues = { [key: string]: unknown };\n\n/**\n * Derived lifecycle-retirement status for a connector-backed record.\n *\n * Populated only on the human Forms/CRUD read responses (list + single GET)\n * so the UI can show an \"Archived in Monday\" / \"Deleted in Monday\" badge.\n * Derived at read time from ``ConnectionEntityExclusion`` + active-link\n * state — there is no stored retirement column on ``DataRecord``.\n *\n * PHI-safe: closed-vocabulary ``status`` / ``reason`` / ``source`` codes\n * only. No field values, no remote item/board IDs, no connection metadata.\n */\nexport interface DataRecordRetirementResponse {\n status?: 'retired';\n reason: DataRecordRetirementResponseReason;\n source?: 'monday';\n}\n\nexport type DataRecordRetirementResponseReason = typeof DataRecordRetirementResponseReason[keyof typeof DataRecordRetirementResponseReason];\n\n\nexport const DataRecordRetirementResponseReason = {\n monday_item_archived: 'monday_item_archived',\n monday_item_deleted: 'monday_item_deleted',\n} as const;\n\nexport interface DataRecordUpdateResponse {\n id: number;\n dataRecordId: number;\n actorMemberId?: number | null;\n recordMemberId?: number | null;\n fieldName: string;\n oldValue: string | null;\n newValue: string | null;\n createdAt: string;\n updatedAt: string;\n assignmentTaskId?: number | null;\n memberName?: string | null;\n source?: string | null;\n}\n\nexport interface DataTypeResponse {\n id: number;\n name: string;\n uuid: string;\n slug: string;\n accessMode?: number | null;\n description: string | null;\n prompt: string | null;\n isCollection: boolean;\n pinned?: boolean | null;\n webhookEventsEnabled?: boolean;\n archived?: boolean;\n ownerId?: number | null;\n recordScope: string;\n adminOnly?: boolean;\n sensitivity: string;\n categories: string[];\n createdAt: string;\n updatedAt: string;\n eventRules: EventRuleResponse[];\n fields: SchemaField[];\n recordCount?: number | null;\n owningConnectionId?: number | null;\n owningConnectionName?: string | null;\n datasetKey?: string | null;\n datasetCardinality?: DataTypeResponseDatasetCardinality;\n connectorFields?: ConnectorFieldCapabilityResponse[] | null;\n}\n\nexport type DataTypeResponseDatasetCardinality = typeof DataTypeResponseDatasetCardinality[keyof typeof DataTypeResponseDatasetCardinality] | null;\n\n\nexport const DataTypeResponseDatasetCardinality = {\n singular: 'singular',\n collection: 'collection',\n} as const;\n\nexport interface IndexStatusResponse {\n fieldId: string;\n fieldName: string;\n shouldIndex: string;\n indexStatus: string;\n message?: string | null;\n}\n\n/**\n * Strongly-typed field definition for DataType schemas.\n */\nexport interface SchemaField {\n /** Unique field identifier */\n slug: string;\n /** Display name for the field */\n name: string;\n /** Optional field description */\n description?: string | null;\n /** Field type (text, email, enum, etc.) */\n fieldType?: typeof SchemaFieldFieldType[keyof typeof SchemaFieldFieldType];\n /** Whether field is required */\n required?: boolean;\n /** Deprecated: Display order is now determined by array position */\n order?: number | null;\n /** Options for enum fields as {label, value} objects. */\n options?: EnumOption[] | null;\n /** Referenced DataType ID for reference fields */\n referencedTypeId?: number | null;\n /** Server-issued reference field identity; preserve on schema round trips */\n referenceFieldId?: number | null;\n /** Server-owned: the connector Member field key this field stores on a connection's bound member profile Form. Never accepted from a customer edit; preserve on schema round trips. */\n connectorKey?: string | null;\n /** Whether to index this field */\n shouldIndex?: boolean;\n /** Whether only admins can see this field */\n adminOnly?: boolean;\n /** Default value for the field */\n defaultValue?: unknown;\n /** CEL expression that computes this field's value. CONSTRAINT: Can ONLY reference regular fields (TEXT, NUMBER, DATE, etc.). Cannot reference other FUNCTION fields. Syntax: record.data.<field_slug>. Example: 'record.data.score1 + record.data.score2' */\n celFunction?: string | null;\n /** CEL expression for cross-field validation. Context: 'value' (current field value), 'record.data.<field_slug>' (other fields). Returns: true if valid, or a string error message if invalid. CONSTRAINT: Can only reference non-FUNCTION fields. Example: 'value >= record.data.min_score' or 'value < record.data.min_score ? \"Must be >= \" + string(record.data.min_score) : true' */\n validateCel?: string | null;\n /** Disclosure severity for audit and access policy */\n sensitivity?: SchemaFieldSensitivity;\n /** Regulatory or content categories for audit and policy */\n categories?: SchemaFieldCategoriesItem[];\n}\n\nexport type SchemaFieldCategoriesItem = typeof SchemaFieldCategoriesItem[keyof typeof SchemaFieldCategoriesItem];\n\n\nexport const SchemaFieldCategoriesItem = {\n personal: 'personal',\n identifier: 'identifier',\n phi: 'phi',\n credential: 'credential',\n} as const;\n\nexport const SchemaFieldFieldType = { enum: 'enum',\n email: 'email',\n phone: 'phone',\n text: 'text',\n longtext: 'longtext',\n number: 'number',\n integer: 'integer',\n boolean: 'boolean',\n date: 'date',\n datetime: 'datetime',\n time_of_day: 'time_of_day',\n us_zip_code: 'us_zip_code',\n array: 'array',\n object: 'object',\n function: 'function',\n reference: 'reference'} as const\n\n/**\n * Disclosure severity for audit and access policy\n */\nexport type SchemaFieldSensitivity = typeof SchemaFieldSensitivity[keyof typeof SchemaFieldSensitivity];\n\n\nexport const SchemaFieldSensitivity = {\n public: 'public',\n internal: 'internal',\n confidential: 'confidential',\n restricted: 'restricted',\n secret: 'secret',\n} as const;\n","// Data-related types.\n// Server response shapes are generated from Pydantic via emit_openapi.py → Orval.\n// Client-only shapes (enums, forms, report items) are defined below.\n\nimport type { SchemaField } from './generated/data';\n\nexport type { DataTypeVersionResponse } from './generated/data_type_version';\n\nexport type { WorkspaceValuesRecordResponse } from './generated/data_type';\n\n// ===== GENERATED SERVER TYPES =====\n\nexport type {\n DataRecordResponse,\n DataRecordResponse as DataRecord,\n DataRecordRetirementResponse,\n DataRecordUpdateResponse,\n DataRecordUpdateResponse as DataRecordUpdate,\n DataTypeResponse,\n DataTypeResponse as DataType,\n IndexStatusResponse,\n SchemaField,\n} from './generated/data';\n\nexport type {\n DataRecordFilterResponse,\n DataRecordFilterResponse as DataRecordFilter,\n CreateDataRecordFilterRequest,\n UpdateDataRecordFilterRequest,\n} from './generated/data_record_filter';\n\nexport { DataRecordRetirementResponseReason } from './generated/data';\n\n// Forms CSV import result (`POST /data-types/{id}/import`). The envelope keeps\n// its established snake_case keys (`Raw`); `outcomes` counts each row once.\nexport type {\n DataRecordImportOutcomes,\n RawDataRecordImportResponse,\n} from './generated/data_record_import';\n\n// Field-slug rename (preview + apply). Value-free by construction: counts, ids,\n// schema slugs and closed-vocabulary blocker codes only.\nexport type {\n FieldReferenceImpact,\n FieldSlugRenamePreview,\n FieldSlugRenameResult,\n} from './generated/data_type_field_rename_service';\n\nimport type { DataRecordFilterResponse as GeneratedDataRecordFilterResponse } from './generated/data_record_filter';\nimport type { QueryPredicate } from './query-engine-types';\n\n/** DataRecordFilter with the query-engine predicate column narrowed to IR. */\nexport type DataRecordFilterWithQuery = GeneratedDataRecordFilterResponse & {\n query?: QueryPredicate | null;\n};\n\nexport interface DataRecordFilterFormData {\n dataTypeId: number;\n name: string;\n description?: string;\n pinned?: boolean;\n /** Query-engine predicate (JSON IR). Pass null to author an empty filter. */\n query: QueryPredicate | null;\n}\n\n// Pagination wrapper for data records (the backend uses an inline shape, not\n// a top-level Pydantic generic, so there is no generated equivalent).\nexport interface DataRecordsPaginatedResponse {\n items: DataRecordResponse[];\n total: number;\n page: number;\n pageSize: number;\n totalPages: number;\n}\n\n// Local import for use in `extends` clauses\nimport type { DataRecordResponse } from './generated/data';\n\n// ===== CLIENT-ONLY SURFACE =====\n// Enums, form shapes, report items, and query helpers that have no direct\n// Pydantic counterpart (or that the frontend builds in a different shape).\n\nimport type { AccountReportItem } from './account-types';\nimport type { EventRuleInput } from './event-types';\nimport type { MemberReportItem } from './member-types';\n\n// Field type enum (kept as TypeScript enum; widely used for comparisons)\nexport enum DataFieldType {\n ENUM = 'enum',\n EMAIL = 'email',\n PHONE = 'phone',\n TEXT = 'text',\n LONGTEXT = 'longtext',\n NUMBER = 'number',\n INTEGER = 'integer',\n DATE = 'date',\n DATETIME = 'datetime',\n TIME_OF_DAY = 'time_of_day',\n BOOLEAN = 'boolean',\n FILE = 'file',\n REFERENCE = 'reference',\n FUNCTION = 'function',\n ARRAY = 'array',\n OBJECT = 'object',\n US_ZIP_CODE = 'us_zip_code',\n}\n\nexport enum IndexStatus {\n NOT_INDEXED = 'not_indexed',\n INDEXING = 'indexing',\n INDEXED = 'indexed',\n ERROR = 'error',\n}\n\nexport enum DataTypeRecordScope {\n WORKSPACE = 'workspace',\n MEMBER = 'member',\n /** Filled in by anonymous visitors; submissions are immutable and never DataRecords. */\n ANONYMOUS = 'anonymous',\n}\n\nexport enum DataSensitivity {\n PUBLIC = 'public',\n INTERNAL = 'internal',\n CONFIDENTIAL = 'confidential',\n RESTRICTED = 'restricted',\n SECRET = 'secret',\n}\n\nexport enum DataCategory {\n PHI = 'phi',\n PII = 'pii',\n FINANCIAL = 'financial',\n OPERATIONAL = 'operational',\n CREDENTIAL = 'credential',\n PERSONAL = 'personal',\n IDENTIFIER = 'identifier',\n}\n\n// DataField — the legacy client-side shape used in forms and the data-type editor.\n// SchemaField (from generated) is the canonical server representation.\nexport interface DataField {\n id?: number;\n name: string;\n slug: string;\n description?: string;\n required: boolean;\n fieldType: DataFieldType;\n options?: EnumOption[];\n referencedTypeId?: number;\n /** Server-issued reference definition identity. */\n referenceFieldId?: number;\n shouldIndex?: boolean;\n indexStatus?: IndexStatus;\n adminOnly?: boolean;\n defaultValue?: any;\n order: number;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Label-value pair for enum field options.\n * Allows enum fields to have user-friendly labels while storing clean values\n * (e.g., numbers for scoring calculations in CEL expressions).\n */\nexport interface EnumOption {\n /** Display label shown to users */\n label: string;\n /** Stored value (can be string or number) */\n value: string | number;\n /**\n * CEL expression that must return true for this option to be visible.\n * Uses record.data.<field_slug> syntax to reference other field values.\n * CONSTRAINT: Can only reference non-FUNCTION fields.\n */\n visibleWhen?: string | null;\n}\n\nexport interface DataTypeFormData {\n name: string;\n slug?: string;\n description?: string;\n prompt?: string;\n isCollection?: boolean;\n recordScope?: DataTypeRecordScope;\n /** Hide this Form and its records from Members without `records:admin`. */\n adminOnly?: boolean;\n sensitivity?: DataSensitivity;\n categories?: DataCategory[];\n // The update/create endpoints accept full SchemaField payloads (including\n // celFunction / validateCel); a narrower \"form data\" type here forced\n // unsafe double-casts at every call site.\n fields?: SchemaField[];\n pinned?: boolean;\n /**\n * Publish this Form's record writes to the organization's webhook endpoints.\n * An egress decision, not a display preference: off by default, and clone and\n * import deliberately reset it (see `DataTypeExport`), so it is always set\n * explicitly by a person. Omitted means \"leave the stored value alone\".\n */\n webhookEventsEnabled?: boolean;\n /** Reassigns the recorded creator. The API refuses `null`. */\n ownerId?: number;\n /**\n * Inline Actions. The same flat list ``DataType.eventRules`` returns, so a\n * form round-trips one shape. (``createRules``/``updateRules`` used to sit\n * here too, marked as the preferred pair — but the API never read them:\n * ``UpdateDataTypeRequest`` accepts ``eventRules`` and nothing else.)\n */\n eventRules?: EventRuleInput[];\n}\n\nexport interface DataRecordFormData {\n dataTypeId: number;\n memberId?: number | null;\n externalId?: string;\n fieldValues: Record<string, unknown>;\n}\n\nexport interface DataRecordAssociationFormData {\n dataRecordId: number;\n accessMode?: number;\n}\n\nexport interface DataRecordWithAccessMode extends DataRecordResponse {\n accessMode?: number | null;\n}\n\nexport interface DataRecordReportItem {\n id: number;\n dataTypeId: number;\n dataTypeSlug: string;\n member?: MemberReportItem;\n account?: AccountReportItem;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface DataIntegrityReportItem {\n dataTypeId: number;\n dataTypeSlug: string;\n dataTypeName: string;\n totalRecords: number;\n invalidRecords: number;\n issues: string[];\n}\n\nexport interface DataTypeExportItem {\n id: number;\n slug: string;\n name: string;\n fields: DataField[];\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface TaskExportDataTypeRelation {\n dataTypeId: number;\n dataTypeSlug: string;\n accessMode: number;\n}\n\nexport interface BulkRecordResult {\n index: number;\n status: 'created' | 'updated' | 'failed';\n recordId?: number;\n error?: string;\n}\n\nexport interface BulkCreateDataRecordResponse {\n importedCount: number;\n totalCount: number;\n success: boolean;\n results: BulkRecordResult[];\n errors?: string[];\n}\n\nexport interface BulkCreateDataRecordRequest {\n dataTypeId: number;\n records: DataRecordFormData[];\n upsert?: boolean;\n}\n","/**\n * Calendar-related types for the Gravity Rail calendar and appointment booking system.\n * Server response shapes are generated from Pydantic via emit_openapi.py → Orval.\n * Client-only shapes (forms, enums, query params) are defined below.\n */\n\n// ===== GENERATED SERVER TYPES =====\n\nexport type {\n AttendeeResponse,\n AttendeeResponse as CalendarEventAttendee,\n AvailabilityResponse,\n AvailableSlotsResponse,\n CalendarResponse as GeneratedCalendarResponse,\n CalendarScheduleResponse as GeneratedCalendarScheduleResponse,\n EventDeletionResponse,\n EventResponse,\n EventResponse as CalendarEvent,\n EventTypeResponse,\n EventTypeResponse as CalendarEventType,\n ExternalAttendeeData,\n GoogleCalendarInfo,\n GoogleCalendarInsufficientScopesResponse,\n GoogleCalendarStatusResponse,\n ICalFeedGrantSummary,\n ICalFeedTokenResponse,\n ICalFeedUrlResponse,\n TimeSlot,\n} from './generated/calendar';\n\nimport type {\n CalendarResponse as GeneratedCalendarResponse,\n CalendarScheduleResponse as GeneratedCalendarScheduleResponse,\n ExternalAttendeeData as GeneratedExternalAttendeeData,\n} from './generated/calendar';\nimport type { EventRuleInput } from './event-types';\n\nexport type Calendar = Omit<GeneratedCalendarResponse, never> & {\n /** Present on detail responses; omitted from some list payloads. */\n eventTypeIds?: number[];\n};\nexport type CalendarResponse = Calendar;\n\nexport type CalendarSchedule = Omit<\n GeneratedCalendarScheduleResponse,\n 'availabilityType' | 'recurrenceType'\n> & {\n availabilityType: CalendarScheduleAvailabilityType | string;\n recurrenceType: CalendarScheduleRecurrence | string;\n};\nexport type CalendarScheduleResponse = CalendarSchedule;\n\n// ===== CLIENT-ONLY TYPES =====\n\nexport enum CalendarPermissionType {\n NONE = 'NONE',\n FREE_BUSY = 'FREE_BUSY',\n READ = 'READ',\n WRITE = 'WRITE',\n ADMIN = 'ADMIN',\n}\n\nexport enum CalendarSource {\n INTERNAL = 'internal',\n GOOGLE = 'google',\n OUTLOOK = 'outlook',\n}\n\nexport interface CalendarFormData {\n name: string;\n slug?: string;\n description?: string | null;\n timezone?: string;\n color?: string | null;\n isPublic?: boolean;\n eventTypeIds?: number[];\n /**\n * Ordered event rules to attach to the calendar in the same request.\n * Server syncs by UUID: same-UUID updates, new UUID creates, omitted\n * UUIDs are deleted. Omit (undefined) to leave existing rules unchanged.\n */\n eventRules?: EventRuleInput[];\n}\n\nexport interface CalendarScheduleFormData {\n name: string;\n description?: string | null;\n availabilityType: CalendarScheduleAvailabilityType;\n recurrenceType: CalendarScheduleRecurrence;\n startTime: string;\n endTime: string;\n recurrenceRule?: Record<string, any> | null;\n recurrenceEndDate?: string | null;\n daysOfWeek?: string[] | null;\n priority?: number;\n eventTypeIds?: number[] | null;\n}\n\nexport enum CalendarScheduleRecurrence {\n ONCE = 'ONCE',\n DAILY = 'DAILY',\n WEEKLY = 'WEEKLY',\n MONTHLY = 'MONTHLY',\n CUSTOM = 'CUSTOM',\n}\n\nexport enum CalendarScheduleAvailabilityType {\n AVAILABLE = 'AVAILABLE',\n UNAVAILABLE = 'UNAVAILABLE',\n}\n\nexport interface CalendarEventTypeFormData {\n name: string;\n slug?: string;\n description?: string | null;\n defaultDurationMinutes: number;\n bufferBeforeMinutes?: number;\n bufferAfterMinutes?: number;\n minAttendees?: number;\n maxAttendees?: number | null;\n color?: string | null;\n active?: boolean;\n /**\n * Ordered event rules scoped to this event type. Server syncs by UUID:\n * same-UUID updates, new UUID creates, omitted UUIDs are deleted.\n */\n eventRules?: EventRuleInput[];\n}\n\nexport interface CalendarEventFormData {\n calendarId: number;\n eventTypeId: number;\n title: string;\n description?: string | null;\n location?: string | null;\n startTime: string;\n attendeeIds: number[];\n externalAttendees?: GeneratedExternalAttendeeData[];\n workflowRevisionId?: number | null;\n workflowId?: number | null;\n taskId?: number | null;\n assignmentId?: number | null;\n}\n\nexport enum CalendarEventStatus {\n TENTATIVE = 'TENTATIVE',\n CONFIRMED = 'CONFIRMED',\n CANCELLED = 'CANCELLED',\n NO_SHOW = 'NO_SHOW',\n COMPLETED = 'COMPLETED',\n}\n\nexport enum AttendeeStatus {\n REQUIRED = 'REQUIRED',\n OPTIONAL = 'OPTIONAL',\n}\n\nexport enum AttendeeResponseStatus {\n PENDING = 'PENDING',\n ACCEPTED = 'ACCEPTED',\n DECLINED = 'DECLINED',\n TENTATIVE = 'TENTATIVE',\n}\n\nexport interface UpdateAttendeeRequest {\n responseStatus: AttendeeResponseStatus;\n note?: string | null;\n}\n\nexport interface AvailabilityCheck {\n eventTypeId: number;\n startTime: string;\n endTime?: string | null;\n}\n\nexport interface AvailableSlotsRequest {\n eventTypeId: number;\n startDate: string;\n endDate: string;\n slotIntervalMinutes?: number;\n}\n\nexport interface CalendarEventsQueryParams {\n calendarId?: number;\n startDate?: string;\n endDate?: string;\n status?: CalendarEventStatus;\n memberId?: number;\n limit?: number;\n offset?: number;\n}\n\nexport interface LinkCalendarRequest {\n googleCalendarId: string;\n}\n\nexport interface LinkCalendarResponse {\n status: string;\n message: string;\n googleCalendarId: string;\n googleCalendarName?: string;\n}\n\nexport interface UnlinkCalendarResponse {\n status: string;\n message: string;\n}\n\nexport interface SyncCalendarResponse {\n status: string;\n message: string;\n created: number;\n updated: number;\n errors: Array<{ event_id: string; error: string }>;\n}\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: chat\n */\n\nimport type { AppContext } from './app_context';\nimport type { AccessGrantDecision, HITLResponse, UIChoiceDecision } from './chat_input';\nimport type { MultimodalCapabilities } from './generated';\n\n/**\n * Display subjects declared by CLI domains; never invocation values.\n */\nexport type ActivitySubject = typeof ActivitySubject[keyof typeof ActivitySubject];\n\n\nexport const ActivitySubject = {\n abilities: 'abilities',\n account_details: 'account_details',\n access: 'access',\n activity: 'activity',\n agents: 'agents',\n agent_tasks: 'agent_tasks',\n models: 'models',\n apps: 'apps',\n integrations: 'integrations',\n assignments: 'assignments',\n billing: 'billing',\n bundles: 'bundles',\n calendars: 'calendars',\n calendar_events: 'calendar_events',\n chats: 'chats',\n command_help: 'command_help',\n commands: 'commands',\n forms: 'forms',\n documentation: 'documentation',\n actions: 'actions',\n experiments: 'experiments',\n features: 'features',\n files: 'files',\n folders: 'folders',\n inboxes: 'inboxes',\n interventions: 'interventions',\n roles: 'roles',\n members: 'members',\n metrics: 'metrics',\n notifications: 'notifications',\n organizations: 'organizations',\n phone_numbers: 'phone_numbers',\n personas: 'personas',\n prompts: 'prompts',\n pronunciations: 'pronunciations',\n qualifications: 'qualifications',\n queries: 'queries',\n recordings: 'recordings',\n reports: 'reports',\n routines: 'routines',\n sites: 'sites',\n subscriptions: 'subscriptions',\n supervisors: 'supervisors',\n support: 'support',\n toolkits: 'toolkits',\n workflows: 'workflows',\n workspaces: 'workspaces',\n workspace_settings: 'workspace_settings',\n member_records: 'member_records',\n labels: 'labels',\n tasks: 'tasks',\n messages: 'messages',\n fields: 'fields',\n domains: 'domains',\n webhooks: 'webhooks',\n api_keys: 'api_keys',\n} as const;\n\n/**\n * What one call does, in one word.\n */\nexport type ActivityVerb = typeof ActivityVerb[keyof typeof ActivityVerb];\n\n\nexport const ActivityVerb = {\n find: 'find',\n read: 'read',\n analyze: 'analyze',\n export: 'export',\n create: 'create',\n update: 'update',\n send: 'send',\n start: 'start',\n import: 'import',\n connect: 'connect',\n download: 'download',\n delete: 'delete',\n revoke: 'revoke',\n} as const;\n\n/**\n * Request model for adding a participant to a chat.\n */\nexport interface AddChatParticipantRequest {\n memberId: number;\n role?: AddChatParticipantRequestRole;\n}\n\nexport type AddChatParticipantRequestRole = typeof AddChatParticipantRequestRole[keyof typeof AddChatParticipantRequestRole];\n\n\nexport const AddChatParticipantRequestRole = {\n user: 'user',\n assistant: 'assistant',\n contributor: 'contributor',\n supervisor: 'supervisor',\n} as const;\n\n/**\n * Chat detail with paginated messages for admin review.\n */\nexport interface AdminChatDetailResponse {\n chat: AdminChatResponse;\n messages: PaginatedResponseOpenAIMessageResponse;\n}\n\n/**\n * Lightweight chat summary for admin listing.\n */\nexport interface AdminChatResponse {\n id: number;\n uuid: string;\n title: string | null;\n summary: string | null;\n channel: string;\n chatType: string;\n paused: boolean;\n archived: boolean;\n needsResponse: boolean;\n isTest: boolean;\n messageCount: number;\n createdAt: string;\n updatedAt: string;\n lastMessageReceivedAt: string | null;\n ownerName: string | null;\n ownerMemberId: number | null;\n participants: ChatParticipantResponse[];\n}\n\n/**\n * A parsed invocation label, not a claim that its effect happened.\n */\nexport interface CallActivityLabel {\n verb: ActivityVerb;\n subject: ActivitySubject;\n}\n\n/**\n * Why a chat yielded no channel messages, as a closed vocabulary.\n *\n * A typed reason rather than a 4xx, because none of these are caller\n * mistakes: they are properties of the chat that the caller could not have\n * known before asking. Any chat page may issue this read, so answering \"this\n * chat has no parallel wire\" with an error would make a perfectly normal\n * web-chat or voice chat surface as a failure — in error logs, in retry\n * counters, and in whatever the client does with a non-2xx.\n *\n * **This is not a claim that the channel set lives only on the server.** The\n * UI keeps its own copy in ``src/components/chat/channel-ghosts/single-channel-chat.ts``\n * and uses it to decide whether to fetch at all, so in practice this branch is\n * reached only when the two sets disagree. That coupling is real and worth\n * stating plainly: adding a channel to :data:`SINGLE_CHANNEL_CHAT_CHANNELS`\n * changes nothing user-visible until the client set is widened too, and\n * removing one here turns a chat the client still queries into an\n * empty-with-reason result rather than an error. Keep the two in sync\n * deliberately; this enum is what makes the mismatch legible instead of\n * silent.\n */\nexport type ChannelMessagesUnavailableReason = typeof ChannelMessagesUnavailableReason[keyof typeof ChannelMessagesUnavailableReason];\n\n\nexport const ChannelMessagesUnavailableReason = {\n not_single_channel: 'not_single_channel',\n no_phone_number: 'no_phone_number',\n no_counterpart_phone: 'no_counterpart_phone',\n} as const;\n\n/**\n * Member-facing receipt of an answered request, without its arguments.\n */\nexport interface ChatApprovalDecision {\n callId: string;\n tool: string;\n answer: ChatApprovalDecisionAnswer;\n}\n\nexport type ChatApprovalDecisionAnswer = typeof ChatApprovalDecisionAnswer[keyof typeof ChatApprovalDecisionAnswer];\n\n\nexport const ChatApprovalDecisionAnswer = {\n approve: 'approve',\n approve_always: 'approve_always',\n reject: 'reject',\n edit: 'edit',\n other: 'other',\n} as const;\n\n/**\n * Response model for chat assignment tasks.\n */\nexport interface ChatAssignmentTaskResponse {\n id: number;\n name: string;\n isCurrent: boolean;\n}\n\n/**\n * Extended chat completion request with app context.\n */\nexport interface ChatCompletionRequest {\n model?: string | null;\n requestId?: string | null;\n messages?: ChatCompletionRequestMessagesItem[];\n context?: AppContext | null;\n resume?: HITLResponse | AccessGrantDecision | UIChoiceDecision | null;\n multimodal?: MultimodalCapabilities | null;\n interactionSessionId?: string | null;\n interactionTurnId?: string | null;\n}\n\nexport type ChatCompletionRequestMessagesItem = { [key: string]: unknown };\n\n/**\n * The single-Chat read (``GET /chats/{chat_id}``, ``/chats/by-uuid/{uuid}``).\n *\n * ``ChatResponse`` plus fields that cost a query per Chat and so stay off the\n * list.\n */\nexport interface ChatDetailResponse {\n id: number;\n uuid: string;\n archived: boolean;\n isStarred?: boolean;\n muted: boolean;\n muteReason?: string | null;\n muteExpiresOnInbound?: boolean;\n mutedByMemberId?: number | null;\n mutedAt?: string | null;\n channel: string;\n transport?: ChatDetailResponseTransport;\n direction?: ChatDetailResponseDirection;\n initiator?: ChatDetailResponseInitiator;\n creationSource?: ChatDetailResponseCreationSource;\n hasRealtimeInteraction?: boolean;\n activeInteractionMode?: ChatDetailResponseActiveInteractionMode;\n chatType: string;\n paused: boolean;\n pausedAt: string | null;\n pausedReason: string | null;\n assignmentId: number | null;\n workflowId: number | null;\n workflowRevisionId?: number | null;\n currentTaskName?: string | null;\n fromMessageId: number | null;\n phoneNumberId: number | null;\n inboxId: number | null;\n siteId: number | null;\n folderId: number | null;\n createdAt: string;\n updatedAt: string;\n title: string | null;\n summary: string | null;\n summaryUpdatedAt: string | null;\n lastMessageReceivedAt: string | null;\n messageCount: number;\n participants: ChatParticipantResponse[];\n canSendAsAssistant: boolean;\n labels: ChatLabelResponse[];\n isTest: boolean;\n interrupt?: ChatInterruptResponse | null;\n initialMessageError?: string | null;\n outboundCallReceipt?: OutboundDialQueued | null;\n sourceCategories: string[];\n}\n\nexport type ChatDetailResponseActiveInteractionMode = typeof ChatDetailResponseActiveInteractionMode[keyof typeof ChatDetailResponseActiveInteractionMode] | null;\n\n\nexport const ChatDetailResponseActiveInteractionMode = {\n text: 'text',\n push_to_talk: 'push_to_talk',\n realtime: 'realtime',\n} as const;\n\nexport type ChatDetailResponseCreationSource = typeof ChatDetailResponseCreationSource[keyof typeof ChatDetailResponseCreationSource] | null;\n\n\nexport const ChatDetailResponseCreationSource = {\n web_arrival: 'web_arrival',\n inbound_channel: 'inbound_channel',\n outbound_action: 'outbound_action',\n operator_create: 'operator_create',\n background_run: 'background_run',\n qualification_run: 'qualification_run',\n} as const;\n\nexport type ChatDetailResponseDirection = typeof ChatDetailResponseDirection[keyof typeof ChatDetailResponseDirection];\n\n\nexport const ChatDetailResponseDirection = {\n inbound: 'inbound',\n outbound: 'outbound',\n unknown: 'unknown',\n} as const;\n\nexport type ChatDetailResponseInitiator = typeof ChatDetailResponseInitiator[keyof typeof ChatDetailResponseInitiator];\n\n\nexport const ChatDetailResponseInitiator = {\n member: 'member',\n workspace: 'workspace',\n system: 'system',\n unknown: 'unknown',\n} as const;\n\nexport type ChatDetailResponseTransport = typeof ChatDetailResponseTransport[keyof typeof ChatDetailResponseTransport];\n\n\nexport const ChatDetailResponseTransport = {\n web: 'web',\n pstn: 'pstn',\n sms: 'sms',\n whatsapp: 'whatsapp',\n email: 'email',\n fax: 'fax',\n slack: 'slack',\n teams: 'teams',\n discord: 'discord',\n direct_message: 'direct_message',\n a2a: 'a2a',\n routine: 'routine',\n background: 'background',\n cli: 'cli',\n frame: 'frame',\n unknown: 'unknown',\n} as const;\n\n/**\n * Response model for a chat filter.\n */\nexport interface ChatFilterResponse {\n id: number;\n uuid: string;\n name: string;\n description: string | null;\n pinned?: boolean | null;\n createdAt: string;\n updatedAt: string;\n rules: ChatFilterRuleResponse[];\n query?: ChatFilterResponseQuery;\n}\n\nexport type ChatFilterResponseQuery = { [key: string]: unknown } | null;\n\n/**\n * Response model for a chat filter rule.\n */\nexport interface ChatFilterRuleResponse {\n id: number;\n uuid: string;\n chatFilterId: number;\n objectType: string;\n filterType: string;\n objectIds?: number[] | null;\n query?: string | null;\n}\n\n/**\n * Pending HITL interrupt on a chat.\n *\n * Canonical API shape (camelCase) for ``GET /chats/:id`` and AG-UI\n * ``human_input_request`` events. Built from LangGraph ``interrupt()``\n * payloads via ``build_chat_interrupt_response``. Resume via\n * ``POST …/inference/hitl`` echoing ``interruptId`` (request body).\n */\nexport interface ChatInterruptResponse {\n type?: string | null;\n interruptId?: string | null;\n openuiMarkup?: string | null;\n description?: string | null;\n userPrompt?: string | null;\n guided?: ChatInterruptResponseGuided;\n specId?: number | null;\n specTitle?: string | null;\n specData?: ChatInterruptResponseSpecData;\n specStatus?: string | null;\n checkoutUrl?: string | null;\n productName?: string | null;\n price?: string | null;\n paymentComplete?: boolean | null;\n [key: string]: unknown;\n }\n\nexport type ChatInterruptResponseGuided = typeof ChatInterruptResponseGuided[keyof typeof ChatInterruptResponseGuided] | null;\n\n\nexport const ChatInterruptResponseGuided = {\n beat: 'beat',\n question: 'question',\n} as const;\n\nexport type ChatInterruptResponseSpecData = { [key: string]: unknown } | null;\n\n/**\n * Response model for chat label endpoints.\n */\nexport interface ChatLabelResponse {\n id: number;\n uuid: string;\n name: string;\n slug: string;\n color: string;\n description: string | null;\n}\n\n/**\n * Per-chat model provenance for override UI (assignment + legacy chats).\n *\n * Effective models mirror runtime (``get_agent_config``). Upstream is the\n * reset/inherit target: pinned workflow revision for assignment chats, else\n * resolved agent/revision defaults. ``*MatchesUpstream`` is true only when\n * both model id and nested config match — so voice/settings-only forks count.\n */\nexport interface ChatModelOverrideResponse {\n chatModel?: string | null;\n chatModelConfig?: ChatModelOverrideResponseChatModelConfig;\n realtimeModel?: string | null;\n realtimeModelConfig?: ChatModelOverrideResponseRealtimeModelConfig;\n upstreamChatModel?: string | null;\n upstreamChatModelConfig?: ChatModelOverrideResponseUpstreamChatModelConfig;\n upstreamRealtimeModel?: string | null;\n upstreamRealtimeModelConfig?: ChatModelOverrideResponseUpstreamRealtimeModelConfig;\n chatModelMatchesUpstream?: boolean;\n realtimeModelMatchesUpstream?: boolean;\n}\n\nexport type ChatModelOverrideResponseChatModelConfig = { [key: string]: unknown } | null;\n\nexport type ChatModelOverrideResponseRealtimeModelConfig = { [key: string]: unknown } | null;\n\nexport type ChatModelOverrideResponseUpstreamChatModelConfig = { [key: string]: unknown } | null;\n\nexport type ChatModelOverrideResponseUpstreamRealtimeModelConfig = { [key: string]: unknown } | null;\n\n/**\n * Reason recorded when a caller mutes a Chat.\n *\n * ``working`` means work is in progress; ``waiting_on_person`` means another\n * person or a later time is needed; ``resolved_elsewhere`` means no action is\n * due in this Chat; and ``not_mine`` means the Chat is outside the operator's\n * responsibility.\n */\nexport type ChatMuteReason = typeof ChatMuteReason[keyof typeof ChatMuteReason];\n\n\nexport const ChatMuteReason = {\n working: 'working',\n waiting_on_person: 'waiting_on_person',\n resolved_elsewhere: 'resolved_elsewhere',\n not_mine: 'not_mine',\n} as const;\n\n/**\n * Response model for chat mute update.\n *\n * Carries the decision the mute recorded (GRA-8353): the reason from the\n * closed vocabulary, whether it lapses on the member's next inbound, and\n * who muted when — so the UI can show \"muted by X for Y\" instead of a bare\n * boolean. ``muted`` stays the raw stored flag; lapse is a read-time\n * surfacing concern, not a write-time one.\n */\nexport interface ChatMuteUpdateResponse {\n id: number;\n muted: boolean;\n muteReason?: string | null;\n muteExpiresOnInbound?: boolean;\n mutedByMemberId?: number | null;\n mutedAt?: string | null;\n}\n\n/**\n * Response model for adding a participant to a chat.\n */\nexport interface ChatParticipantAddedResponse {\n success: boolean;\n message: string;\n participantId: number;\n}\n\n/**\n * Request model for chat participants.\n *\n * All participants are members (agents are members with member_type='agent').\n */\nexport interface ChatParticipantRequest {\n memberId?: number | null;\n additionalInstructions?: string | null;\n role: ChatParticipantRequestRole;\n}\n\nexport type ChatParticipantRequestRole = typeof ChatParticipantRequestRole[keyof typeof ChatParticipantRequestRole];\n\n\nexport const ChatParticipantRequestRole = {\n user: 'user',\n assistant: 'assistant',\n contributor: 'contributor',\n supervisor: 'supervisor',\n} as const;\n\nexport interface ChatParticipantResponse {\n name: string;\n avatarUrl?: string | null;\n avatarIcon?: ChatParticipantResponseAvatarIcon;\n avatarColor?: ChatParticipantResponseAvatarColor;\n additionalInstructions?: string | null;\n role: string;\n memberId?: number | null;\n orgAgentUuid?: string | null;\n orgAgentConfigRevision?: number | null;\n memberType?: string | null;\n chatModel?: string | null;\n realtimeModel?: string | null;\n chatModelConfig?: ChatParticipantResponseChatModelConfig;\n realtimeModelConfig?: ChatParticipantResponseRealtimeModelConfig;\n}\n\nexport type ChatParticipantResponseAvatarColor = typeof ChatParticipantResponseAvatarColor[keyof typeof ChatParticipantResponseAvatarColor] | null;\n\n\nexport const ChatParticipantResponseAvatarColor = {\n teal: 'teal',\n sky: 'sky',\n blue: 'blue',\n indigo: 'indigo',\n violet: 'violet',\n fuchsia: 'fuchsia',\n slate: 'slate',\n} as const;\n\nexport type ChatParticipantResponseAvatarIcon = typeof ChatParticipantResponseAvatarIcon[keyof typeof ChatParticipantResponseAvatarIcon] | null;\n\n\nexport const ChatParticipantResponseAvatarIcon = {\n user: 'user',\n stethoscope: 'stethoscope',\n heart: 'heart',\n shield: 'shield',\n sparkles: 'sparkles',\n star: 'star',\n} as const;\n\nexport type ChatParticipantResponseChatModelConfig = { [key: string]: unknown } | null;\n\nexport type ChatParticipantResponseRealtimeModelConfig = { [key: string]: unknown } | null;\n\n/**\n * Response model for chat endpoints.\n */\nexport interface ChatResponse {\n id: number;\n uuid: string;\n archived: boolean;\n isStarred?: boolean;\n muted: boolean;\n muteReason?: string | null;\n muteExpiresOnInbound?: boolean;\n mutedByMemberId?: number | null;\n mutedAt?: string | null;\n channel: string;\n transport?: ChatResponseTransport;\n direction?: ChatResponseDirection;\n initiator?: ChatResponseInitiator;\n creationSource?: ChatResponseCreationSource;\n hasRealtimeInteraction?: boolean;\n activeInteractionMode?: ChatResponseActiveInteractionMode;\n chatType: string;\n paused: boolean;\n pausedAt: string | null;\n pausedReason: string | null;\n assignmentId: number | null;\n workflowId: number | null;\n workflowRevisionId?: number | null;\n currentTaskName?: string | null;\n fromMessageId: number | null;\n phoneNumberId: number | null;\n inboxId: number | null;\n siteId: number | null;\n folderId: number | null;\n createdAt: string;\n updatedAt: string;\n title: string | null;\n summary: string | null;\n summaryUpdatedAt: string | null;\n lastMessageReceivedAt: string | null;\n messageCount: number;\n participants: ChatParticipantResponse[];\n canSendAsAssistant: boolean;\n labels: ChatLabelResponse[];\n isTest: boolean;\n interrupt?: ChatInterruptResponse | null;\n initialMessageError?: string | null;\n outboundCallReceipt?: OutboundDialQueued | null;\n}\n\nexport type ChatResponseActiveInteractionMode = typeof ChatResponseActiveInteractionMode[keyof typeof ChatResponseActiveInteractionMode] | null;\n\n\nexport const ChatResponseActiveInteractionMode = {\n text: 'text',\n push_to_talk: 'push_to_talk',\n realtime: 'realtime',\n} as const;\n\nexport type ChatResponseCreationSource = typeof ChatResponseCreationSource[keyof typeof ChatResponseCreationSource] | null;\n\n\nexport const ChatResponseCreationSource = {\n web_arrival: 'web_arrival',\n inbound_channel: 'inbound_channel',\n outbound_action: 'outbound_action',\n operator_create: 'operator_create',\n background_run: 'background_run',\n qualification_run: 'qualification_run',\n} as const;\n\nexport type ChatResponseDirection = typeof ChatResponseDirection[keyof typeof ChatResponseDirection];\n\n\nexport const ChatResponseDirection = {\n inbound: 'inbound',\n outbound: 'outbound',\n unknown: 'unknown',\n} as const;\n\nexport type ChatResponseInitiator = typeof ChatResponseInitiator[keyof typeof ChatResponseInitiator];\n\n\nexport const ChatResponseInitiator = {\n member: 'member',\n workspace: 'workspace',\n system: 'system',\n unknown: 'unknown',\n} as const;\n\nexport type ChatResponseTransport = typeof ChatResponseTransport[keyof typeof ChatResponseTransport];\n\n\nexport const ChatResponseTransport = {\n web: 'web',\n pstn: 'pstn',\n sms: 'sms',\n whatsapp: 'whatsapp',\n email: 'email',\n fax: 'fax',\n slack: 'slack',\n teams: 'teams',\n discord: 'discord',\n direct_message: 'direct_message',\n a2a: 'a2a',\n routine: 'routine',\n background: 'background',\n cli: 'cli',\n frame: 'frame',\n unknown: 'unknown',\n} as const;\n\n/**\n * Aggregated token usage for a chat.\n */\nexport interface ChatTokenUsageResponse {\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n cachedTokens?: number;\n audioInputTokens?: number;\n audioOutputTokens?: number;\n credits?: number;\n creditsRemaining?: number | null;\n extraUsageEnabled?: boolean | null;\n usageByModel?: ModelUsageResponse[];\n sttUsage?: VoiceUsageResponse[];\n ttsUsage?: VoiceUsageResponse[];\n voiceDurationSeconds?: number | null;\n creditsPerHour?: number | null;\n}\n\n/**\n * Create a new chat.\n */\nexport interface CreateChatRequest {\n channel: CreateChatRequestChannel;\n /** Deprecated browser surface alias; use interactionMode. */\n browserChannel?: CreateChatRequestBrowserChannel;\n /** How a browser Chat opens; does not change its stored channel. */\n interactionMode?: CreateChatRequestInteractionMode;\n chatType?: CreateChatRequestChatType;\n workflowId?: number | null;\n workflowUuid?: string | null;\n workflowRevisionId?: number | null;\n workflowRevisionUuid?: string | null;\n title?: string | null;\n phoneNumberId?: number | null;\n inboxId?: number | null;\n siteId?: number | null;\n memberId?: number | null;\n participants?: ChatParticipantRequest[];\n assistantKind?: CreateChatRequestAssistantKind;\n assistantEnabled?: boolean;\n assistantMemberId?: number | null;\n assistantOrgAgentUuid?: string | null;\n /** Which side the organization Agent in `assistantOrgAgentUuid` is on: `caller` when the Agent starts the Chat (it is recorded as the instigator), `receiver` when a person starts it and the Agent answers. Required with `assistantOrgAgentUuid`, and only with it. */\n assistantOrgAgentRole?: CreateChatRequestAssistantOrgAgentRole;\n assistantName?: string | null;\n assistantChatModelId?: string | null;\n assistantChatModelConfig?: CreateChatRequestAssistantChatModelConfig;\n assistantRealtimeModelId?: string | null;\n assistantRealtimeModelConfig?: CreateChatRequestAssistantRealtimeModelConfig;\n isTest?: boolean;\n initialMessage?: string | null;\n}\n\nexport type CreateChatRequestAssistantChatModelConfig = { [key: string]: unknown } | null;\n\nexport type CreateChatRequestAssistantKind = typeof CreateChatRequestAssistantKind[keyof typeof CreateChatRequestAssistantKind] | null;\n\n\nexport const CreateChatRequestAssistantKind = {\n ai: 'ai',\n human: 'human',\n} as const;\n\n/**\n * Which side the organization Agent in `assistantOrgAgentUuid` is on: `caller` when the Agent starts the Chat (it is recorded as the instigator), `receiver` when a person starts it and the Agent answers. Required with `assistantOrgAgentUuid`, and only with it.\n */\nexport type CreateChatRequestAssistantOrgAgentRole = typeof CreateChatRequestAssistantOrgAgentRole[keyof typeof CreateChatRequestAssistantOrgAgentRole] | null;\n\n\nexport const CreateChatRequestAssistantOrgAgentRole = {\n caller: 'caller',\n receiver: 'receiver',\n} as const;\n\nexport type CreateChatRequestAssistantRealtimeModelConfig = { [key: string]: unknown } | null;\n\n/**\n * Deprecated browser surface alias; use interactionMode.\n */\nexport type CreateChatRequestBrowserChannel = typeof CreateChatRequestBrowserChannel[keyof typeof CreateChatRequestBrowserChannel] | null;\n\n\nexport const CreateChatRequestBrowserChannel = {\n 'web-chat': 'web-chat',\n 'web-voice': 'web-voice',\n} as const;\n\nexport type CreateChatRequestChannel = typeof CreateChatRequestChannel[keyof typeof CreateChatRequestChannel];\n\n\nexport const CreateChatRequestChannel = {\n cli: 'cli',\n frame: 'frame',\n 'phone-sms': 'phone-sms',\n 'phone-voice': 'phone-voice',\n fax: 'fax',\n 'phone-whatsapp': 'phone-whatsapp',\n email: 'email',\n background: 'background',\n 'web-chat': 'web-chat',\n 'web-voice': 'web-voice',\n discord: 'discord',\n slack: 'slack',\n teams: 'teams',\n 'direct-message': 'direct-message',\n a2a: 'a2a',\n routine: 'routine',\n} as const;\n\nexport type CreateChatRequestChatType = typeof CreateChatRequestChatType[keyof typeof CreateChatRequestChatType];\n\n\nexport const CreateChatRequestChatType = {\n assignment: 'assignment',\n manager: 'manager',\n contributor: 'contributor',\n dm: 'dm',\n} as const;\n\n/**\n * How a browser Chat opens; does not change its stored channel.\n */\nexport type CreateChatRequestInteractionMode = typeof CreateChatRequestInteractionMode[keyof typeof CreateChatRequestInteractionMode] | null;\n\n\nexport const CreateChatRequestInteractionMode = {\n text: 'text',\n push_to_talk: 'push_to_talk',\n realtime: 'realtime',\n} as const;\n\n/**\n * Create-chat preflight: is an SMS conversation already live with this member?\n *\n * An SMS conversation with a member is a single stream — inbound SMS routes to\n * ONE current chat per (member phone, workspace phone) pair\n * (``get_current_chat_for_phone_and_target_member``) — so creating a new SMS\n * chat supersedes the existing one: from the next inbound message onwards the\n * old chat goes quiet. This endpoint lets the create-chat UI warn about that\n * before the operator commits.\n *\n * **PHI-safe by construction.** Status and timing only: no message content, no\n * phone numbers, no member names, and deliberately no chat title (titles are\n * auto-summarised from message content, so they ARE PHI).\n *\n * ``exists is False`` leaves every other field ``None`` — the caller should\n * branch on ``exists``, not on a null id.\n */\nexport interface CurrentSmsChatResponse {\n exists: boolean;\n chatId?: number | null;\n chatUuid?: string | null;\n chatType?: string | null;\n workflowName?: string | null;\n lastActivityAt?: string | null;\n needsResponse?: boolean | null;\n paused?: boolean | null;\n aiAnswering?: boolean | null;\n}\n\n/**\n * Request model for deleting a chat with audit reason.\n */\nexport interface DeleteChatRequest {\n /** Optional reason for deletion (logged for audit) */\n reason?: string | null;\n}\n\n/**\n * Per-message escalation signal scores (evals keystone A2).\n *\n * The stored payload is ``EscalationSignalAssessment.to_payload()``; its\n * snake_case keys are accepted on the way in and serialize camelCase. PHI:\n * scores concern a Member or advice given to them, so they travel only beside\n * the ``content`` they describe (see ``Message.escalation_signals``).\n */\nexport interface EscalationSignalsResponse {\n status: string;\n signalSet: string;\n engine?: string | null;\n scores?: EscalationSignalsResponseScores;\n raised?: string[];\n latencyMs?: number | null;\n}\n\nexport type EscalationSignalsResponseScores = {[key: string]: number};\n\n/**\n * Request model for finding or creating a DM chat.\n */\nexport interface FindOrCreateDMChatRequest {\n memberId: number;\n}\n\n/**\n * Request model for generating chat summaries in bulk.\n */\nexport interface GenerateChatSummariesRequest {\n after_date?: string | null;\n only_without_summaries?: boolean;\n}\n\n/**\n * Selectable built-in Manager AI skill metadata.\n */\nexport interface ManagerSkillSummary {\n name: string;\n title: string;\n description: string;\n}\n\n/**\n * Skill catalogue for pre-Chat Manager composers (and Routine manager tasks).\n */\nexport interface ManagerSkillsResponse {\n items: ManagerSkillSummary[];\n}\n\n/**\n * One captured aspect of a Chat at a Message, without its source text.\n */\nexport interface MessageFeatureResponse {\n decision: MessageFeatureResponseDecision;\n value: MessageFeatureResponseValue;\n status: MessageFeatureResponseStatus;\n engine: string | null;\n questionSet: string;\n latencyMs: number;\n}\n\nexport type MessageFeatureResponseDecision = typeof MessageFeatureResponseDecision[keyof typeof MessageFeatureResponseDecision];\n\n\nexport const MessageFeatureResponseDecision = {\n greeting: 'greeting',\n answer: 'answer',\n} as const;\n\nexport type MessageFeatureResponseStatus = typeof MessageFeatureResponseStatus[keyof typeof MessageFeatureResponseStatus];\n\n\nexport const MessageFeatureResponseStatus = {\n decided: 'decided',\n unavailable: 'unavailable',\n} as const;\n\nexport type MessageFeatureResponseValue = typeof MessageFeatureResponseValue[keyof typeof MessageFeatureResponseValue] | null;\n\n\nexport const MessageFeatureResponseValue = {\n human: 'human',\n voicemail: 'voicemail',\n call_screening: 'call_screening',\n unknown: 'unknown',\n answerable: 'answerable',\n not_found: 'not_found',\n} as const;\n\n/**\n * Protected metadata describing the Chat at this Message.\n */\nexport interface MessageFeatures {\n greeting?: MessageFeatureResponse | null;\n retrievedAnswer?: MessageFeatureResponse | null;\n}\n\n/**\n * Token usage for a single message.\n */\nexport interface MessageTokenUsageResponse {\n model: string;\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n cachedTokens?: number;\n credits?: number;\n}\n\n/**\n * Token and credit usage for a specific model.\n */\nexport interface ModelUsageResponse {\n model: string;\n promptTokens?: number;\n completionTokens?: number;\n totalTokens: number;\n cachedTokens?: number;\n /** Combined credit usage for this model across LLM and image operations. Token fields count LLM tokens only; billing reports separate image credits. */\n credits: number;\n multiplier: number;\n inputMultiplier?: number;\n outputMultiplier?: number;\n cachedMultiplier?: number;\n audioInputTokens?: number;\n audioOutputTokens?: number;\n}\n\n/**\n * Response model for OpenAI function tool calls.\n */\nexport interface OpenAIFunctionToolCall {\n id?: string;\n type?: string;\n function?: OpenAIFunctionToolCallFunction;\n /** Derive display metadata from the mapped invocation when serialized. */\n readonly activity: CallActivityLabel | null;\n}\n\nexport type OpenAIFunctionToolCallFunction = { [key: string]: unknown };\n\n/**\n * Response model for chat messages in OpenAI format.\n *\n * **Telling a human-sent assistant message from an AI one.** ``role`` no\n * longer answers this: the ``\"operator\"`` value was retired because a human\n * answering IS the assistant, and because an automated consent auto-reply\n * wrote that value too (see\n * ``https://github.com/Gravity-Rail/gravity-team/blob/c22ffd57b17e281f04bc07c7d901ee640cec555b/docs/projects/active/operator-role-collapse.md``). The answer comes from\n * the sender, exactly as it does for participants:\n *\n * const sender = chat.participants.find(\n * (p) => p.role === 'assistant' && p.memberId === message.memberId\n * );\n * const sentByHuman = !!sender && sender.memberType !== 'agent';\n *\n * ``memberId`` is the message's owning member; a human take-over owns their\n * reply through their own ``role=\"assistant\"`` participant, so the lookup\n * hits a participant whose ``memberType`` is not ``\"agent\"``. The AI's turns\n * resolve either to the agent participant (``memberType === 'agent'``) or, on\n * a revision-backed chat whose assistant participant is a member-less\n * persona, to no assistant participant at all — both mean \"AI\", which is why\n * the default above is AI rather than human.\n */\nexport interface OpenAIMessageResponse {\n id?: string | null;\n uuid?: string | null;\n role?: string | null;\n content?: OpenAIMessageResponseContent;\n originalContent?: OpenAIMessageResponseOriginalContent;\n truncationReason?: string | null;\n truncatedAtMs?: number | null;\n sttMetadata?: SttMetadataResponse | null;\n escalationSignals?: EscalationSignalsResponse | null;\n messageFeatures?: MessageFeatures | null;\n approvalDecision?: ChatApprovalDecision | null;\n tool_calls?: OpenAIFunctionToolCall[];\n tool_call_id?: string | null;\n suggestions?: string[] | null;\n created_at?: string | null;\n email_id?: number | null;\n inbox_id?: number | null;\n tokenUsage?: MessageTokenUsageResponse | null;\n memberId?: number | null;\n origin?: string | null;\n audience?: string | null;\n toolStatus?: string | null;\n sourceCategories?: string[] | null;\n isCanned?: boolean;\n parentMessageId?: string | null;\n taskId?: number | null;\n interactionSessionId?: string | null;\n interactionMode?: OpenAIMessageResponseInteractionMode;\n interactionTurnId?: string | null;\n audioFileUuid?: string | null;\n audioMetadata?: OpenAIMessageResponseAudioMetadata;\n smsDeliveryStatus?: string | null;\n smsDeliveryErrorCode?: string | null;\n smsDeliveryUpdatedAt?: string | null;\n smsDeliveryFailureReason?: string | null;\n userRating?: number | null;\n userRatingComment?: string | null;\n}\n\nexport type OpenAIMessageResponseAudioMetadata = { [key: string]: unknown } | null;\n\nexport type OpenAIMessageResponseContent = string | { [key: string]: unknown }[] | null;\n\nexport type OpenAIMessageResponseInteractionMode = typeof OpenAIMessageResponseInteractionMode[keyof typeof OpenAIMessageResponseInteractionMode] | null;\n\n\nexport const OpenAIMessageResponseInteractionMode = {\n text: 'text',\n push_to_talk: 'push_to_talk',\n realtime: 'realtime',\n} as const;\n\nexport type OpenAIMessageResponseOriginalContent = string | { [key: string]: unknown }[] | null;\n\n/**\n * Request model for initiating outbound calls.\n */\nexport interface OutboundCallRequest {\n phoneNumberId: number;\n chatId: number;\n}\n\n/**\n * The call was accepted as a durable intent; nothing was dialled here.\n *\n * P10's queued receipt: admission (``OutboundCallWorkflow``) places the call\n * later, so there is no ``call_sid`` and none is ever fabricated. Queued is\n * acceptance, not ringing. ``intentState`` is the intent's attempt state\n * when this receipt was read; ``notAfter`` is the intent's deadline (ISO\n * 8601), after which admission gives up and closes it\n * ``admission_timed_out`` without dialling. ``newlyQueued`` is False when\n * the key named an intent an earlier submission accepted: a replay reports\n * that intent's own state and deadline, never a fresh acceptance or a\n * renewed deadline. Identifiers, a closed state and a timestamp only. The\n * keys are camelCase: the union is an API response shape (the operator dial\n * route returns it).\n */\nexport interface OutboundDialQueued {\n status: 'queued';\n intentUuid: string;\n chatId: number;\n intentState: string;\n notAfter: string;\n newlyQueued: boolean;\n}\n\nexport interface PaginatedResponseOpenAIMessageResponse {\n items: OpenAIMessageResponse[];\n total: number;\n page: number;\n pageSize: number;\n totalPages: number;\n}\n\n/**\n * Request model for rating a chat message.\n */\nexport interface RateMessageRequest {\n rating: number;\n comment?: string | null;\n}\n\n/**\n * Callbacks for one chat.\n */\nexport interface ScheduledCallbackListResponse {\n callbacks: ScheduledCallbackResponse[];\n}\n\n/**\n * One scheduled follow-up on a chat.\n */\nexport interface ScheduledCallbackResponse {\n id: number;\n uuid: string;\n chatId: number;\n memberId: number;\n targetChannel?: string | null;\n reason?: string | null;\n scheduledTime: string;\n status: string;\n statusDetail?: string | null;\n createdChatId?: number | null;\n createdAt: string;\n completedAt?: string | null;\n}\n\n/**\n * Request model for sending a message as the assistant.\n */\nexport interface SendAssistantMessageRequest {\n message: string;\n tool_calls?: SendAssistantMessageRequestToolCalls;\n}\n\nexport type SendAssistantMessageRequestToolCalls = { [key: string]: unknown }[] | null;\n\n/**\n * Request model for sending a user message in a chat.\n */\nexport interface SendUserMessageRequest {\n content: string;\n}\n\n/**\n * Response model for the agent's loaded skills state.\n *\n * Sent as a state.SkillsResponse custom event to sync loaded skills to the client.\n *\n * Attributes:\n * loadedSkills: Skills that are currently loaded (prompts injected into context)\n * revealedSkills: Skills that are visible but not yet loaded\n * enabledToolkitTools: Toolkit tool URIs/names selected for this Manager chat\n */\nexport interface SkillsResponse {\n loadedSkills?: string[];\n revealedSkills?: string[];\n enabledToolkitTools?: string[];\n}\n\n/**\n * Per-turn STT confidence for a voice user turn (#21973).\n *\n * ``extra=\"allow\"`` so a producer that adds a field does not break\n * existing clients before the SDK catches up; ``protected_namespaces``\n * is cleared because the provider key really is called ``model``.\n */\nexport interface SttMetadataResponse {\n model?: string | null;\n eotConfidence?: number | null;\n min?: number | null;\n mean?: number | null;\n words?: SttWordConfidenceResponse[];\n [key: string]: unknown;\n }\n\n/**\n * One transcribed word and how sure the recognizer was about it.\n *\n * Compact keys mirror the stored JSONB (see\n * ``lib.voice.stt_confidence.to_stt_metadata``) — they are per-word on\n * every voice turn, so the shortening is deliberate. ``s``/``e`` are\n * absent on self-hosted Flux, which returns no word timings at all.\n */\nexport interface SttWordConfidenceResponse {\n w: string;\n c: number;\n s?: number | null;\n e?: number | null;\n [key: string]: unknown;\n }\n\n/**\n * Response model for a single todo item.\n */\nexport interface TodoItemResponse {\n id: string;\n content: string;\n status: string;\n notes?: string | null;\n}\n\n/**\n * Response model for the agent's todo list state.\n *\n * Sent as a state.TodosResponse custom event to sync todos to the client.\n */\nexport interface TodosResponse {\n todos?: TodoItemResponse[];\n}\n\n/**\n * Update an existing chat's per-chat model snapshot from the Chat sidebar.\n *\n * Public API is camelCase. Every field is optional: only fields explicitly\n * present in the request (tracked via ``model_fields_set``) are touched, so a\n * caller can give an old chat voice by sending ``realtimeModelId`` alone.\n *\n * Per-model semantics (applied by ``apply_chat_model_override``):\n * - a concrete, non-empty id → *pin* that model (and its paired config) on the\n * chat's snapshot;\n * - an empty string / null id → *reset* that model to the agent's current\n * default (re-snapshot from the live agent/workflow config). Snapshot\n * semantics stay pure — there is no read-time fallback (PR #19699), so\n * \"inherit\" is implemented as an explicit re-snapshot at write time.\n */\nexport interface UpdateChatModelOverrideRequest {\n chatModelId?: string | null;\n chatModelConfig?: UpdateChatModelOverrideRequestChatModelConfig;\n realtimeModelId?: string | null;\n realtimeModelConfig?: UpdateChatModelOverrideRequestRealtimeModelConfig;\n}\n\nexport type UpdateChatModelOverrideRequestChatModelConfig = { [key: string]: unknown } | null;\n\nexport type UpdateChatModelOverrideRequestRealtimeModelConfig = { [key: string]: unknown } | null;\n\n/**\n * Request model for updating chat mute status.\n *\n * Muting REQUIRES a reason (GRA-8353): an anonymous mute is exactly the\n * shape that made ``needs_response`` unmaintainable, so the closed\n * vocabulary is not optional. ``muteExpiresOnInbound`` defaults to True —\n * the conditional \"until the member replies again\" mute is the default\n * offered, because a permanent mute is how a conversation gets silently\n * lost. Unmuting ignores both fields; the service clears them.\n */\nexport interface UpdateChatMuteRequest {\n muted: boolean;\n muteReason?: ChatMuteReason | null;\n muteExpiresOnInbound?: boolean;\n}\n\n/**\n * Update a chat.\n */\nexport interface UpdateChatRequest {\n title?: string | null;\n assignmentId?: number | null;\n phoneNumberId?: number | null;\n inboxId?: number | null;\n paused?: boolean | null;\n labelIds?: number[] | null;\n}\n\n/**\n * STT or TTS usage for a specific model.\n */\nexport interface VoiceUsageResponse {\n model: string;\n credits: number;\n multiplier: number;\n durationSeconds?: number | null;\n characterCount?: number | null;\n}\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: task\n */\n\nimport type { AbilityData, AbilityResponse } from './ability';\nimport type { ChatTaskConfigurationPatch } from './chat_task_configuration';\nimport type { ConfigHealthIssue } from './config_health';\nimport type { DataRecordResponse } from './data';\nimport type { EventRuleData, EventRuleResponse } from './event_rule';\nimport type { FileResponse } from './file';\nimport type { PageResponse } from './site';\nimport type { TaskAssociationRequest } from './workspace';\n\n/**\n * A non-blocking diagnostic about an ability's configuration.\n *\n * Emitted by :meth:`AbilityBase.collect_config_issues` and aggregated\n * by the workflow-level config validation route. Config issues describe\n * drift in the ability's own references (e.g. a file that was deleted\n * after the ability was saved).\n */\nexport interface AbilityConfigIssue {\n severity: AbilityConfigIssueSeverity;\n code: AbilityConfigIssueCode;\n abilityType: string;\n taskId?: number | null;\n resourceType?: string | null;\n resourceId?: number | string | null;\n resourceName?: string | null;\n objectType?: string | null;\n eventType?: string | null;\n message: string;\n}\n\nexport type AbilityConfigIssueCode = typeof AbilityConfigIssueCode[keyof typeof AbilityConfigIssueCode];\n\n\nexport const AbilityConfigIssueCode = {\n missing_resource: 'missing_resource',\n invalid_state: 'invalid_state',\n feature_disabled: 'feature_disabled',\n missing_connection: 'missing_connection',\n external_drift: 'external_drift',\n no_qualification_scenarios: 'no_qualification_scenarios',\n check_truncated: 'check_truncated',\n} as const;\n\nexport type AbilityConfigIssueSeverity = typeof AbilityConfigIssueSeverity[keyof typeof AbilityConfigIssueSeverity];\n\n\nexport const AbilityConfigIssueSeverity = {\n warning: 'warning',\n error: 'error',\n} as const;\n\n/**\n * When the Agent tells the person it is an AI.\n */\nexport type AiDisclosure = typeof AiDisclosure[keyof typeof AiDisclosure];\n\n\nexport const AiDisclosure = {\n when_asked: 'when_asked',\n at_opening: 'at_opening',\n} as const;\n\nexport interface AssignmentResponse {\n id: number;\n uuid: string;\n taskId?: number | null;\n taskName?: string | null;\n memberId: number;\n createdAt: string;\n updatedAt: string;\n status?: string;\n outcome?: string | null;\n outcomeReason?: string | null;\n concludedAt?: string | null;\n rootTask?: AssignmentTaskResponse | null;\n currentTask?: AssignmentTaskResponse | null;\n isTest: boolean;\n dataRecords?: DataRecordResponse[];\n files: FileResponse[];\n pages?: PageResponse[];\n workflowId: number;\n workflowName?: string | null;\n workflowUuid?: string | null;\n workflowRevisionId?: number | null;\n workflowRevisionUuid?: string | null;\n workflowRevisionNumber?: number | null;\n workflowRevisionName?: string | null;\n}\n\n/**\n * Response model for assignment task endpoints.\n */\nexport interface AssignmentTaskResponse {\n id: number;\n uuid: string;\n required: boolean;\n autoNext: boolean;\n taskId: number;\n workflowId: number;\n taskName: string;\n taskUuid: string;\n visitedAt: string | null;\n children?: AssignmentTaskResponse[];\n}\n\n/**\n * Response model for child task endpoints.\n *\n * ``id`` is the **TaskAssociation row id** — the edge's own identity, which\n * Workflow Health warnings address and the editor deep-links to. It is\n * ``None`` for an edge of an installed Workflow: the edge lives on the pinned\n * resource revision and this workspace has no association row for it, so\n * there is no id to report. Reporting the child Task's id instead would look\n * like an association id and silently never match.\n *\n * ``edgeId`` is the edge's id in whatever graph the Workflow runs on: the\n * association row id for a workspace Workflow, the pinned revision's edge id\n * for an installed one. It is the id in the connection's path tool name\n * (``take_path_<edgeId>``), so a client can name the Task a stored path call\n * led to. It is configuration, not Member data.\n */\nexport interface ChildTaskResponse {\n id: number | null;\n edgeId?: number | null;\n taskId: number;\n taskName: string;\n taskUuid: string;\n choicePrompt: string | null;\n celCondition: string | null;\n routing?: OutcomeTaskRouting | MatchTaskRouting | ConditionTaskRouting | OtherwiseTaskRouting | null;\n order: number;\n autoNext: boolean;\n required: boolean;\n /**\n * Authored Path language over the compatible transport fields.\n *\n * This full-content response already carries the expression and prompt.\n * Computing the view prevents a stale client-supplied projection from\n * overriding those fields. It is not a live availability judgment.\n */\n readonly pathDefinition: PathDefinition;\n}\n\n/**\n * Request body for cloning a task.\n */\nexport interface CloneTaskRequest {\n name: string;\n slug?: string | null;\n}\n\nexport interface ConditionTaskRouting {\n kind?: 'condition';\n /** @pattern ^[a-z][a-z0-9_]{0,31}$ */\n key: string;\n}\n\n/**\n * Create a new task.\n */\nexport interface CreateTaskRequest {\n name: string;\n taskType?: string | null;\n configuration?: CreateTaskRequestConfiguration;\n description?: string | null;\n prompt?: string | null;\n isAdmin?: boolean;\n childTasks?: TaskAssociationRequest[] | null;\n insertBetween?: InsertTaskBetweenRequest | null;\n celGuard?: string | null;\n workflowId?: number | null;\n workflowRevisionId?: number | null;\n posX?: number | null;\n posY?: number | null;\n abilities?: AbilityData[] | null;\n eventRules?: EventRuleData[] | null;\n}\n\nexport type CreateTaskRequestConfiguration = { [key: string]: unknown } | null;\n\n/**\n * Response from executing a tool in the context of an assignment.\n */\nexport interface ExecuteToolResponse {\n toolName: string;\n result: string;\n success?: boolean;\n chatId?: number | null;\n}\n\n/**\n * One authored opening line.\n *\n * ``channel`` is either :data:`DEFAULT_CHANNEL_KEY` or a canonical\n * ``Channel``; ``locale`` is a supported locale tag. Both are validated at\n * the request boundary (``validate_initial_message_entries``) rather than\n * here, so a malformed value is a 422 naming the field instead of a generic\n * model error — and so an import or direct DB write cannot smuggle a bad\n * vocabulary token past the API.\n *\n * ``allowInterrupt`` is per entry, not per direction: the rows are already\n * channel-keyed, and barge-in means anything only on a voice channel, so a\n * ``phone-voice`` disclosure can be must-hear-in-full while the ``default``\n * text stays interruptible. ``None`` (the default) is \"unset\" — an absent\n * key behaves exactly like ``True`` — so only an explicit opt-out changes\n * anything. It is independent of turn ownership (``wait_for_response``);\n * deriving one from the other is the regression #30201 records.\n */\nexport interface GreetingEntry {\n /** Canonical Channel, or 'default' for any channel. */\n channel?: string;\n /** Supported locale tag, e.g. 'en-US'. */\n locale: string;\n /** What the assistant opens with. */\n text: string;\n /** When false, a voice channel cannot barge over this greeting — use for required disclosures. Absent means true (interruptible). Ignored on channels without canned speech. */\n allowInterrupt?: boolean | null;\n}\n\n/**\n * Split an existing connection in the same draft, in one transaction.\n */\nexport interface InsertTaskBetweenRequest {\n parentTaskId: number;\n childTaskId: number;\n routing?: OutcomeTaskRouting | MatchTaskRouting | ConditionTaskRouting | OtherwiseTaskRouting | null;\n}\n\n/**\n * One attached folder or file.\n *\n * ``canList`` and ``canSearch`` mean something only for a folder; a file\n * entry refuses them rather than dropping them in silence.\n */\nexport interface KnowledgeEntry {\n kind: KnowledgeEntryKind;\n uuid: string;\n canRead?: boolean;\n canList?: boolean;\n canSearch?: boolean;\n hint?: string | null;\n}\n\nexport type KnowledgeEntryKind = typeof KnowledgeEntryKind[keyof typeof KnowledgeEntryKind];\n\n\nexport const KnowledgeEntryKind = {\n folder: 'folder',\n file: 'file',\n} as const;\n\nexport interface MatchTaskRouting {\n kind?: 'match';\n value: string | number | boolean | null;\n}\n\n/**\n * Child task info for the operator assignment view.\n */\nexport interface OperatorChildTaskDetail {\n assignmentTaskId: number;\n taskId: number;\n taskName: string;\n taskUuid: string;\n taskType: string;\n choicePrompt?: string | null;\n celCondition?: string | null;\n autoNext?: boolean;\n required?: boolean;\n order?: number;\n visitedAt?: string | null;\n}\n\n/**\n * Rich task detail for operator assignment view.\n *\n * Includes prompt, abilities, and child task details with CEL conditions\n * so the operator can see what the AI would see and navigate workflow steps.\n */\nexport interface OperatorTaskDetailResponse {\n assignmentId: number;\n assignmentTaskId: number;\n taskId: number;\n taskName: string;\n taskType: string;\n prompt?: string | null;\n renderedPrompt?: string | null;\n description?: string | null;\n configuration?: OperatorTaskDetailResponseConfiguration;\n celGuard?: string | null;\n abilities?: AbilityResponse[];\n inheritedAbilities?: AbilityResponse[];\n childTasks?: OperatorChildTaskDetail[];\n parentAssignmentTaskId?: number | null;\n parentTaskName?: string | null;\n}\n\nexport type OperatorTaskDetailResponseConfiguration = { [key: string]: unknown } | null;\n\nexport const OtherwiseTaskRoutingValue = {\n kind: 'otherwise',\n} as const;\nexport type OtherwiseTaskRouting = typeof OtherwiseTaskRoutingValue;\n\nexport interface OutcomeTaskRouting {\n kind?: 'outcome';\n /** @pattern ^[a-z][a-z0-9_]{0,31}$ */\n outcome: string;\n}\n\n/**\n * The path-specific permission to take a Path, separate from Task readiness.\n */\nexport interface PathAvailabilityCondition {\n kind: PathAvailabilityConditionKind;\n expression: string | null;\n /** @nullable */\n decisionPrompt: null;\n}\n\nexport type PathAvailabilityConditionKind = typeof PathAvailabilityConditionKind[keyof typeof PathAvailabilityConditionKind];\n\n\nexport const PathAvailabilityConditionKind = {\n always: 'always',\n cel: 'cel',\n} as const;\n\n/**\n * An authored Path definition, not a live availability judgment.\n */\nexport interface PathDefinition {\n availability: PathAvailabilityCondition;\n selection: PathSelection;\n}\n\n/**\n * Who selects a Path, why, and how competing matches are resolved.\n */\nexport interface PathSelection {\n mode: PathSelectionMode;\n rule: PathSelectionRule;\n choicePrompt: string | null;\n /** @nullable */\n condition: null;\n outcome: string | null;\n routing?: OutcomeTaskRouting | MatchTaskRouting | ConditionTaskRouting | OtherwiseTaskRouting | null;\n policy: PathSelectionPolicy;\n priority: number | null;\n}\n\nexport type PathSelectionMode = typeof PathSelectionMode[keyof typeof PathSelectionMode];\n\n\nexport const PathSelectionMode = {\n choice: 'choice',\n automatic: 'automatic',\n} as const;\n\nexport type PathSelectionPolicy = typeof PathSelectionPolicy[keyof typeof PathSelectionPolicy];\n\n\nexport const PathSelectionPolicy = {\n choose_one: 'choose_one',\n first_match: 'first_match',\n matching_outcome: 'matching_outcome',\n} as const;\n\nexport type PathSelectionRule = typeof PathSelectionRule[keyof typeof PathSelectionRule];\n\n\nexport const PathSelectionRule = {\n choice: 'choice',\n when_available: 'when_available',\n task_outcome: 'task_outcome',\n} as const;\n\n/**\n * How much the Agent says per turn.\n */\nexport type ResponseLength = typeof ResponseLength[keyof typeof ResponseLength];\n\n\nexport const ResponseLength = {\n brief: 'brief',\n short: 'short',\n detailed: 'detailed',\n} as const;\n\n/**\n * Response model for task assignment statistics.\n */\nexport interface TaskAssignmentStatsResponse {\n current: number;\n total: number;\n parentTotal?: number | null;\n}\n\n/**\n * Identity fields needed to select a Task; no Task configuration.\n */\nexport interface TaskCatalogResponse {\n id: number;\n name: string;\n workflowId: number | null;\n workflowRevisionId: number | null;\n}\n\n/**\n * Response model for a chat on a specific task.\n */\nexport interface TaskChatResponse {\n chatId: number;\n chatUuid: string;\n title?: string | null;\n summary?: string | null;\n assignmentId: number;\n memberName: string;\n memberId: number;\n currentTaskName: string;\n workflowName: string;\n lastMessageAt?: string | null;\n messageCount?: number;\n}\n\n/**\n * Response model for paginated list of task chats.\n */\nexport interface TaskChatsListResponse {\n items: TaskChatResponse[];\n total: number;\n limit: number;\n offset: number;\n}\n\n/**\n * Response model for task endpoints.\n */\nexport interface TaskResponse {\n id: number;\n name: string;\n uuid: string;\n lineageUuid?: string | null;\n taskType: string;\n configuration?: TaskResponseConfiguration;\n workflowId?: number | null;\n workflowRevisionId?: number | null;\n description: string | null;\n prompt: string | null;\n ownerId?: number | null;\n createdAt: string;\n updatedAt: string;\n archived: boolean;\n isAdmin: boolean;\n enterRules: EventRuleResponse[];\n leaveRules: EventRuleResponse[];\n childTasks?: ChildTaskResponse[];\n permissions?: number;\n celGuard?: string | null;\n posX?: number | null;\n posY?: number | null;\n abilities?: AbilityResponse[];\n inheritedAbilities?: AbilityResponse[];\n eventRules?: EventRuleResponse[];\n}\n\nexport type TaskResponseConfiguration = { [key: string]: unknown } | null;\n\n/**\n * Update a task.\n */\nexport interface UpdateTaskRequest {\n name?: string | null;\n taskType?: string | null;\n configuration?: UpdateTaskRequestConfiguration;\n configurationPatch?: ChatTaskConfigurationPatch | null;\n workflowId?: number | null;\n workflowRevisionId?: number | null;\n description?: string | null;\n prompt?: string | null;\n isAdmin?: boolean | null;\n childTasks?: TaskAssociationRequest[] | null;\n ownerId?: number | null;\n celGuard?: string | null;\n posX?: number | null;\n posY?: number | null;\n abilities?: AbilityData[] | null;\n eventRules?: EventRuleData[] | null;\n archived?: boolean | null;\n}\n\nexport type UpdateTaskRequestConfiguration = { [key: string]: unknown } | null;\n\n/**\n * Revision-owned Agent behavior settings shown on the Assistant tab.\n */\nexport interface WorkflowAgentBehavior {\n responseLength?: ResponseLength;\n oneQuestionPerTurn?: boolean;\n aiDisclosure?: AiDisclosure;\n smsStopInstructions?: boolean;\n}\n\n/**\n * Response model for workflow config-validation (drift) diagnostics.\n *\n * ``configHealthIssues`` is the canonical contract (plan §3.9) and the\n * stable final field name — it is deliberately NOT renamed back onto\n * ``issues`` at cleanup, so consumers see only one wire-type change.\n * Discriminated provenance (a real Ability slug versus a closed detector\n * code) and typed remediation focus replace the overloaded ``abilityType``.\n *\n * ``issues`` is the LEGACY field and this is Phase 3A, the additive step: a\n * browser still running a pre-cutover bundle reads ``issues``, so removing\n * it in the same deploy that ships the canonical bundle would silently empty\n * every one of those dialogs. Both lists are produced from ONE evaluation —\n * :func:`lib.services.config_health_legacy.to_legacy_ability_issues`\n * projects the same findings — so nothing is evaluated twice and the two can\n * never disagree. Phase 3C removes ``issues`` in a later PR and deploy.\n *\n * The endpoint still evaluates the editor's DRAFT revision — the canonical\n * item shape is lifecycle-neutral.\n */\nexport interface WorkflowConfigValidationResponse {\n issues?: AbilityConfigIssue[];\n configHealthIssues?: ConfigHealthIssue[];\n}\n\n/**\n * Response model for workflow contributor.\n */\nexport interface WorkflowContributorResponse {\n id: number;\n workflowRevisionId: number;\n memberId: number;\n title: string;\n channels: string[];\n hint?: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Portable policy; automatic decisions do not use tool availability.\n */\nexport interface WorkflowEscalationPolicy {\n signalTriggers?: ('self_harm' | 'harm_to_others' | 'medical_emergency' | 'unsafe_situation' | 'emotional_distress' | 'frustration' | 'requests_human')[] | null;\n pausedMessage?: string | null;\n notifiedMessage?: string | null;\n onlineMessage?: string | null;\n offlineMessage?: string | null;\n pauseOnEscalate?: boolean | null;\n routingMode?: WorkflowEscalationPolicyRoutingMode;\n includeWorkspaceRules?: boolean;\n manualToolEnabled?: boolean;\n manualToolCondition?: string | null;\n}\n\nexport type WorkflowEscalationPolicyRoutingMode = typeof WorkflowEscalationPolicyRoutingMode[keyof typeof WorkflowEscalationPolicyRoutingMode];\n\n\nexport const WorkflowEscalationPolicyRoutingMode = {\n workspace: 'workspace',\n custom: 'custom',\n} as const;\n\n/**\n * Recipient bindings owned by one workspace, outside shared policy.\n */\nexport interface WorkflowEscalationRouting {\n priorityMemberIds?: number[];\n operatorGroupIds?: number[];\n}\n\n/**\n * Response model for workflow note.\n */\nexport interface WorkflowNoteResponse {\n id: number;\n uuid: string;\n /** STABLE Workflow root id */\n workflowId: number;\n /** WorkflowRevision id this note is scoped to */\n workflowRevisionId: number;\n posX: number;\n posY: number;\n width: number;\n height: number;\n contents: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * One executable workflow revision — pure revision facts only.\n *\n * Root facts (name/description/owner/archived/defaults) live on\n * :class:`WorkflowResponse`; this model carries revision identity plus\n * ``workflowId`` / ``workflowUuid`` / ``workflowName`` backrefs and, when\n * loaded, the graph collections (abilities, event rules, contributors,\n * task counts) and the caller's permission mask.\n */\nexport interface WorkflowRevisionResponse {\n id: number;\n uuid: string;\n workflowId: number;\n workflowUuid: string;\n workflowName?: string | null;\n revisionNumber?: number | null;\n revisionName?: string | null;\n publishNotes?: string | null;\n publishedAt?: string | null;\n publishedByAccountUuid?: string | null;\n prompt?: string | null;\n assistantName?: string | null;\n assistantIdentity?: string | null;\n initialMessageOutbound?: GreetingEntry[] | null;\n initialMessageInbound?: GreetingEntry[] | null;\n escalationSettings?: WorkflowEscalationPolicy;\n escalationRouting?: WorkflowEscalationRouting;\n escalationRoutingRequired?: boolean;\n agentBehavior?: WorkflowAgentBehavior;\n assistantConfigDigest: string;\n startTaskId?: number | null;\n chatModelId: string;\n chatModelConfig?: WorkflowRevisionResponseChatModelConfig;\n realtimeModelId?: string | null;\n realtimeModelConfig?: WorkflowRevisionResponseRealtimeModelConfig;\n enableVoicemailDetection?: boolean | null;\n posX?: number | null;\n posY?: number | null;\n knowledge?: KnowledgeEntry[];\n createdAt: string;\n updatedAt: string;\n taskCount?: number;\n archivedTaskCount?: number;\n permissions?: number;\n abilities?: AbilityResponse[];\n eventRules?: EventRuleResponse[];\n contributors?: WorkflowContributorResponse[];\n}\n\nexport type WorkflowRevisionResponseChatModelConfig = { [key: string]: unknown } | null;\n\nexport type WorkflowRevisionResponseRealtimeModelConfig = { [key: string]: unknown } | null;\n\n/**\n * PHI-safe response shape for the route dry-run endpoint.\n *\n * Fields:\n * assignmentId / chatId — context the dry-run was executed under.\n * sourceTaskId / sourceAssignmentTaskId — current Task/AssignmentTask\n * resolved from the supplied chat context (after applying any\n * ``current_task_id`` / ``current_assignment_task_id`` overrides).\n * status — one of the\n * :class:`lib.services.cel_edge_evaluator.EdgeEvaluationStatus`\n * labels (e.g. ``\"no_edges\"``, ``\"no_match\"``,\n * ``\"would_transition\"``, ``\"matched_current_task\"``,\n * ``\"missing_assignment_task\"``, ``\"transition_blocked\"``,\n * ``\"error\"``).\n * edgeCount — number of automatic-routing-candidate edges the\n * evaluator considered.\n * candidateChildTaskIds — Task IDs of every candidate edge the\n * evaluator examined.\n * winningChildTaskId — Task ID of the matched child Task, populated\n * when ``status == \"would_transition\"`` or\n * ``\"matched_current_task\"`` or ``\"missing_assignment_task\"``\n * or ``\"transition_blocked\"``.\n * errorType — exception class name only when ``status == \"error\"``;\n * never the raw ``str(exc)`` message.\n * issues — optional list of related ``AbilityConfigIssue`` entries\n * (e.g. from the Workflow Health collectors) the caller may\n * surface alongside the trace. The route may leave this empty\n * in Phase 4; the field exists to keep the contract stable.\n *\n * PHI guard (enforced by tests): raw CEL, Form values, Member values,\n * Chat content, and ``str(exc)`` MUST NOT appear on this response.\n */\nexport interface WorkflowRouteDryRunResponse {\n assignmentId: number;\n chatId: number;\n sourceTaskId?: number | null;\n sourceAssignmentTaskId?: number | null;\n status: string;\n edgeCount: number;\n candidateChildTaskIds?: number[];\n winningChildTaskId?: number | null;\n errorType?: string | null;\n issues?: AbilityConfigIssue[];\n}\n\n/**\n * Response model for a workflow template.\n */\nexport interface WorkflowTemplateResponse {\n uuid: string;\n name: string;\n icon: string;\n shortDescription: string;\n longDescription: string;\n defaultWorkflowName: string;\n exampleConversation: string;\n requiredFeatures: string[];\n tags?: string[];\n available: boolean;\n}\n"],"mappings":";AAyIO,IAAM,qCAAqC;AAAA,EAChD,sBAAsB;AAAA,EACtB,qBAAqB;AACvB;;;ACrDO,IAAK,gBAAL,kBAAKA,mBAAL;AACJ,EAAAA,eAAA,UAAO;AACP,EAAAA,eAAA,WAAQ;AACR,EAAAA,eAAA,WAAQ;AACR,EAAAA,eAAA,UAAO;AACP,EAAAA,eAAA,cAAW;AACX,EAAAA,eAAA,YAAS;AACT,EAAAA,eAAA,aAAU;AACV,EAAAA,eAAA,UAAO;AACP,EAAAA,eAAA,cAAW;AACX,EAAAA,eAAA,iBAAc;AACd,EAAAA,eAAA,aAAU;AACV,EAAAA,eAAA,UAAO;AACP,EAAAA,eAAA,eAAY;AACZ,EAAAA,eAAA,cAAW;AACX,EAAAA,eAAA,WAAQ;AACR,EAAAA,eAAA,YAAS;AACT,EAAAA,eAAA,iBAAc;AAjBL,SAAAA;AAAA,GAAA;AAoBL,IAAK,cAAL,kBAAKC,iBAAL;AACJ,EAAAA,aAAA,iBAAc;AACd,EAAAA,aAAA,cAA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EACV,OAAO;AAAA,EACP,eAAe;AAAA,EACf,aAAa;AAAA,EACb,SAAS;AAAA,EACT,UAAU;AAAA,EACV,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,oBAAoB;AAAA,EACpB,gBAAgB;AAAA,EAChB,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AACZ;AAQO,IAAM,eAAe;AAAA,EAC1B,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,QAAQ;AACV;AAmFO,IAAM,mCAAmC;AAAA,EAC9C,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,sBAAsB;AACxB;AAwRO,IAAM,iBAAiB;AAAA,EAC5B,SAAS;AAAA,EACT,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,UAAU;AACZ;;;AC5aO,IAAM,yBAAyB;AAAA,EACpC,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,gBAAgB;AAAA,EAChB,4BAA4B;AAAA,EAC5B,iBAAiB;AACnB;AAKO,IAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA,EACT,OAAO;AACT;AAQO,IAAM,eAAe;AAAA,EAC1B,YAAY;AAAA,EACZ,YAAY;AACd;AAmUO,IAAM,iBAAiB;AAAA,EAC5B,OAAO;AAAA,EACP,OAAO;AAAA,EACP,UAAU;AACZ;","names":["DataFieldType","IndexStatus","DataTypeRecordScope","DataSensitivity","DataCategory","CalendarPermissionType","CalendarSource","CalendarScheduleRecurrence","CalendarScheduleAvailabilityType","CalendarEventStatus","AttendeeStatus","AttendeeResponseStatus"]}
@@ -242,6 +242,20 @@ var BaseApiClient = class {
242
242
  this.setOrgSession(void 0);
243
243
  }
244
244
  async fetch(endpoint, options, orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1, enhancedAuthRetry = false) {
245
+ return this.fetchApiVersion(
246
+ "v2",
247
+ endpoint,
248
+ options,
249
+ orgAuthRetriesRemaining,
250
+ enhancedAuthRetry
251
+ );
252
+ }
253
+ /**
254
+ * `fetch` against a named API version: `/api/{version}/{endpoint}`, with the
255
+ * same credentials, step-up retry, org-auth challenge handling and
256
+ * org-session rejection bookkeeping. `fetch` is this method bound to `v2`.
257
+ */
258
+ async fetchApiVersion(version, endpoint, options, orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1, enhancedAuthRetry = false) {
245
259
  try {
246
260
  const headers = new Headers({
247
261
  // Don't set Content-Type for FormData — the browser must set it
@@ -257,7 +271,7 @@ var BaseApiClient = class {
257
271
  const requestOrgRevision = this.orgSessionRevision;
258
272
  const presentedOrgUuid = this.orgSessionOrgUuid;
259
273
  const rejectionHandler = this.orgSessionRejectionHandler;
260
- const fullUrl = `${this.baseUrl}/api/v2/${endpoint}`;
274
+ const fullUrl = `${this.baseUrl}/api/${version}/${endpoint}`;
261
275
  const response = await this.fetchFunction(fullUrl, {
262
276
  ...options,
263
277
  ...this.credentialsInit(),
@@ -277,7 +291,13 @@ var BaseApiClient = class {
277
291
  this.enhancedAuthInProgress = null;
278
292
  }
279
293
  }
280
- return await this.fetch(endpoint, options, orgAuthRetriesRemaining, true);
294
+ return await this.fetchApiVersion(
295
+ version,
296
+ endpoint,
297
+ options,
298
+ orgAuthRetriesRemaining,
299
+ true
300
+ );
281
301
  }
282
302
  if (response.status === 401) {
283
303
  const orgAuthInfo = parseOrgAuthChallenge(response.headers.get("WWW-Authenticate"));
@@ -298,7 +318,13 @@ var BaseApiClient = class {
298
318
  if (completion !== "cache") nextOrgRetries = 0;
299
319
  }
300
320
  this.assertOrgAuthContext(orgAuthInfo.orgUuid);
301
- return await this.fetch(endpoint, options, nextOrgRetries, enhancedAuthRetry);
321
+ return await this.fetchApiVersion(
322
+ version,
323
+ endpoint,
324
+ options,
325
+ nextOrgRetries,
326
+ enhancedAuthRetry
327
+ );
302
328
  }
303
329
  if (orgAuthInfo) {
304
330
  this.clearOrgSessionIfCurrent(presentedOrgSession);
@@ -311,7 +337,7 @@ var BaseApiClient = class {
311
337
  }
312
338
  }
313
339
  const errorData = await response.json().catch(() => ({}));
314
- if (response.status === 401 && endpoint === "account") {
340
+ if (response.status === 401 && version === "v2" && endpoint === "account") {
315
341
  throw new Error("unauthorized");
316
342
  }
317
343
  if (Array.isArray(errorData.detail)) {
@@ -551,4 +577,4 @@ export {
551
577
  BaseApiClient,
552
578
  ChatInteractionController
553
579
  };
554
- //# sourceMappingURL=chunk-ZLF3N3ZD.js.map
580
+ //# sourceMappingURL=chunk-P2X5TOYY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/api/base.ts","../src/helpers/chat-interaction.ts"],"sourcesContent":["// Utility function to read a specific cookie value\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const trimmedCookie = cookie.trim();\n const eqIndex = trimmedCookie.indexOf('=');\n if (eqIndex === -1) continue;\n\n const cookieName = trimmedCookie.substring(0, eqIndex);\n const cookieValue = trimmedCookie.substring(eqIndex + 1);\n\n if (cookieName === name) {\n return cookieValue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Structured validation error returned by the backend's workflow-expression\n * validator (CEL / Jinja schema checks). See WorkflowValidationErrorResponse\n * in workflowValidationTypes.ts for the public-facing shape.\n */\nexport interface ApiValidationError {\n field: string;\n kind: 'cel_syntax' | 'cel_schema' | 'jinja_syntax' | 'jinja_schema';\n message: string;\n offendingPath: string | null;\n location: {\n start: number;\n end: number;\n line: number;\n column: number;\n length: number;\n } | null;\n suggestion: string | null;\n}\n\nfunction isApiValidationError(value: unknown): value is ApiValidationError {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.field === 'string' && typeof v.kind === 'string' && typeof v.message === 'string'\n );\n}\n\n/** Browser-console sink for API failures. A fixed event name only — never the\n * error object, its ``name``, or response-derived ``message``/``errorData``. */\nfunction logApiClientError(_error: unknown): void {\n console.warn('API request failed');\n}\n\nexport class ApiError extends Error {\n statusCode: number;\n /** Legacy string-array errors — kept for non-validation callers. */\n errors?: string[];\n /**\n * Structured workflow-expression validation errors (CEL/Jinja).\n * Populated when the backend returns a WorkflowValidationErrorResponse.\n */\n validationErrors?: ApiValidationError[];\n /**\n * The raw structured `detail` object when the backend returned one (a body\n * with `error: true` or a `code`). Declared here rather than bolted on with\n * `as any` at the throw site so consumers can narrow it with a type guard —\n * see `isMemberContactConflict` in `types/member-types`.\n */\n errorData?: unknown;\n\n constructor(\n message: string,\n statusCode: number,\n errors?: string[],\n validationErrors?: ApiValidationError[]\n ) {\n super(message);\n this.name = 'ApiError';\n this.statusCode = statusCode;\n this.errors = errors;\n this.validationErrors = validationErrors;\n }\n}\n\n/**\n * Handler for enhanced authentication requirement (RFC 9470 Step-Up Authentication).\n * Called when a 401 response includes WWW-Authenticate header with\n * error=\"insufficient_user_authentication\".\n * Should return a promise that resolves with the new auth token after re-auth.\n */\nexport type EnhancedAuthHandler = () => Promise<string>;\n\n/**\n * Info parsed from WWW-Authenticate header for org auth requirement.\n */\nexport interface OrgAuthInfo {\n orgUuid: string;\n authUrl: string;\n /** Requested authentication contexts. The server must verify the new evidence. */\n acrValues?: string[];\n /** The SDK sent an org credential on the request that produced this challenge. */\n sessionRejected?: boolean;\n}\n\n/**\n * Handler for organization authentication requirement.\n * Called when a 401 response includes WWW-Authenticate header with realm=\"org\".\n * The handler should redirect the user to the auth URL for consent/SSO.\n * Bearer handlers return a candidate; cookie handlers may resolve without a value.\n * `sessionRejected` describes the credential sent on that request, without\n * exposing it. A rejected cached candidate requires fresh authentication.\n */\nexport interface OrgAuthSessionCandidate {\n session: string;\n orgUuid: string;\n /** Local provenance only; the server still validates the credential. */\n source: 'cache' | 'new';\n /** Cleanup for this exact candidate when its own org rejects it. */\n onRejected?: () => void;\n}\n\nexport type OrgAuthHandler = (info: OrgAuthInfo) => Promise<OrgAuthSessionCandidate | void>;\ntype OrgAuthCompletion = OrgAuthSessionCandidate['source'] | 'cookie';\n\n/**\n * Check if a WWW-Authenticate header indicates step-up authentication is required.\n * Per RFC 9470, this is indicated by error=\"insufficient_user_authentication\".\n */\nfunction requiresStepUpAuth(wwwAuthenticate: string | null): boolean {\n if (!wwwAuthenticate) return false;\n return wwwAuthenticate.includes('error=\"insufficient_user_authentication\"');\n}\n\n/**\n * Parse org auth info from WWW-Authenticate header.\n * Returns null if this is not an org auth challenge.\n * Expected format: Bearer realm=\"org\", org_uuid=\"...\", auth_url=\"...\"\n * (the challenge names no cookie: a browser's org session is an httpOnly\n * cookie on its own host, and a bearer client sends `X-Org-Session`).\n *\n * Exported so non-SDK fetch paths (e.g. the app's same-origin file-content\n * proxy fetches) can detect the same challenge and trigger the shared org\n * step-up flow.\n */\nexport function parseOrgAuthChallenge(wwwAuthenticate: string | null): OrgAuthInfo | null {\n if (!wwwAuthenticate) return null;\n if (!wwwAuthenticate.includes('realm=\"org\"')) return null;\n\n // Parse the key-value pairs from the header\n const orgUuidMatch = wwwAuthenticate.match(/org_uuid=\"([^\"]+)\"/);\n const authUrlMatch = wwwAuthenticate.match(/auth_url=\"([^\"]+)\"/);\n const acrValues = wwwAuthenticate\n .match(/acr_values=\"([^\"]*)\"/)?.[1]\n ?.trim()\n .split(/\\s+/)\n .filter(Boolean);\n\n if (!orgUuidMatch?.[1] || !authUrlMatch?.[1]) {\n // Don't log the raw header value — it embeds org_uuid + auth_url.\n console.warn('Invalid org auth challenge header: missing required fields');\n return null;\n }\n\n return {\n orgUuid: orgUuidMatch[1],\n authUrl: authUrlMatch[1],\n ...(acrValues?.length ? { acrValues } : {}),\n };\n}\n\n/**\n * The API versions a client can address. `/api/v2` is every existing method's\n * base; `/api/v3` serves the Chat resource\n * (`docs/decisions/api/2026-11-09-1-api-v3-begins-with-the-chat-resource.md`).\n */\ntype ApiVersion = 'v2' | 'v3';\n\nfunction setOrgAuthHeader(headers: Headers, token: string | undefined): void {\n if (!token) return;\n headers.set('X-Org-Session', token);\n}\n\n/**\n * Transport and credential for every request the client makes.\n *\n * - **Bearer** (`apiKey` set): `Authorization: Bearer <apiKey>` on every\n * request, no cookies. This is how non-browser consumers (the CLI, servers,\n * API keys) and bearer-holding browser runtimes (widget iframes) call the API.\n * - **Same-origin session** (no `apiKey`): no `Authorization` header and\n * `credentials: 'same-origin'`. The browser presents the host's httpOnly\n * session cookie, and only to the origin the page is on; the client never\n * reads a cookie to build a credential. A browser app points `baseUrl` at its\n * own origin, which serves `/api/v2` and `/api/v3` (Gravity Rail's edge on\n * full-account hosts, the frontend's proxy on Site hosts).\n *\n * The org-auth challenge (`WWW-Authenticate: Bearer realm=\"org\"`) is answered by\n * `setOrgAuthHandler`. A bearer client's handler hands back the org session with\n * a candidate result, which is sent as `X-Org-Session`; in same-origin session\n * mode the org session is an httpOnly cookie on the page's origin, so the\n * request is retried once after the handler and the browser presents it.\n * A bearer request that starts without an org credential may first try a\n * cached candidate, then make one fresh-auth attempt if the server rejects\n * it. A request that starts with an org credential has only the fresh attempt.\n */\nexport class BaseApiClient {\n protected baseUrl: string;\n protected apiKey: string | undefined;\n protected isCrossDomain: boolean;\n protected fetchFunction: typeof fetch;\n private enhancedAuthHandler?: EnhancedAuthHandler;\n private enhancedAuthInProgress: Promise<string> | null = null;\n private orgAuthHandler?: OrgAuthHandler;\n private orgAuthInProgress: {\n orgUuid: string;\n requestRevision: number;\n promise: Promise<OrgAuthCompletion>;\n } | null = null;\n private orgSessionRevision = 0;\n private orgSessionRejectionHandler?: () => void;\n private orgSession?: string;\n /**\n * Optional issuer context supplied with an opaque credential. A handler\n * cannot complete a challenge with a session explicitly bound to another org.\n * The server remains responsible for validating the credential itself.\n */\n private orgSessionOrgUuid?: string;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n // console.log('[BaseApiClient] constructor - baseUrl:', baseUrl);\n // Bind fetch to its proper context (window in browser, global in Node)\n this.fetchFunction =\n customFetch || (typeof window !== 'undefined' ? fetch.bind(window) : fetch);\n\n // Determine if we're making cross-domain requests by comparing current origin to API origin\n const apiUrlParsed = new URL(baseUrl);\n const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';\n this.isCrossDomain = currentOrigin !== '' && currentOrigin !== apiUrlParsed.origin;\n // console.log('[BaseApiClient] isCrossDomain:', this.isCrossDomain, 'currentOrigin:', currentOrigin, 'apiOrigin:', apiUrlParsed.origin);\n }\n\n /**\n * Set the handler for enhanced authentication requirements (RFC 9470 Step-Up Auth).\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with error=\"insufficient_user_authentication\".\n */\n setEnhancedAuthHandler(handler: EnhancedAuthHandler | undefined) {\n this.enhancedAuthHandler = handler;\n }\n\n /**\n * Set the handler for organization authentication requirements.\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with realm=\"org\". The handler should redirect the user to complete org auth.\n */\n setOrgAuthHandler(handler: OrgAuthHandler | undefined) {\n this.orgAuthHandler = handler;\n }\n\n /**\n * Update the API key (used after successful re-authentication).\n */\n updateApiKey(newApiKey: string) {\n this.apiKey = newApiKey;\n }\n\n /**\n * Set the opaque org session credential a bearer client sends as `X-Org-Session`.\n * Only opaque `gr_sess_` credentials are supported. A legacy org token\n * raises an error; sign in to the organization again to obtain a session.\n * Pass `undefined` to clear the session.\n *\n * `orgUuid` is the org that issued the credential. When supplied by an\n * org-auth handler, it must match the challenge the handler completes.\n * Callers without that context may omit it. Any rejected credential can\n * trigger one reauthentication attempt, including for the same org.\n */\n setOrgSession(session: string | undefined, orgUuid?: string) {\n if (session !== undefined && !/^gr_sess_[A-Za-z0-9_-]+$/.test(session)) {\n throw new Error(\n 'Unsupported organization session. Sign in again to obtain an opaque gr_sess_ credential.'\n );\n }\n this.orgSessionRejectionHandler = undefined;\n this.orgSession = session;\n this.orgSessionOrgUuid = session ? orgUuid : undefined;\n this.orgSessionRevision += 1;\n }\n\n /**\n * The `credentials` a request carries: none for a bearer client (the fetch\n * default), the page's own-origin cookies for a same-origin session.\n */\n private credentialsInit(): Pick<RequestInit, 'credentials'> {\n return this.apiKey ? {} : { credentials: 'same-origin' };\n }\n\n /**\n * Run the org-auth handler once for concurrent challenges. A bearer client's\n * handler returns a candidate; a same-origin session's\n * handler leaves an httpOnly org-session cookie on the page's origin instead,\n * which the retry presents. A bearer client whose handler issued nothing has\n * nothing to retry with.\n */\n private async answerOrgAuthChallenge(\n info: OrgAuthInfo,\n presented: string | null,\n requestRevision: number\n ): Promise<OrgAuthCompletion> {\n const handler = this.orgAuthHandler;\n if (!handler) throw new ApiError('Organization authentication handler is unavailable', 401);\n if (this.orgAuthInProgress) {\n if (\n this.orgAuthInProgress.orgUuid !== info.orgUuid ||\n this.orgAuthInProgress.requestRevision !== requestRevision\n ) {\n throw new ApiError(\n 'Organization authentication context changed. Retry the request.',\n 401\n );\n }\n return this.orgAuthInProgress.promise;\n }\n if (this.orgSessionRevision !== requestRevision) {\n throw new ApiError('Organization authentication context changed. Retry the request.', 401);\n }\n this.clearOrgSessionIfCurrent(presented);\n const attemptRevision = this.orgSessionRevision;\n const promise: Promise<OrgAuthCompletion> = Promise.resolve()\n .then(() => handler(info))\n .then((candidate): OrgAuthCompletion => {\n if (this.orgSessionRevision !== attemptRevision) {\n throw new ApiError(\n 'Organization authentication context changed. Retry the request.',\n 401\n );\n }\n if (candidate === undefined) {\n if (this.apiKey) {\n throw new ApiError(\n 'Organization authentication must return a session candidate',\n 401\n );\n }\n return 'cookie';\n }\n if (\n !candidate ||\n typeof candidate.session !== 'string' ||\n (candidate.source !== 'cache' && candidate.source !== 'new')\n ) {\n throw new ApiError(\n 'Organization authentication returned an invalid session candidate',\n 401\n );\n }\n if (candidate.orgUuid !== info.orgUuid) {\n throw new ApiError(\n 'Organization authentication issued a session for another organization',\n 401\n );\n }\n if (candidate.source === 'cache' && info.sessionRejected) {\n throw new ApiError(\n 'Organization authentication requires a newly issued session after rejection',\n 401\n );\n }\n this.setOrgSession(candidate.session, candidate.orgUuid);\n let rejected = false;\n this.orgSessionRejectionHandler = () => {\n if (rejected) return;\n rejected = true;\n candidate.onRejected?.();\n };\n return candidate.source;\n })\n .finally(() => {\n if (this.orgAuthInProgress?.promise === promise) this.orgAuthInProgress = null;\n });\n this.orgAuthInProgress = { orgUuid: info.orgUuid, requestRevision, promise };\n return promise;\n }\n\n private assertOrgAuthContext(orgUuid: string): void {\n if (\n (this.orgSession && this.orgSessionOrgUuid !== orgUuid) ||\n (this.apiKey && !this.orgSession)\n ) {\n throw new ApiError('Organization authentication context changed. Retry the request.', 401);\n }\n }\n\n private notifyOrgSessionRejected(\n presented: string | null,\n callback: (() => void) | undefined\n ): void {\n try {\n callback?.();\n } catch {\n this.clearOrgSessionIfCurrent(presented);\n throw new ApiError('Could not discard rejected organization session', 401);\n }\n }\n\n private hasNewerOrgSession(presented: string | null, orgUuid: string): boolean {\n // A concurrent login may have replaced the rejected credential. Retry\n // that replacement only with an explicit matching org binding; the\n // server still validates it, and this consumes the existing retry budget.\n return Boolean(\n presented &&\n this.orgSession &&\n this.orgSession !== presented &&\n this.orgSessionOrgUuid === orgUuid\n );\n }\n\n private clearOrgSessionIfCurrent(expected: string | null | undefined): void {\n if (this.orgSession !== expected || this.orgSession === undefined) return;\n this.setOrgSession(undefined);\n }\n\n protected async fetch<T>(\n endpoint: string,\n options?: RequestInit,\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<T> {\n return this.fetchApiVersion<T>(\n 'v2',\n endpoint,\n options,\n orgAuthRetriesRemaining,\n enhancedAuthRetry\n );\n }\n\n /**\n * `fetch` against a named API version: `/api/{version}/{endpoint}`, with the\n * same credentials, step-up retry, org-auth challenge handling and\n * org-session rejection bookkeeping. `fetch` is this method bound to `v2`.\n */\n protected async fetchApiVersion<T>(\n version: ApiVersion,\n endpoint: string,\n options?: RequestInit,\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<T> {\n try {\n const headers = new Headers({\n // Don't set Content-Type for FormData — the browser must set it\n // with the multipart boundary automatically.\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n const presentedOrgSession = headers.get('X-Org-Session');\n const requestOrgRevision = this.orgSessionRevision;\n const presentedOrgUuid = this.orgSessionOrgUuid;\n const rejectionHandler = this.orgSessionRejectionHandler;\n\n // console.warn(\"Calling with apiKey:\", this.apiKey)\n const fullUrl = `${this.baseUrl}/api/${version}/${endpoint}`;\n // console.log('[BaseApiClient] fetch - URL:', fullUrl, 'baseUrl:', this.baseUrl, 'endpoint:', endpoint);\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n !enhancedAuthRetry &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n if (this.apiKey) this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n return await this.fetchApiVersion<T>(\n version,\n endpoint,\n options,\n orgAuthRetriesRemaining,\n true\n );\n }\n\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (orgAuthInfo && presentedOrgSession) {\n orgAuthInfo.sessionRejected = true;\n if (presentedOrgUuid === orgAuthInfo.orgUuid) {\n this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);\n }\n }\n if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {\n let nextOrgRetries = orgAuthRetriesRemaining - 1;\n if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {\n const completion = await this.answerOrgAuthChallenge(\n orgAuthInfo,\n presentedOrgSession,\n requestOrgRevision\n );\n if (completion !== 'cache') nextOrgRetries = 0;\n }\n this.assertOrgAuthContext(orgAuthInfo.orgUuid);\n return await this.fetchApiVersion<T>(\n version,\n endpoint,\n options,\n nextOrgRetries,\n enhancedAuthRetry\n );\n }\n if (orgAuthInfo) {\n this.clearOrgSessionIfCurrent(presentedOrgSession);\n if (orgAuthInfo.acrValues?.includes('urn:gravity:mfa')) {\n throw new ApiError(\n 'Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.',\n 401\n );\n }\n }\n }\n\n const errorData = await response.json().catch(() => ({}));\n\n // Handle unauthorized errors for account endpoint\n if (response.status === 401 && version === 'v2' && endpoint === 'account') {\n throw new Error('unauthorized');\n }\n\n // Handle structured validation errors (Pydantic array format)\n if (Array.isArray(errorData.detail)) {\n const formattedErrors = errorData.detail\n .map((error: any) => {\n const location = error.loc.join(' > ');\n return `${location}: ${error.msg}`;\n })\n .join('\\n');\n throw new ApiError(`Validation Error:\\n${formattedErrors}`, response.status);\n }\n\n // Handle validation errors with errors array (new format)\n if (errorData.errors && Array.isArray(errorData.errors)) {\n // Structured workflow-expression validation errors — objects with\n // { field, kind, message, offendingPath, location }. Build a\n // readable message and preserve the structured payload.\n if (errorData.errors.length > 0 && isApiValidationError(errorData.errors[0])) {\n const validationErrors: ApiValidationError[] =\n errorData.errors.filter(isApiValidationError);\n const [first] = validationErrors;\n if (first) {\n const extra =\n validationErrors.length > 1\n ? ` (+${validationErrors.length - 1} more)`\n : '';\n const readable = `${first.field}: ${first.message}${extra}`;\n throw new ApiError(\n readable,\n response.status,\n validationErrors.map((e) => `${e.field}: ${e.message}`),\n validationErrors\n );\n }\n }\n\n // Legacy string-array errors.\n const stringErrors: string[] = errorData.errors.filter(\n (e: unknown): e is string => typeof e === 'string'\n );\n const details = stringErrors.join('; ');\n const message = errorData.detail\n ? `${errorData.detail}: ${details}`\n : `Validation failed: ${details}`;\n throw new ApiError(message, response.status, stringErrors);\n }\n\n // Handle structured errors (with error: true or with code property).\n //\n // TWO body shapes reach here and both carry structure:\n //\n // * `detail` IS the structured object — the member/account contact\n // conflicts build their whole payload as `HTTPException.detail`.\n // * `detail` is PROSE and the machine-readable fields sit beside it\n // at the top level. That is what the domain exception handlers\n // emit: `conflict_handler` writes `{detail, code, ...payload}`, so\n // a Journey v2 refusal arrives as\n // `{detail: \"...\", code: \"journey_v2_invalid_topology\", issues: [...]}`.\n //\n // `detail || errorData` picked the prose string for the second shape,\n // which is not an object, so the branch fell through and `code` and\n // `issues` were dropped on the floor — leaving a client unable to\n // tell a definition conflict from a structural refusal, or to point\n // at the resources a validator rejected. Prefer an OBJECT detail and\n // otherwise read the body itself; the message is unchanged in both\n // cases (prose still wins when there is prose).\n const detail = errorData.detail;\n const structuredError = detail && typeof detail === 'object' ? detail : errorData;\n if (\n structuredError &&\n typeof structuredError === 'object' &&\n (structuredError.error === true || structuredError.code)\n ) {\n const message =\n (typeof detail === 'string' && detail) ||\n structuredError.message ||\n structuredError.code ||\n 'Unknown error';\n const error = new ApiError(message, response.status);\n // Attach the full error data for frontend handling\n error.errorData = structuredError;\n throw error;\n }\n\n // Handle simple error messages\n const errorMessage =\n typeof errorData.detail === 'string'\n ? errorData.detail\n : errorData.message || response.statusText;\n const simpleError = new ApiError(errorMessage, response.status);\n // A prose `detail` STRING alongside a top-level `code` is the shape\n // the backend's domain-validation handler produces: it merges an\n // exception's `payload` into the body and keeps `detail`\n // authoritative. That misses the structured branch above, because\n // `errorData.detail || errorData` resolves to the string. Carry the\n // body through so a caller can still branch on the token — the\n // alternative is parsing `detail`, which is deliberately\n // human-facing prose and not a stable contract.\n if (typeof errorData.code === 'string') {\n simpleError.errorData = errorData;\n }\n throw simpleError;\n }\n\n // Handle 204 No Content - no JSON body to parse\n if (response.status === 204) {\n return undefined as any;\n }\n\n return response.json();\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n\n protected async fetchRaw(\n endpoint: string,\n options?: RequestInit,\n allowedErrorStatuses: number[] = [],\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<Response> {\n try {\n const headers = new Headers({\n ...((options?.headers as Record<string, string>) || {}),\n });\n // Without this, fetch labels a string body text/plain and FastAPI\n // rejects a JSON body parameter with 422 \"Validation failed\" (every\n // live-view browser storage save, until 2026-10-27).\n if (typeof options?.body === 'string' && !headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n const presentedOrgSession = headers.get('X-Org-Session');\n const requestOrgRevision = this.orgSessionRevision;\n const presentedOrgUuid = this.orgSessionOrgUuid;\n const rejectionHandler = this.orgSessionRejectionHandler;\n\n const response = await this.fetchFunction(`${this.baseUrl}/api/v2/${endpoint}`, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n !enhancedAuthRetry &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n if (this.apiKey) this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n return await this.fetchRaw(\n endpoint,\n options,\n allowedErrorStatuses,\n orgAuthRetriesRemaining,\n true\n );\n }\n\n // Mirror of the org-auth branch in fetch() above; see comments there.\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (orgAuthInfo && presentedOrgSession) {\n orgAuthInfo.sessionRejected = true;\n if (presentedOrgUuid === orgAuthInfo.orgUuid) {\n this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);\n }\n }\n if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {\n let nextOrgRetries = orgAuthRetriesRemaining - 1;\n if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {\n const completion = await this.answerOrgAuthChallenge(\n orgAuthInfo,\n presentedOrgSession,\n requestOrgRevision\n );\n if (completion !== 'cache') nextOrgRetries = 0;\n }\n this.assertOrgAuthContext(orgAuthInfo.orgUuid);\n return await this.fetchRaw(\n endpoint,\n options,\n allowedErrorStatuses,\n nextOrgRetries,\n enhancedAuthRetry\n );\n }\n if (orgAuthInfo) {\n this.clearOrgSessionIfCurrent(presentedOrgSession);\n if (\n !allowedErrorStatuses.includes(401) &&\n orgAuthInfo.acrValues?.includes('urn:gravity:mfa')\n ) {\n throw new ApiError(\n 'Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.',\n 401\n );\n }\n }\n }\n\n if (allowedErrorStatuses.includes(response.status)) {\n return response;\n }\n\n const errorText = await response.text().catch(() => '');\n throw new ApiError(errorText || response.statusText, response.status);\n }\n\n return response;\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n\n /**\n * Fetch from root path (not prefixed with /api/v2/)\n * Used for OAuth and other non-API endpoints\n */\n protected async fetchRoot<T>(path: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const fullUrl = `${this.baseUrl}/${path}`;\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null as T;\n }\n const errorData = await response.json().catch(() => ({}));\n const errorMessage = errorData.detail || errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n return response.json();\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n}\n","import type { ChatsApi } from '../api/chats';\nimport type { InteractionMode, InteractionSessionResponse } from '../types/chat-types';\n\ntype InteractionApi = Pick<\n ChatsApi,\n 'createChatInteractionSession' | 'transitionChatInteractionSession'\n>;\n\n/** One client's mode history in one Chat. Create a separate controller per device/session. */\nexport class ChatInteractionController {\n private current: InteractionSessionResponse | undefined;\n private pending: { mode: InteractionMode; requestId: string } | undefined;\n private tail: Promise<unknown> = Promise.resolve();\n private readonly clientSessionId = crypto.randomUUID();\n\n constructor(\n private readonly api: InteractionApi,\n private readonly workspaceId: string,\n private readonly chatId: number\n ) {}\n\n /** Serialize switches and reuse request IDs when a response is lost. */\n ensure(mode: InteractionMode): Promise<InteractionSessionResponse> {\n const operation = this.tail.then(async () => {\n // Resolve an uncertain earlier write before selecting the next mode.\n if (this.pending) await this.applyPending();\n if (this.current?.mode !== mode) {\n this.pending = { mode, requestId: crypto.randomUUID() };\n await this.applyPending();\n }\n if (!this.current) throw new Error('Interaction session unavailable');\n return this.current;\n });\n this.tail = operation.catch(() => undefined);\n return operation;\n }\n\n private async applyPending(): Promise<void> {\n const pending = this.pending;\n if (!pending) return;\n this.current = this.current\n ? await this.api.transitionChatInteractionSession(\n this.workspaceId,\n this.chatId,\n this.current.id,\n pending\n )\n : await this.api.createChatInteractionSession(this.workspaceId, this.chatId, {\n ...pending,\n clientSessionId: this.clientSessionId,\n });\n this.pending = undefined;\n }\n}\n"],"mappings":";AACO,SAAS,eAAe,MAAkC;AAC9D,MAAI,OAAO,aAAa,YAAa,QAAO;AAE5C,QAAM,UAAU,SAAS,OAAO,MAAM,GAAG;AACzC,aAAW,UAAU,SAAS;AAC3B,UAAM,gBAAgB,OAAO,KAAK;AAClC,UAAM,UAAU,cAAc,QAAQ,GAAG;AACzC,QAAI,YAAY,GAAI;AAEpB,UAAM,aAAa,cAAc,UAAU,GAAG,OAAO;AACrD,UAAM,cAAc,cAAc,UAAU,UAAU,CAAC;AAEvD,QAAI,eAAe,MAAM;AACtB,aAAO;AAAA,IACV;AAAA,EACH;AAEA,SAAO;AACV;AAsBA,SAAS,qBAAqB,OAA6C;AACxE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,IAAI;AACV,SACG,OAAO,EAAE,UAAU,YAAY,OAAO,EAAE,SAAS,YAAY,OAAO,EAAE,YAAY;AAExF;AAIA,SAAS,kBAAkB,QAAuB;AAC/C,UAAQ,KAAK,oBAAoB;AACpC;AAEO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACjC;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA;AAAA,EAEA,YACG,SACA,YACA,QACA,kBACD;AACC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,SAAS;AACd,SAAK,mB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