Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(whatsapp): start new direct chats from contacts or a phone number (#9224)
Wolf Mermelsteinf2b4898c3942
diff --git a/.sqlx/query-0b0a2408eb78dd1867080685a8933769e5c6985759d1986cf9186ea80f30683c.json b/.sqlx/query-0b0a2408eb78dd1867080685a8933769e5c6985759d1986cf9186ea80f30683c.jsonnew file mode 100644index 0000000000..665a851770--- /dev/null+++ b/.sqlx/query-0b0a2408eb78dd1867080685a8933769e5c6985759d1986cf9186ea80f30683c.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT count(*) AS \"count!\" FROM whatsapp_lookup\n WHERE account_id = $1 AND created_at > now() - make_interval(mins => $2)",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Int4"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "0b0a2408eb78dd1867080685a8933769e5c6985759d1986cf9186ea80f30683c"+}diff --git a/.sqlx/query-16b84acaf9ea03605c0a85705d097ec3d2a4602c994c8014628dcba3be2d9254.json b/.sqlx/query-16b84acaf9ea03605c0a85705d097ec3d2a4602c994c8014628dcba3be2d9254.jsonnew file mode 100644index 0000000000..9ca5b4257e--- /dev/null+++ b/.sqlx/query-16b84acaf9ea03605c0a85705d097ec3d2a4602c994c8014628dcba3be2d9254.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE external_chat g SET backfill_state = 'pending'\n FROM UNNEST($2::text[], $3::timestamptz[]) AS i(jid, at)\n WHERE g.user_id = $1 AND g.provider = 'whatsapp' AND g.remote_id = i.jid AND g.state = 'active'\n AND (g.backfill_state = 'waiting_for_message'\n OR (g.kind = 'direct' AND g.backfill_state = 'done' AND g.backfill_imported = 0\n AND g.backfill_cursor IS NULL AND i.at < g.adopted_at))\n RETURNING g.id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "TimestamptzArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "16b84acaf9ea03605c0a85705d097ec3d2a4602c994c8014628dcba3be2d9254"+}diff --git a/.sqlx/query-194744c76fe7241eb04b1065bea357189369075e7e49a90ad03aaec3b95c583a.json b/.sqlx/query-194744c76fe7241eb04b1065bea357189369075e7e49a90ad03aaec3b95c583a.jsonnew file mode 100644index 0000000000..ad519c9e9e--- /dev/null+++ b/.sqlx/query-194744c76fe7241eb04b1065bea357189369075e7e49a90ad03aaec3b95c583a.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM whatsapp_lookup WHERE created_at < now() - make_interval(mins => $1)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int4"+ ]+ },+ "nullable": []+ },+ "hash": "194744c76fe7241eb04b1065bea357189369075e7e49a90ad03aaec3b95c583a"+}diff --git a/.sqlx/query-2516c719bac2a81c5405c4e8d56fc6b19b64435df55290a6b4b1891b756e03c8.json b/.sqlx/query-2516c719bac2a81c5405c4e8d56fc6b19b64435df55290a6b4b1891b756e03c8.jsonnew file mode 100644index 0000000000..2a39353b66--- /dev/null+++ b/.sqlx/query-2516c719bac2a81c5405c4e8d56fc6b19b64435df55290a6b4b1891b756e03c8.json@@ -0,0 +1,42 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id, phone_number, chat_jid,\n CASE WHEN state = 'pending' AND created_at <= now() - make_interval(secs => $3)\n THEN 'failed' ELSE state END AS \"state!\"\n FROM whatsapp_lookup WHERE id = $1 AND account_id = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "phone_number",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "chat_jid",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "state!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Float8"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ null+ ]+ },+ "hash": "2516c719bac2a81c5405c4e8d56fc6b19b64435df55290a6b4b1891b756e03c8"+}diff --git a/.sqlx/query-351f5871d97d6e8cbc309def2c7d5f4d070f960bd3b9b0e9f603c8a053127d7d.json b/.sqlx/query-351f5871d97d6e8cbc309def2c7d5f4d070f960bd3b9b0e9f603c8a053127d7d.jsonnew file mode 100644index 0000000000..c4b893f781--- /dev/null+++ b/.sqlx/query-351f5871d97d6e8cbc309def2c7d5f4d070f960bd3b9b0e9f603c8a053127d7d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM whatsapp_lookup WHERE account_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "351f5871d97d6e8cbc309def2c7d5f4d070f960bd3b9b0e9f603c8a053127d7d"+}diff --git a/.sqlx/query-3f9251885a54cf2a438438c4a487b3cb526f09dc70bc0b1dab6e19ace21d2b90.json b/.sqlx/query-3f9251885a54cf2a438438c4a487b3cb526f09dc70bc0b1dab6e19ace21d2b90.jsondeleted file mode 100644index 6c26172f52..0000000000--- a/.sqlx/query-3f9251885a54cf2a438438c4a487b3cb526f09dc70bc0b1dab6e19ace21d2b90.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "UPDATE external_chat SET backfill_state = 'pending'\n WHERE user_id = $1 AND provider = 'whatsapp' AND remote_id = ANY($2) AND state = 'active'\n AND backfill_state = 'waiting_for_message'\n RETURNING id",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray"- ]- },- "nullable": [- false- ]- },- "hash": "3f9251885a54cf2a438438c4a487b3cb526f09dc70bc0b1dab6e19ace21d2b90"-}diff --git a/.sqlx/query-73bbf1182277a756cfc53fccbc6054452b3849608fb02d7364e1434b2d2b4110.json b/.sqlx/query-73bbf1182277a756cfc53fccbc6054452b3849608fb02d7364e1434b2d2b4110.jsonnew file mode 100644index 0000000000..b2dcc57233--- /dev/null+++ b/.sqlx/query-73bbf1182277a756cfc53fccbc6054452b3849608fb02d7364e1434b2d2b4110.json@@ -0,0 +1,42 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO whatsapp_lookup (id, account_id, phone_number, state)\n VALUES ($1, $2, $3, 'pending')\n RETURNING id, phone_number, state, chat_jid",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "phone_number",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "chat_jid",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true+ ]+ },+ "hash": "73bbf1182277a756cfc53fccbc6054452b3849608fb02d7364e1434b2d2b4110"+}diff --git a/.sqlx/query-af6b9864550e0af119079c65748bbfcc956b26d41e14fcc6c0c681645dc4b5cd.json b/.sqlx/query-af6b9864550e0af119079c65748bbfcc956b26d41e14fcc6c0c681645dc4b5cd.jsonnew file mode 100644index 0000000000..0dcbc06243--- /dev/null+++ b/.sqlx/query-af6b9864550e0af119079c65748bbfcc956b26d41e14fcc6c0c681645dc4b5cd.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id, phone_number FROM whatsapp_lookup\n WHERE account_id = $1 AND state = 'pending'\n AND created_at > now() - make_interval(secs => $2)\n ORDER BY created_at, id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "phone_number",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Float8"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "af6b9864550e0af119079c65748bbfcc956b26d41e14fcc6c0c681645dc4b5cd"+}diff --git a/.sqlx/query-bc499fb4343c751918d50ff3ee7905851eeda322b83c1aafd4b35d5bbf7b9b54.json b/.sqlx/query-bc499fb4343c751918d50ff3ee7905851eeda322b83c1aafd4b35d5bbf7b9b54.jsonnew file mode 100644index 0000000000..0a015f88c5--- /dev/null+++ b/.sqlx/query-bc499fb4343c751918d50ff3ee7905851eeda322b83c1aafd4b35d5bbf7b9b54.json@@ -0,0 +1,42 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id, phone_number, state, chat_jid FROM whatsapp_lookup\n WHERE account_id = $1 AND phone_number = $2 AND state = 'pending'\n AND created_at > now() - make_interval(secs => $3)\n ORDER BY created_at DESC LIMIT 1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "phone_number",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "chat_jid",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Float8"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true+ ]+ },+ "hash": "bc499fb4343c751918d50ff3ee7905851eeda322b83c1aafd4b35d5bbf7b9b54"+}diff --git a/.sqlx/query-ce3c6028020a7520656f55d00c373864657a8c71bbc1b6cd32b9d5d658028966.json b/.sqlx/query-ce3c6028020a7520656f55d00c373864657a8c71bbc1b6cd32b9d5d658028966.jsonnew file mode 100644index 0000000000..2ed6e3d8ab--- /dev/null+++ b/.sqlx/query-ce3c6028020a7520656f55d00c373864657a8c71bbc1b6cd32b9d5d658028966.json@@ -0,0 +1,26 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE whatsapp_lookup SET state = $3, chat_jid = $4, completed_at = now()\n WHERE id = $1 AND account_id = $2 AND state = 'pending'\n AND created_at > now() - make_interval(secs => $5)\n RETURNING id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text",+ "Float8"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "ce3c6028020a7520656f55d00c373864657a8c71bbc1b6cd32b9d5d658028966"+}diff --git a/.sqlx/query-b2bff9a37ede9681c192b928d7a1ede4da01a78ffe74d088c25c9e410090b05d.json b/.sqlx/query-d317c8f7251e33843304f9ef894be916b1ce8a4a527e439adae896802fcc5c82.jsonsimilarity index 87%rename from .sqlx/query-b2bff9a37ede9681c192b928d7a1ede4da01a78ffe74d088c25c9e410090b05d.jsonrename to .sqlx/query-d317c8f7251e33843304f9ef894be916b1ce8a4a527e439adae896802fcc5c82.jsonindex e8f4700844..bd5a39109c 100644--- a/.sqlx/query-b2bff9a37ede9681c192b928d7a1ede4da01a78ffe74d088c25c9e410090b05d.json+++ b/.sqlx/query-d317c8f7251e33843304f9ef894be916b1ce8a4a527e439adae896802fcc5c82.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "INSERT INTO external_chat (id, provider, remote_id, kind, name, user_id, state, share_permission_id, backfill_state)\n VALUES ($1,'whatsapp',$2,$3,$4,$5,'active',$6,\n CASE WHEN EXISTS (SELECT 1 FROM whatsapp_chat WHERE account_id = $7 AND chat_jid = $2 AND anchor IS NOT NULL)\n OR EXISTS (SELECT 1 FROM external_chat_message m JOIN external_chat g ON g.id = m.chat_id\n WHERE g.provider = 'whatsapp' AND g.remote_id = $2 AND m.kind = 'message' AND m.message_id IS NOT NULL\n AND EXISTS (SELECT 1 FROM whatsapp_message_observation o WHERE o.chat_id = m.chat_id\n AND o.person_id = m.person_id AND o.source_id = m.source_id AND o.account_id = $7))\n THEN 'pending' ELSE 'waiting_for_message' END)\n RETURNING id, provider, remote_id, kind, user_id, state, adopted_at",+ "query": "INSERT INTO external_chat (id, provider, remote_id, kind, name, user_id, state, share_permission_id, backfill_state)\n VALUES ($1,'whatsapp',$2,$3,$4,$5,'active',$6,\n CASE WHEN EXISTS (SELECT 1 FROM whatsapp_chat WHERE account_id = $7 AND chat_jid = $2 AND anchor IS NOT NULL)\n OR EXISTS (SELECT 1 FROM external_chat_message m JOIN external_chat g ON g.id = m.chat_id\n WHERE g.provider = 'whatsapp' AND g.remote_id = $2 AND m.kind = 'message' AND m.message_id IS NOT NULL\n AND EXISTS (SELECT 1 FROM whatsapp_message_observation o WHERE o.chat_id = m.chat_id\n AND o.person_id = m.person_id AND o.source_id = m.source_id AND o.account_id = $7))\n THEN 'pending' WHEN $3 = 'direct' THEN 'done' ELSE 'waiting_for_message' END)\n RETURNING id, provider, remote_id, kind, user_id, state, adopted_at","describe": {"columns": [{@@ -60,5 +60,5 @@false]},- "hash": "b2bff9a37ede9681c192b928d7a1ede4da01a78ffe74d088c25c9e410090b05d"+ "hash": "d317c8f7251e33843304f9ef894be916b1ce8a4a527e439adae896802fcc5c82"}diff --git a/.sqlx/query-eae5ce884ee1054ac47f9e1d907f57276c0458ee9d4dead7d9be06409be8dca6.json b/.sqlx/query-eae5ce884ee1054ac47f9e1d907f57276c0458ee9d4dead7d9be06409be8dca6.jsonnew file mode 100644index 0000000000..ef2d944e29--- /dev/null+++ b/.sqlx/query-eae5ce884ee1054ac47f9e1d907f57276c0458ee9d4dead7d9be06409be8dca6.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT state, generation FROM whatsapp_linked_account WHERE id = $1 FOR NO KEY UPDATE",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "generation",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "eae5ce884ee1054ac47f9e1d907f57276c0458ee9d4dead7d9be06409be8dca6"+}diff --git a/apps/web/src/features/whatsapp-linked/AGENTS.md b/apps/web/src/features/whatsapp-linked/AGENTS.mdindex 4303b8feaa..5bb2125fb6 100644--- a/apps/web/src/features/whatsapp-linked/AGENTS.md+++ b/apps/web/src/features/whatsapp-linked/AGENTS.md@@ -21,12 +21,19 @@ own shareable external chat (`POST /external-chats` with `provider:`primitives/open-sections.ts`, per user.- `components/chat-list.tsx`: one-line chat rows styled like Macro's list rows(`bg-list-hover`, actions on hover/focus, always on touch).+- Starting chats: `core/chat.ts` `chatSections` puts saved contacts nobody+ wrote to (direct, no `lastActivityAt`) in `contacts`, shown as the page's+ Contacts section. `components/new-chat-dialog.tsx` takes a number+ (`core/new-chat.ts` normalises it to E.164 and words each+ `NewChatFailure`); the `startChat` capability looks it up+ (`useLookUpWhatsappNumberMutation` polls `GET /whatsapp/lookups/{id}`),+ then adds and opens the chat.- `core/chat.ts`: chat sections, search matching and row wording.## Scope-- Owns: the WhatsApp account page, pairing dialog and one-click add- (no dialog; DSS names the chat after WhatsApp).+- Owns: the WhatsApp account page, pairing dialog, one-click add (no+ dialog; DSS names the chat after WhatsApp) and the New chat dialog.- Chat timeline and sending: `features/external-chat`; channels only reach achat through a mention, which shares it (`MentionsMenu`).- One account at a time: there is no replace flow; switching meansdiff --git a/apps/web/src/features/whatsapp-linked/components/new-chat-dialog.tsx b/apps/web/src/features/whatsapp-linked/components/new-chat-dialog.tsxnew file mode 100644index 0000000000..8ae80bdcef--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/components/new-chat-dialog.tsx@@ -0,0 +1,119 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { ActionDialogShell, Button, Dialog, TextField } from '@ui';+import type { ResultAsync } from 'neverthrow';+import { createSignal } from 'solid-js';+import {+ type NewChatFailure,+ newChatFailureMessage,+ normalizePhoneNumber,+} from '../core/new-chat';++/**+ * Start a direct chat with a phone number that isn't in the chat list:+ * WhatsApp is asked whether it has an account, and a found number's chat is+ * added and opened. Stays open with the reason when it can't.+ */+export function NewChatDialog(props: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onStart: (phoneNumber: string) => ResultAsync<unknown, NewChatFailure>;+}) {+ const [typed, setTyped] = createSignal('');+ const [pending, setPending] = createSignal(false);+ const [failure, setFailure] = createSignal<string>();++ const close = (open: boolean) => {+ if (pending()) return;+ if (!open) {+ setTyped('');+ setFailure(undefined);+ }+ props.onOpenChange(open);+ };++ const submit = async (event: SubmitEvent) => {+ event.preventDefault();+ if (pending()) return;+ const phoneNumber = normalizePhoneNumber(typed());+ if (!phoneNumber) {+ setFailure(newChatFailureMessage({ reason: 'invalid-number' }));+ return;+ }+ setFailure(undefined);+ setPending(true);+ const result = await props.onStart(phoneNumber);+ setPending(false);+ if (result.isErr()) {+ setFailure(newChatFailureMessage(result.error));+ return;+ }+ close(false);+ };++ return (+ <Dialog+ open={props.open}+ onOpenChange={close}+ position="center"+ class="ph-no-capture w-110"+ visibleScrim+ >+ <ActionDialogShell>+ <form+ class="flex min-h-0 flex-col"+ aria-busy={pending()}+ onSubmit={(event) =>+ fireAndForget(submit(event), 'whatsapp-linked.new-chat')+ }+ >+ <ActionDialogShell.Body>+ <ActionDialogShell.Header>+ <ActionDialogShell.Title>+ New WhatsApp chat+ </ActionDialogShell.Title>+ <ActionDialogShell.Description>+ Message anyone on WhatsApp by their phone number.+ </ActionDialogShell.Description>+ </ActionDialogShell.Header>+ <TextField+ value={typed()}+ onChange={(value) => {+ setTyped(value);+ setFailure(undefined);+ }}+ validationState={failure() ? 'invalid' : 'valid'}+ >+ <TextField.Label>Phone number</TextField.Label>+ <TextField.Input+ type="tel"+ inputMode="tel"+ autocomplete="tel"+ placeholder="+ country code and number"+ readOnly={pending()}+ autofocus+ />+ <TextField.ErrorMessage>{failure()}</TextField.ErrorMessage>+ </TextField>+ </ActionDialogShell.Body>+ <ActionDialogShell.Footer>+ <Button+ type="button"+ variant="ghost"+ disabled={pending()}+ onClick={() => close(false)}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ variant="primary"+ disabled={pending() || typed().trim() === ''}+ >+ {pending() ? 'Looking up…' : 'Start chat'}+ </Button>+ </ActionDialogShell.Footer>+ </form>+ </ActionDialogShell>+ </Dialog>+ );+}diff --git a/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx b/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsxindex b3826a68dc..3fab9d3eca 100644--- a/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx+++ b/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx@@ -8,6 +8,7 @@ import {import type { WhatsAppAccount } from '../core/account';import type { AddFailure } from '../core/add';import type { WhatsAppChat } from '../core/chat';+import type { NewChatFailure } from '../core/new-chat';import type { PairingStep, PasskeyChallenge } from '../core/pairing';/** Which collapsible sections of a list are open; unknown ones start open. */@@ -97,6 +98,13 @@ export type WhatsAppLinkedCapabilities = {add: (chat: Pick<WhatsAppChat, 'jid' | 'kind'>) => ResultAsync<{ chatId: string }, AddFailure>;+ /**+ * Start a direct chat with someone not in the chat list: ask WhatsApp+ * whether the number (E.164) has an account, then add that chat.+ */+ startChat: (+ phoneNumber: string+ ) => ResultAsync<{ chatId: string }, NewChatFailure>;isConnecting: Accessor<boolean>;isDisconnecting: Accessor<boolean>;/** Host action: open a chat in Macro. */diff --git a/apps/web/src/features/whatsapp-linked/core/chat.ts b/apps/web/src/features/whatsapp-linked/core/chat.tsindex 51e13703e7..856bd74690 100644--- a/apps/web/src/features/whatsapp-linked/core/chat.ts+++ b/apps/web/src/features/whatsapp-linked/core/chat.ts@@ -32,7 +32,9 @@ export type WhatsAppChat = {kind: 'group' | 'direct';/** WhatsApp's subject or contact name, or DSS's fallback; never empty. */name: string;- /** Newest message WhatsApp reported, when known. */+ /** The other person's number (`+<digits>`) of a direct chat, when known. */+ phoneNumber: string | undefined;+ /** Newest message WhatsApp reported; unknown for contacts never written to. */lastActivityAt: string | undefined;archived: boolean;inMacro: InMacro | undefined;@@ -45,11 +47,16 @@ export type WhatsAppChat = {community?: ChatCommunity;};+/** A saved contact (or looked-up number) nobody has written to yet. */+const isUnwrittenContact = (chat: WhatsAppChat) =>+ chat.kind === 'direct' && !chat.lastActivityAt && !chat.inMacro;+/*** The WhatsApp page's lists, in DSS's recent-activity order. `listed` holds* the chats to add and those shared with the viewer, plus (while searching)* the viewer's own added chats, which otherwise live in External's sidebar.- * `query` keeps the chats whose name matches.+ * `contacts` holds people to start a chat with: saved contacts nobody wrote+ * to yet. `query` keeps the chats whose name or number matches.*/export function chatSections(chats: WhatsAppChat[], query = '') {const searching = query.trim() !== '';@@ -58,8 +65,10 @@ export function chatSections(chats: WhatsAppChat[], query = '') {listed: visible.filter((chat) =>chat.inMacro?.kind === 'own'? searching- : chat.canAdd || chat.inMacro?.kind === 'shared'+ : !isUnwrittenContact(chat) &&+ (chat.canAdd || chat.inMacro?.kind === 'shared')),+ contacts: visible.filter((chat) => isUnwrittenContact(chat) && chat.canAdd),unsupported: visible.filter((chat) => !chat.inMacro && !chat.canAdd && !!chat.cannotAddReason),@@ -130,7 +139,12 @@ export function matchesChatQuery(chat: WhatsAppChat, query: string): boolean {if (fold(communityTitle(chat.name, chat.community)).includes(wanted))return true;const digits = wanted.replace(/[\s()+-]/g, '');- return /^\d+$/.test(digits) && chat.name.replace(/\D/g, '').includes(digits);+ return (+ /^\d+$/.test(digits) &&+ [chat.name, chat.phoneNumber ?? ''].some((text) =>+ text.replace(/\D/g, '').includes(digits)+ )+ );}/** Why a chat can't be added to Macro, as DSS reports it. */@@ -163,7 +177,10 @@ export function cannotAddLabel(chat: WhatsAppChat): string | undefined {: undefined;}-/** "Group", "Direct chat · Archived"; the row shows last activity apart. */+/**+ * "Group", "Direct chat · +351 …" (the number when the name isn't it),+ * "Direct chat · Archived"; the row shows last activity apart.+ */export function chatMetadata(chat: WhatsAppChat): string {return [chat.kind === 'direct'@@ -173,6 +190,7 @@ export function chatMetadata(chat: WhatsAppChat): string {: chat.community? 'Community group': 'Group',+ chat.phoneNumber !== chat.name ? chat.phoneNumber : undefined,chat.archived ? 'Archived' : undefined,].filter(Boolean)diff --git a/apps/web/src/features/whatsapp-linked/core/new-chat.test.ts b/apps/web/src/features/whatsapp-linked/core/new-chat.test.tsnew file mode 100644index 0000000000..b57511a5fe--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/core/new-chat.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest';+import { chatSections, type WhatsAppChat } from './chat';+import { normalizePhoneNumber } from './new-chat';++describe('normalizePhoneNumber', () => {+ it('accepts international numbers however they are spaced', () => {+ expect(normalizePhoneNumber('+5550001')).toBe('+5550001');+ expect(normalizePhoneNumber(' +555 000 1 ')).toBe('+5550001');+ expect(normalizePhoneNumber('+555-00.01')).toBe('+5550001');+ expect(normalizePhoneNumber('+(555) 0001')).toBe('+5550001');+ expect(normalizePhoneNumber('00 555 0001')).toBe('+5550001');+ });++ it('refuses numbers without a country code or of the wrong length', () => {+ expect(normalizePhoneNumber('555 0001')).toBeUndefined();+ expect(normalizePhoneNumber('+0555001')).toBeUndefined();+ expect(normalizePhoneNumber('+555001')).toBeUndefined();+ expect(normalizePhoneNumber(`+${'1'.repeat(16)}`)).toBeUndefined();+ expect(normalizePhoneNumber('+555 0001 ext 2')).toBeUndefined();+ expect(normalizePhoneNumber('')).toBeUndefined();+ });+});++describe('chatSections', () => {+ const direct = {+ kind: 'direct' as const,+ archived: false,+ inMacro: undefined,+ canAdd: true,+ cannotAddReason: undefined,+ };+ const recent: WhatsAppChat = {+ ...direct,+ jid: 'recent',+ name: 'Ana Ruiz',+ phoneNumber: '+5550001',+ lastActivityAt: '2025-03-07T10:00:00Z',+ };+ const contact: WhatsAppChat = {+ ...direct,+ jid: 'contact',+ name: 'Dana Smith',+ phoneNumber: '+5550002',+ lastActivityAt: undefined,+ };+ const added: WhatsAppChat = {+ ...contact,+ jid: 'added',+ name: 'Eve Adams',+ inMacro: { kind: 'own', chatId: 'chat-eve' },+ canAdd: false,+ };++ it('lists contacts nobody wrote to apart from recent chats', () => {+ const sections = chatSections([recent, contact, added]);+ expect(sections.listed.map((chat) => chat.jid)).toEqual(['recent']);+ expect(sections.contacts.map((chat) => chat.jid)).toEqual(['contact']);+ });++ it('finds a contact by name or by number', () => {+ expect(chatSections([recent, contact], 'dana').contacts).toEqual([contact]);+ expect(chatSections([recent, contact], '555 0002').contacts).toEqual([+ contact,+ ]);+ expect(chatSections([recent, contact], '555 0002').listed).toEqual([]);+ });+});diff --git a/apps/web/src/features/whatsapp-linked/core/new-chat.ts b/apps/web/src/features/whatsapp-linked/core/new-chat.tsnew file mode 100644index 0000000000..02fee4c4fe--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/core/new-chat.ts@@ -0,0 +1,54 @@+import { match } from 'ts-pattern';+import { type AddRefusal, addFailureMessage } from './add';++/** WhatsApp numbers: a country code first, 7 to 15 digits in all. */+const E164 = /^\+[1-9]\d{6,14}$/;++/**+ * A typed phone number in E.164 (`+<country code><number>`), ignoring+ * spaces, dashes, dots and brackets; `00` counts as `+`. Undefined when it+ * isn't a full international number.+ */+export function normalizePhoneNumber(typed: string): string | undefined {+ const compact = typed.trim().replace(/[\s().-]/g, '');+ const international = compact.startsWith('00')+ ? `+${compact.slice(2)}`+ : compact;+ return E164.test(international) ? international : undefined;+}++/** Why starting a chat with a number did not open one. */+export type NewChatFailure =+ | { reason: 'invalid-number' }+ | { reason: 'not-on-whatsapp'; phoneNumber: string }+ /** WhatsApp did not answer in time, or the connection is down. */+ | { reason: 'no-answer' }+ | { reason: 'lookup-refused'; refusal: AddRefusal }+ | { reason: 'add-refused'; refusal: AddRefusal };++/** Specific words for each failure; never a catch-all. */+export function newChatFailureMessage(failure: NewChatFailure): string {+ return match(failure)+ .with(+ { reason: 'invalid-number' },+ () => 'Enter the full number, starting with + and the country code.'+ )+ .with(+ { reason: 'not-on-whatsapp' },+ ({ phoneNumber }) => `${phoneNumber} isn't on WhatsApp.`+ )+ .with(+ { reason: 'no-answer' },+ () =>+ "WhatsApp didn't answer. Check that your phone is online, then try again."+ )+ .with(+ { reason: 'lookup-refused', refusal: { reason: 'rate-limited' } },+ () =>+ "You've looked up many numbers recently. WhatsApp blocks accounts that check too many, so try again in an hour."+ )+ .with({ reason: 'lookup-refused' }, { reason: 'add-refused' }, (failed) =>+ addFailureMessage(failed.refusal)+ )+ .exhaustive();+}diff --git a/apps/web/src/features/whatsapp-linked/queries/decode.ts b/apps/web/src/features/whatsapp-linked/queries/decode.tsindex 470d127e34..de827a7f91 100644--- a/apps/web/src/features/whatsapp-linked/queries/decode.ts+++ b/apps/web/src/features/whatsapp-linked/queries/decode.ts@@ -29,6 +29,7 @@ export function decodeChat(jid: chat.jid,kind: chat.kind,name: chat.name,+ phoneNumber: chat.phoneNumber ?? undefined,lastActivityAt: chat.lastActivityAt ?? undefined,archived: chat.archived,inMacro: chat.addeddiff --git a/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts b/apps/web/src/features/whatsapp-linked/queries/production-capabilities.tsindex 4a4bb72430..3e60d497ac 100644--- a/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts+++ b/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts@@ -10,6 +10,7 @@ import {useCancelWhatsappPairingMutation,useConnectWhatsappMutation,useDisconnectWhatsappMutation,+ useLookUpWhatsappNumberMutation,useSubmitWhatsappPasskeyMutation,useWhatsappLinkedAccountQuery,useWhatsappLinkedChatsQuery,@@ -17,8 +18,9 @@ import {} from '@queries/whatsapp-linked';import { type LoadResult, traceLoad } from '@queries/whatsapp-linked/operation';import type { UseQueryResult } from '@tanstack/solid-query';-import { ResultAsync } from 'neverthrow';+import { err, ok, type Result, ResultAsync } from 'neverthrow';import { type Accessor, createMemo, createSignal } from 'solid-js';+import { match, P } from 'ts-pattern';import type {OpenSections,PasskeyCapability,@@ -29,6 +31,7 @@ import type {import { accountStatus, type WhatsAppAccount } from '../core/account';import type { AddFailure } from '../core/add';import type { WhatsAppChat } from '../core/chat';+import type { NewChatFailure } from '../core/new-chat';import {authenticateWhatsAppPasskey,canAuthenticatePasskey,@@ -99,6 +102,7 @@ export function createWhatsAppLinkedCapabilities(host: {const disconnect = useDisconnectWhatsappMutation();const cancel = useCancelWhatsappPairingMutation();const add = useAddWhatsappChatMutation();+ const lookUp = useLookUpWhatsappNumberMutation();const submitPasskey = useSubmitWhatsappPasskeyMutation();const passkey: PasskeyCapability = canAuthenticatePasskey()? {@@ -170,6 +174,35 @@ export function createWhatsAppLinkedCapabilities(host: {...decodeAddRefusal(error),})).map((added) => ({ chatId: added.chatId })),+ startChat: (phoneNumber) =>+ ResultAsync.fromPromise(+ lookUp.mutateAsync(phoneNumber),+ (error): NewChatFailure => ({+ reason: 'lookup-refused',+ refusal: decodeAddRefusal(error),+ })+ )+ .andThen((lookup) =>+ match(lookup)+ .returnType<Result<string, NewChatFailure>>()+ .with({ state: 'found', chatJid: P.string }, ({ chatJid }) =>+ ok(chatJid)+ )+ .with({ state: 'not_on_whatsapp' }, () =>+ err({ reason: 'not-on-whatsapp', phoneNumber })+ )+ .otherwise(() => err({ reason: 'no-answer' }))+ )+ .andThen((jid) =>+ ResultAsync.fromPromise(+ add.mutateAsync({ jid, kind: 'direct' }),+ (error): NewChatFailure => ({+ reason: 'add-refused',+ refusal: decodeAddRefusal(error),+ })+ )+ )+ .map((added) => ({ chatId: added.chatId })),isConnecting: () => connect.isPending,isDisconnecting: () => disconnect.isPending,openChat: host.openChat,diff --git a/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts b/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.tsindex 4476ea2e82..6e05d0e9af 100644--- a/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts+++ b/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts@@ -11,6 +11,7 @@ import type {import type { WhatsAppAccount } from '../core/account';import type { AddFailure } from '../core/add';import type { WhatsAppChat } from '../core/chat';+import type { NewChatFailure } from '../core/new-chat';import type { PairingStep } from '../core/pairing';import { createOpenSections } from '../primitives/open-sections';@@ -119,6 +120,10 @@ export function createFakeWhatsApp(initial: {): ResultAsync<{ chatId: string }, AddFailure> =>okAsync({ chatId: 'chat-new' })),+ startChat: vi.fn(+ (_phoneNumber: string): ResultAsync<{ chatId: string }, NewChatFailure> =>+ okAsync({ chatId: 'chat-started' })+ ),isConnecting: () => false,isDisconnecting: () => false,openChat: vi.fn(),diff --git a/apps/web/src/features/whatsapp-linked/views/new-chat.test.tsx b/apps/web/src/features/whatsapp-linked/views/new-chat.test.tsxnew file mode 100644index 0000000000..e01eb35bbc--- /dev/null+++ b/apps/web/src/features/whatsapp-linked/views/new-chat.test.tsx@@ -0,0 +1,170 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@solidjs/testing-library';+import { errAsync } from 'neverthrow';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { WhatsAppLinkedProvider } from '../context/whatsapp-linked-context';+import type { WhatsAppChat } from '../core/chat';+import { createFakeWhatsApp } from '../tests/fake-capabilities';+import { WhatsAppPage } from './whatsapp-page';++vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: vi.fn(), failure: vi.fn() },+}));++beforeEach(() => {+ vi.stubGlobal('scrollTo', vi.fn());+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe = vi.fn();+ unobserve = vi.fn();+ disconnect = vi.fn();+ }+ );+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ vi.unstubAllGlobals();+});++const direct = {+ kind: 'direct' as const,+ archived: false,+ inMacro: undefined,+ canAdd: true,+ cannotAddReason: undefined,+};++/** DSS's order: recent chats first, contacts nobody wrote to last. */+const chats: WhatsAppChat[] = [+ {+ ...direct,+ jid: 'ana',+ name: 'Ana Ruiz',+ phoneNumber: '+5550001',+ lastActivityAt: '2025-03-07T10:00:00Z',+ },+ {+ ...direct,+ jid: 'dana',+ name: 'Dana Smith',+ phoneNumber: '+5550002',+ lastActivityAt: undefined,+ },+ {+ ...direct,+ jid: 'eve',+ name: '+5550003',+ phoneNumber: '+5550003',+ lastActivityAt: undefined,+ },+];++function mount() {+ const fake = createFakeWhatsApp({+ account: { generation: 3, phone: '+5550009', health: 'connected' },+ chats,+ });+ render(() => (+ <WhatsAppLinkedProvider value={fake.capabilities}>+ <WhatsAppPage />+ </WhatsAppLinkedProvider>+ ));+ return fake;+}++describe('contacts', () => {+ it('lists saved contacts nobody wrote to below recent chats, with their numbers', () => {+ const fake = mount();+ const recent = within(+ screen.getByRole('list', { name: 'Direct messages' })+ );+ expect(recent.getAllByRole('listitem')).toHaveLength(1);+ const contacts = within(screen.getByRole('list', { name: 'Contacts' }));+ expect(+ contacts.getAllByRole('listitem').map((row) => row.textContent)+ ).toEqual([+ 'Dana SmithDirect chat · +5550002Add to Macro',+ '+5550003Direct chatAdd to Macro',+ ]);++ fireEvent.click(+ contacts.getAllByRole('button', { name: 'Add to Macro' })[0]+ );+ expect(fake.capabilities.add).toHaveBeenCalledWith(chats[1]);+ });++ it('finds contacts by number', () => {+ mount();+ fireEvent.input(screen.getByRole('searchbox'), {+ target: { value: '555 0002' },+ });+ expect(screen.queryByRole('list', { name: 'Direct messages' })).toBeNull();+ expect(+ within(screen.getByRole('list', { name: 'Contacts' }))+ .getAllByRole('listitem')+ .map((row) => row.textContent)+ ).toEqual(['Dana SmithDirect chat · +5550002Add to Macro']);+ });+});++describe('new chat', () => {+ it('starts a chat with a typed number and opens it', async () => {+ const fake = mount();+ fireEvent.click(screen.getByRole('button', { name: 'New chat' }));+ const dialog = within(await screen.findByRole('dialog'));+ fireEvent.input(dialog.getByLabelText('Phone number'), {+ target: { value: '+555 000 7' },+ });+ fireEvent.click(dialog.getByRole('button', { name: 'Start chat' }));++ await waitFor(() =>+ expect(fake.capabilities.openChat).toHaveBeenCalledWith('chat-started')+ );+ expect(fake.capabilities.startChat).toHaveBeenCalledWith('+5550007');+ });++ it('says why a number did not start a chat and stays open', async () => {+ const fake = mount();+ fireEvent.click(screen.getByRole('button', { name: 'New chat' }));+ const dialog = within(await screen.findByRole('dialog'));+ const field = dialog.getByLabelText('Phone number');++ fireEvent.input(field, { target: { value: '555 0007' } });+ fireEvent.click(dialog.getByRole('button', { name: 'Start chat' }));+ expect(+ await dialog.findByText(+ 'Enter the full number, starting with + and the country code.'+ )+ ).toBeTruthy();+ expect(fake.capabilities.startChat).not.toHaveBeenCalled();++ fake.capabilities.startChat.mockReturnValueOnce(+ errAsync({ reason: 'not-on-whatsapp', phoneNumber: '+5550007' })+ );+ fireEvent.input(field, { target: { value: '+5550007' } });+ fireEvent.click(dialog.getByRole('button', { name: 'Start chat' }));+ expect(await dialog.findByText("+5550007 isn't on WhatsApp.")).toBeTruthy();+ expect(fake.capabilities.openChat).not.toHaveBeenCalled();++ fake.capabilities.startChat.mockReturnValueOnce(+ errAsync({+ reason: 'lookup-refused',+ refusal: { reason: 'rate-limited' },+ })+ );+ fireEvent.click(dialog.getByRole('button', { name: 'Start chat' }));+ expect(+ await dialog.findByText(/looked up many numbers recently/)+ ).toBeTruthy();+ });+});diff --git a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsxindex ac3ccd8b6e..70cb0b08c2 100644--- a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx@@ -70,6 +70,7 @@ const launch = (announcements: boolean) => ({const chat = {kind: 'group' as const,+ phoneNumber: undefined,lastActivityAt: undefined,archived: false,inMacro: undefined,@@ -469,6 +470,7 @@ describe('connected', () => {jid: '[email protected]',kind: 'direct' as const,name: '+1 415-555-0123',+ lastActivityAt: '2025-03-04T10:00:00Z',canAdd: false,cannotAddReason: 'not_in_chat_list' as const,},@@ -505,7 +507,11 @@ describe('connected', () => {expect(screen.queryByText('Ana Ruiz')).toBeNull();fireEvent.input(search, { target: { value: 'nothing like it' } });- expect(screen.getByText('No chats to add match your search.')).toBeTruthy();+ expect(+ screen.getByText(+ 'No chats or contacts match your search. To message someone else, start a new chat with their number.'+ )+ ).toBeTruthy();});it('adds a group in one click, without a dialog', async () => {@@ -533,6 +539,7 @@ describe('connected', () => {jid: '[email protected]',kind: 'direct' as const,name: 'Ben Ode',+ lastActivityAt: '2025-03-04T10:00:00Z',},],});@@ -575,6 +582,7 @@ describe('connected', () => {jid: '[email protected]',kind: 'direct' as const,name: 'Ben Ode',+ lastActivityAt: '2025-03-04T10:00:00Z',},{...chat,diff --git a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsxindex 82acfdae35..f551ebad18 100644--- a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx@@ -3,12 +3,17 @@ import { ViewSkeleton } from '@app/components/view-shell/ViewSkeleton';import { toast } from '@core/component/Toast/Toast';import { isMobile } from '@core/mobile/isMobile';import { fireAndForget } from '@core/util/fireAndForget';+import NotePencilIcon from '@phosphor/note-pencil.svg';import { Button, ConfirmDialog } from '@ui';import { createSignal, Match, onMount, Show, Switch } from 'solid-js';import { match } from 'ts-pattern';import { AccountStrip, ConnectCard } from '../components/account-card';import { ChatList, UnsupportedChatList } from '../components/chat-list';-import { ConversationSectionList } from '../components/conversation-sections';+import {+ ConversationSection,+ ConversationSectionList,+} from '../components/conversation-sections';+import { NewChatDialog } from '../components/new-chat-dialog';import { PairingDialog, type PasskeyMode } from '../components/pairing-dialog';import { useWhatsAppLinked } from '../context/whatsapp-linked-context';import { accountStatus } from '../core/account';@@ -20,6 +25,9 @@ import {} from '../core/chat';import { createPairingFlow } from '../primitives/pairing-flow';+/** The Contacts section's id for its remembered open state. */+const CONTACTS_SECTION = 'contacts';+function Notice(props: { children: string }) {return (<p role="alert" class="text-sm text-ink-muted">@@ -87,6 +95,7 @@ export function WhatsAppPage(props: {.exhaustive();};const [confirmingDisconnect, setConfirmingDisconnect] = createSignal(false);+ const [startingChat, setStartingChat] = createSignal(false);const [adding, setAdding] = createSignal<ReadonlySet<string>>(new Set());const [addErrors, setAddErrors] = createSignal<Record<string, string>>({});@@ -146,14 +155,26 @@ export function WhatsAppPage(props: {{(current) => (<><div class="sticky top-0 z-10 flex flex-col gap-2 bg-panel px-4 pt-4 pb-1 touch:static">- <div class="flex min-w-0 items-center gap-3 touch:flex-col-reverse touch:items-stretch">- <SearchBar- label="Search WhatsApp chats"- placeholder="Search chats"- value={query()}- onValueChange={setQuery}- class="max-w-md flex-1 touch:max-w-none"- />+ <div class="flex min-w-0 flex-wrap items-center gap-3 touch:flex-col-reverse touch:flex-nowrap touch:items-stretch">+ <div class="flex min-w-64 max-w-md flex-1 items-center gap-2 touch:min-w-0 touch:max-w-none">+ <SearchBar+ label="Search WhatsApp chats"+ placeholder="Search chats and contacts"+ value={query()}+ onValueChange={setQuery}+ class="min-w-0 flex-1"+ />+ <Button+ type="button"+ variant="secondary"+ size="sm"+ aria-label="New chat"+ onClick={() => setStartingChat(true)}+ >+ <NotePencilIcon class="size-3.5" />+ <span class="mobile:hidden">New chat</span>+ </Button>+ </div><div class="ml-auto min-w-0 touch:ml-0"><AccountStripaccount={current().account}@@ -201,10 +222,46 @@ export function WhatsAppPage(props: {)}/></div>- <Show when={!sections().listed.length}>+ <Show when={sections().contacts.length}>+ <div class="px-2 pt-(--sidebar-section-gap)">+ <ConversationSection+ title="Contacts"+ open={+ searching() ||+ whatsapp.sections.isOpen(CONTACTS_SECTION)+ }+ onOpenChange={(open) =>+ whatsapp.sections.setOpen(+ CONTACTS_SECTION,+ open+ )+ }+ >+ <ChatList+ label="Contacts"+ chats={sections().contacts}+ adding={adding()}+ errors={addErrors()}+ onAdd={(chat) =>+ fireAndForget(+ add(chat),+ 'whatsapp-linked.add'+ )+ }+ onOpenChat={whatsapp.openChat}+ />+ </ConversationSection>+ </div>+ </Show>+ <Show+ when={+ !sections().listed.length &&+ !sections().contacts.length+ }+ ><p class="px-4 py-2 text-sm text-ink-extra-muted">{searching()- ? 'No chats to add match your search.'+ ? 'No chats or contacts match your search. To message someone else, start a new chat with their number.': 'Every WhatsApp chat you can add is already in Macro.'}</p></Show>@@ -225,6 +282,15 @@ export function WhatsAppPage(props: {<LoadFailure what="your chats" onRetry={chats.refetch} /></Match></Switch>+ <NewChatDialog+ open={startingChat()}+ onOpenChange={setStartingChat}+ onStart={(phoneNumber) =>+ .startChat(phoneNumber)+ .map(({ chatId }) => whatsapp.openChat(chatId))+ }+ /><ConfirmDialogopen={confirmingDisconnect()}onOpenChange={setConfirmingDisconnect}diff --git a/apps/web/src/lib/queries/whatsapp-linked/index.ts b/apps/web/src/lib/queries/whatsapp-linked/index.tsindex ca5a2fd002..4c5315a677 100644--- a/apps/web/src/lib/queries/whatsapp-linked/index.ts+++ b/apps/web/src/lib/queries/whatsapp-linked/index.ts@@ -1,4 +1,5 @@import { throwOnErr } from '@core/util/result';+import { sleep } from '@core/util/sleep';import { externalChatsClient } from '@service-storage/external-chats';import type { ExternalChatKind } from '@service-storage/generated/schemas/externalChatKind';import type { WhatsappPasskeyBody } from '@service-storage/generated/schemas/whatsappPasskeyBody';@@ -13,6 +14,9 @@ import { whatsappOperation } from './operation';/** How often an open pairing dialog asks for a rotated QR or a result. */export const PAIRING_POLL_MS = 1500;+/** How often a phone-number lookup is read until WhatsApp answers. */+export const LOOKUP_POLL_MS = 1000;+function accountOptions(userId: string) {return queryOptions({queryKey: whatsappLinkedKeys.account(userId).queryKey,@@ -116,6 +120,28 @@ export function useSubmitWhatsappPasskeyMutation() {}));}+/**+ * Asks WhatsApp whether a number has an account and waits for the answer+ * (DSS fails a lookup WhatsApp leaves unanswered). A found number joins the+ * chat list.+ */+export function useLookUpWhatsappNumberMutation() {+ return useMutation(() => ({+ mutationFn: (phoneNumber: string) =>+ whatsappOperation('lookup', async () => {+ let lookup = await throwOnErr(() => client.startLookup(phoneNumber));+ while (lookup.state === 'pending') {+ await sleep(LOOKUP_POLL_MS);+ const id = lookup.id;+ lookup = await throwOnErr(() => client.lookup(id));+ }+ return lookup;+ }),+ onSuccess: (lookup) =>+ lookup.state === 'found' ? invalidateChats() : undefined,+ }));+}+/** Adds one of the account's WhatsApp chats to Macro as an external chat. */export function useAddWhatsappChatMutation() {return useMutation(() => ({diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 87571643a8..688bb2b438 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -2329,11 +2329,16 @@ export * from './whatsAppChatAdded';export * from './whatsAppChatCannotAddReason';export * from './whatsAppChatCommunity';export * from './whatsAppChatLastActivityAt';+export * from './whatsAppChatPhoneNumber';export * from './whatsAppChatShared';export * from './whatsAppChats';export * from './whatsAppConnect';export * from './whatsAppDisconnect';export * from './whatsAppDisconnectRequest';+export * from './whatsAppLookup';+export * from './whatsAppLookupChatJid';+export * from './whatsAppLookupRequest';+export * from './whatsAppLookupState';export * from './whatsAppPairing';export * from './whatsAppPairingState';export * from './whatsAppPairState';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChat.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChat.tsindex bd1209396c..a85bfc05cf 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChat.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChat.ts@@ -10,6 +10,7 @@ import type { WhatsAppChatAdded } from './whatsAppChatAdded';import type { WhatsAppChatCannotAddReason } from './whatsAppChatCannotAddReason';import type { WhatsAppChatCommunity } from './whatsAppChatCommunity';import type { WhatsAppChatLastActivityAt } from './whatsAppChatLastActivityAt';+import type { WhatsAppChatPhoneNumber } from './whatsAppChatPhoneNumber';import type { WhatsAppChatShared } from './whatsAppChatShared';/**@@ -29,11 +30,15 @@ export interface WhatsAppChat {/** Group or direct chat. */kind: ExternalChatKind;/** Newest activity WhatsApp reported (message or history sync); `null`-when unknown. The list is sorted by it, newest first, unknown last. */+when unknown, as for saved contacts never messaged. The list is+sorted by it, newest first, unknown last. */lastActivityAt?: WhatsAppChatLastActivityAt;/** Group: the subject, or member names for an unnamed group. Direct: thecontact or WhatsApp name, else `+<phone>`. Always non-empty. */name: string;+ /** The other person's phone number (`+<digits>`) of a direct chat, when+WhatsApp told us it. */+ phoneNumber?: WhatsAppChatPhoneNumber;/** Pinned in WhatsApp. */pinned: boolean;shared?: WhatsAppChatShared;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChatLastActivityAt.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChatLastActivityAt.tsindex edeebff6c3..218be09e3e 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChatLastActivityAt.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChatLastActivityAt.ts@@ -7,6 +7,7 @@/*** Newest activity WhatsApp reported (message or history sync); `null`-when unknown. The list is sorted by it, newest first, unknown last.+when unknown, as for saved contacts never messaged. The list is+sorted by it, newest first, unknown last.*/export type WhatsAppChatLastActivityAt = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChatPhoneNumber.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChatPhoneNumber.tsnew file mode 100644index 0000000000..2dd8b9cfb8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppChatPhoneNumber.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The other person's phone number (`+<digits>`) of a direct chat, when+WhatsApp told us it.+ */+export type WhatsAppChatPhoneNumber = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookup.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookup.tsnew file mode 100644index 0000000000..407aee2c19--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookup.ts@@ -0,0 +1,23 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { WhatsAppLookupChatJid } from './whatsAppLookupChatJid';+import type { WhatsAppLookupState } from './whatsAppLookupState';++/**+ * The owner asking whether a phone number has a WhatsApp account, to start+a direct chat with it.+ */+export interface WhatsAppLookup {+ /** Found: the direct chat's JID, now addable from the chat list. */+ chatJid?: WhatsAppLookupChatJid;+ /** Poll `GET /whatsapp/lookups/{id}` with it. */+ id: string;+ /** The number asked about, E.164 (`+<digits>`). */+ phoneNumber: string;+ /** Progress. */+ state: WhatsAppLookupState;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookupChatJid.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookupChatJid.tsnew file mode 100644index 0000000000..8329035662--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookupChatJid.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Found: the direct chat's JID, now addable from the chat list.+ */+export type WhatsAppLookupChatJid = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookupRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookupRequest.tsnew file mode 100644index 0000000000..650d70e8f9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookupRequest.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * A phone number to start a direct chat with.+ */+export interface WhatsAppLookupRequest {+ /** E.164: `+`, the country code and the number, without spacing. */+ phoneNumber: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookupState.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookupState.tsnew file mode 100644index 0000000000..df029030d9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppLookupState.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Where a phone-number lookup is.+ */+export type WhatsAppLookupState =+ (typeof WhatsAppLookupState)[keyof typeof WhatsAppLookupState];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const WhatsAppLookupState = {+ pending: 'pending',+ found: 'found',+ not_on_whatsapp: 'not_on_whatsapp',+ failed: 'failed',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex afc7668c6d..c1ff1d538f 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -59045,13 +59045,19 @@ export const whatsappChatsResponse = zod.datetime({}).nullish().describe(- 'Newest activity WhatsApp reported (message or history sync); `null`\nwhen unknown. The list is sorted by it, newest first, unknown last.'+ 'Newest activity WhatsApp reported (message or history sync); `null`\nwhen unknown, as for saved contacts never messaged. The list is\nsorted by it, newest first, unknown last.'),name: zod.string().describe('Group: the subject, or member names for an unnamed group. Direct: the\ncontact or WhatsApp name, else `+<phone>`. Always non-empty.'),+ phoneNumber: zod+ .string()+ .nullish()+ .describe(+ "The other person's phone number (`+<digits>`) of a direct chat, when\nWhatsApp told us it."+ ),pinned: zod.boolean().describe('Pinned in WhatsApp.'),shared: zod.union([@@ -59138,6 +59144,68 @@ export const whatsappDisconnectResponse = zod}).describe('Result of disconnecting an account.');+/**+ * @summary Ask whether a phone number has a WhatsApp account, to start a direct chat+with it; poll the lookup until it is no longer `pending`. Found numbers+join the chat list, so `POST /external-chats` adds them.+ */+export const whatsappStartLookupBody = zod+ .object({+ phoneNumber: zod+ .string()+ .describe(+ 'E.164: `+`, the country code and the number, without spacing.'+ ),+ })+ .describe('A phone number to start a direct chat with.');++export const whatsappStartLookupResponse = zod+ .object({+ chatJid: zod+ .string()+ .nullish()+ .describe(+ "Found: the direct chat's JID, now addable from the chat list."+ ),+ id: zod.uuid().describe('Poll `GET \/whatsapp\/lookups\/{id}` with it.'),+ phoneNumber: zod+ .string()+ .describe('The number asked about, E.164 (`+<digits>`).'),+ state: zod+ .enum(['pending', 'found', 'not_on_whatsapp', 'failed'])+ .describe('Where a phone-number lookup is.'),+ })+ .describe(+ 'The owner asking whether a phone number has a WhatsApp account, to start\na direct chat with it.'+ );++/**+ * @summary Poll the caller's phone-number lookup.+ */+export const whatsappLookupParams = zod.object({+ id: zod.uuid(),+});++export const whatsappLookupResponse = zod+ .object({+ chatJid: zod+ .string()+ .nullish()+ .describe(+ "Found: the direct chat's JID, now addable from the chat list."+ ),+ id: zod.uuid().describe('Poll `GET \/whatsapp\/lookups\/{id}` with it.'),+ phoneNumber: zod+ .string()+ .describe('The number asked about, E.164 (`+<digits>`).'),+ state: zod+ .enum(['pending', 'found', 'not_on_whatsapp', 'failed'])+ .describe('Where a phone-number lookup is.'),+ })+ .describe(+ 'The owner asking whether a phone number has a WhatsApp account, to start\na direct chat with it.'+ );+/*** @summary Poll the caller's pairing transaction, including its current QR code.*/diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex fe321da710..1dc3365b7c 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -19464,6 +19464,65 @@}}},+ "/whatsapp/lookups": {+ "post": {+ "tags": ["whatsapp_linked::inbound::router"],+ "summary": "Ask whether a phone number has a WhatsApp account, to start a direct chat\nwith it; poll the lookup until it is no longer `pending`. Found numbers\njoin the chat list, so `POST /external-chats` adds them.",+ "operationId": "whatsapp_start_lookup",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WhatsAppLookupRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WhatsAppLookup"+ }+ }+ }+ }+ }+ }+ },+ "/whatsapp/lookups/{id}": {+ "get": {+ "tags": ["whatsapp_linked::inbound::router"],+ "summary": "Poll the caller's phone-number lookup.",+ "operationId": "whatsapp_lookup",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WhatsAppLookup"+ }+ }+ }+ }+ }+ }+ },"/whatsapp/pairing/{id}": {"get": {"tags": ["whatsapp_linked::inbound::router"],@@ -45437,12 +45496,16 @@"lastActivityAt": {"type": ["string", "null"],"format": "date-time",- "description": "Newest activity WhatsApp reported (message or history sync); `null`\nwhen unknown. The list is sorted by it, newest first, unknown last."+ "description": "Newest activity WhatsApp reported (message or history sync); `null`\nwhen unknown, as for saved contacts never messaged. The list is\nsorted by it, newest first, unknown last."},"name": {"type": "string","description": "Group: the subject, or member names for an unnamed group. Direct: the\ncontact or WhatsApp name, else `+<phone>`. Always non-empty."},+ "phoneNumber": {+ "type": ["string", "null"],+ "description": "The other person's phone number (`+<digits>`) of a direct chat, when\nWhatsApp told us it."+ },"pinned": {"type": "boolean","description": "Pinned in WhatsApp."@@ -45507,6 +45570,46 @@}}},+ "WhatsAppLookup": {+ "type": "object",+ "description": "The owner asking whether a phone number has a WhatsApp account, to start\na direct chat with it.",+ "required": ["id", "phoneNumber", "state"],+ "properties": {+ "chatJid": {+ "type": ["string", "null"],+ "description": "Found: the direct chat's JID, now addable from the chat list."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Poll `GET /whatsapp/lookups/{id}` with it."+ },+ "phoneNumber": {+ "type": "string",+ "description": "The number asked about, E.164 (`+<digits>`)."+ },+ "state": {+ "$ref": "#/components/schemas/WhatsAppLookupState",+ "description": "Progress."+ }+ }+ },+ "WhatsAppLookupRequest": {+ "type": "object",+ "description": "A phone number to start a direct chat with.",+ "required": ["phoneNumber"],+ "properties": {+ "phoneNumber": {+ "type": "string",+ "description": "E.164: `+`, the country code and the number, without spacing."+ }+ }+ },+ "WhatsAppLookupState": {+ "type": "string",+ "description": "Where a phone-number lookup is.",+ "enum": ["pending", "found", "not_on_whatsapp", "failed"]+ },"WhatsAppPairState": {"type": "object","description": "Owner-only pairing status. Deliberately has no `Debug` implementation: the\nQR and pairing code are secrets for the duration of the transaction.",diff --git a/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts b/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.tsindex d44b10bcd0..fa05bdd6c4 100644--- a/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts+++ b/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts@@ -6,6 +6,8 @@ import type { WhatsAppAccountView } from './generated/schemas/whatsAppAccountVieimport type { WhatsAppChats } from './generated/schemas/whatsAppChats';import type { WhatsAppDisconnect } from './generated/schemas/whatsAppDisconnect';import type { WhatsAppDisconnectRequest } from './generated/schemas/whatsAppDisconnectRequest';+import type { WhatsAppLookup } from './generated/schemas/whatsAppLookup';+import type { WhatsAppLookupRequest } from './generated/schemas/whatsAppLookupRequest';import type { WhatsAppPairing } from './generated/schemas/whatsAppPairing';import type { WhatsAppPairState } from './generated/schemas/whatsAppPairState';import type { WhatsappPasskeyBody } from './generated/schemas/whatsappPasskeyBody';@@ -45,4 +47,15 @@ export const whatsappLinkedClient = {post<Record<string, never>>(`${pairing(id)}/passkey`, response),/** Every WhatsApp chat, newest activity first; asks DSS for a group refresh. */chats: () => fetchWithToken<WhatsAppChats>(`${root}/chats`),+ /** Asks whether a number (E.164) has a WhatsApp account, to start a chat. */+ startLookup: (phoneNumber: string) =>+ post<WhatsAppLookup>(`${root}/lookups`, {+ phoneNumber,+ } satisfies WhatsAppLookupRequest),+ /** A lookup's progress; poll it until it isn't `pending`. */+ lookup: (id: string) =>+ fetchWithToken<WhatsAppLookup, WhatsAppErrorCode>(+ `${root}/lookups/${encodeURIComponent(id)}`,+ { cache: 'no-store', errorResponseHandler: whatsappErrorResponse }+ ),};diff --git a/apps/web/tests/functional/whatsapp-linked.spec.ts b/apps/web/tests/functional/whatsapp-linked.spec.tsindex d45723a9a2..a332adfa69 100644--- a/apps/web/tests/functional/whatsapp-linked.spec.ts+++ b/apps/web/tests/functional/whatsapp-linked.spec.ts@@ -10,6 +10,8 @@ import type {WhatsAppAccount,WhatsAppAccountView,WhatsAppDisconnect,+ WhatsAppLookup,+ WhatsAppLookupRequest,WhatsAppPairing,} from '../../src/lib/service-clients/service-storage/generated/schemas';@@ -61,8 +63,15 @@ type LinkedServer = {upload: Omit<ExternalChatUploadedAttachment, 'uploadId'>;/** Stored attachments' bytes, by static file id; others never load. */files: Record<string, { body: Buffer; contentType: string }>;+ /** Numbers WhatsApp has an account for; the rest aren't on WhatsApp. */+ registered: string[];+ /** Lookups started so far, by id: the number asked about. */+ lookups: Record<string, string>;};+/** A person's phone-number JID. */+const phoneJid = (digits: string) => `${digits}@s.whatsapp.net`;+function server(): LinkedServer {return {account: null,@@ -127,6 +136,8 @@ function server(): LinkedServer {delivery: {},upload: { filename: 'design.pdf', kind: 'document' },files: {},+ registered: [],+ lookups: {},};}@@ -459,9 +470,58 @@ async function mount(page: Page, state: LinkedServer, query = '') {community: chat.community ?? null,canAdd: !chat.self && !chat.added && !chat.shared,cannotAddReason: chat.self ? 'own_chat' : null,+ phoneNumber:+ chat.kind === 'direct' ? `+${chat.jid.split('@')[0]}` : null,})),},});+ if (path === 'whatsapp/lookups' && method === 'POST') {+ const { phoneNumber }: WhatsAppLookupRequest = route+ .request()+ .postDataJSON();+ const id = `lookup-${Object.keys(state.lookups).length + 1}`;+ state.lookups[id] = phoneNumber;+ return route.fulfill({+ json: {+ id,+ phoneNumber,+ state: 'pending',+ chatJid: null,+ } satisfies WhatsAppLookup,+ });+ }+ const lookup = /^whatsapp\/lookups\/(lookup-\d+)$/.exec(path);+ if (lookup && method === 'GET') {+ const id = lookup[1] ?? '';+ const phoneNumber = state.lookups[id] ?? '';+ if (!state.registered.includes(phoneNumber))+ return route.fulfill({+ json: {+ id,+ phoneNumber,+ state: 'not_on_whatsapp',+ chatJid: null,+ } satisfies WhatsAppLookup,+ });+ // A found number joins the chat list.+ const jid = phoneJid(phoneNumber.slice(1));+ if (!state.chats.some((chat) => chat.jid === jid))+ state.chats.push({+ jid,+ kind: 'direct',+ name: phoneNumber,+ lastActivityAt: null,+ added: null,+ });+ return route.fulfill({+ json: {+ id,+ phoneNumber,+ state: 'found',+ chatJid: jid,+ } satisfies WhatsAppLookup,+ });+ }if (path === 'whatsapp/disconnect') {state.account = null;return route.fulfill({@@ -565,6 +625,107 @@ test('links WhatsApp by QR, then adds a shareable WhatsApp chat', async ({expect(unexpected).toEqual([]);});+for (const mobile of [false, true]) {+ test.describe(`${mobile ? 'mobile' : 'desktop'} new chats`, () => {+ test.use({+ viewport: mobile+ ? { width: 390, height: 844 }+ : { width: 1440, height: 900 },+ isMobile: mobile,+ hasTouch: mobile,+ });+ test('starts chats with a saved contact or a phone number', async ({+ page,+ }) => {+ const screenshot = (name: string) =>+ page.screenshot({+ path: process.env.WHATSAPP_SCREENSHOT_DIR+ ? join(+ process.env.WHATSAPP_SCREENSHOT_DIR,+ `${name}-${mobile ? 'mobile' : 'desktop'}.png`+ )+ : test.info().outputPath(`${name}.png`),+ });+ const state = server();+ state.account = {+ id: 'account-1',+ userId: USER_ID,+ authorizationGeneration: 4,+ identityJid: phoneJid('14155550142:3'),+ state: 'connected',+ };+ state.chats.push(+ {+ jid: phoneJid('5550002'),+ kind: 'direct',+ name: 'Dana Smith',+ lastActivityAt: null,+ added: null,+ },+ {+ jid: phoneJid('5550003'),+ kind: 'direct',+ name: 'Eve Adams',+ lastActivityAt: null,+ added: null,+ }+ );+ state.registered = ['+5550007'];+ const unexpected = await mount(page, state);++ // Saved contacts nobody wrote to are listed apart, with their numbers.+ const contacts = page.getByRole('list', { name: 'Contacts' });+ await expect(contacts.getByRole('listitem')).toHaveCount(2);+ await expect(+ contacts+ .getByRole('listitem')+ .filter({ hasText: 'Dana Smith' })+ .getByText('Direct chat · +5550002')+ ).toBeVisible();+ expect(+ await page.evaluate(+ () => document.documentElement.scrollWidth > innerWidth+ )+ ).toBe(false);+ await screenshot('whatsapp-contacts');+ await page+ .getByRole('searchbox', { name: 'Search WhatsApp chats' })+ .fill('555 0003');+ await expect(contacts.getByRole('listitem')).toHaveCount(1);+ await contacts.getByRole('button', { name: 'Add to Macro' }).click();+ await expect(contacts).toHaveCount(0);+ expect(state.additions).toEqual([+ { provider: 'whatsapp', remoteId: phoneJid('5550003'), kind: 'direct' },+ ]);++ await page.getByRole('button', { name: 'New chat' }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).toHaveClass(/ph-no-capture/);+ const number = dialog.getByLabel('Phone number');+ await number.fill('+555 000 9');+ await dialog.getByRole('button', { name: 'Start chat' }).click();+ await expect(+ dialog.getByText("+5550009 isn't on WhatsApp.")+ ).toBeVisible();+ await screenshot('whatsapp-new-chat-not-on-whatsapp');++ await number.fill('+555 000 7');+ await dialog.getByRole('button', { name: 'Start chat' }).click();+ await expect(dialog).toBeHidden();+ expect(await page.evaluate(() => window.openedChats)).toEqual([+ 'chat-new',+ ]);+ expect(state.additions.at(-1)).toEqual({+ provider: 'whatsapp',+ remoteId: phoneJid('5550007'),+ kind: 'direct',+ });+ expect(Object.values(state.lookups)).toEqual(['+5550009', '+5550007']);+ expect(unexpected).toEqual([]);+ });+ });+}+test('a refused add says why, on that group', async ({ page }) => {const state = server();state.account = {diff --git a/apps/web/tests/functional/whatsapp-linked/fixture.tsx b/apps/web/tests/functional/whatsapp-linked/fixture.tsxindex 8de6c12fe9..559cdaf88d 100644--- a/apps/web/tests/functional/whatsapp-linked/fixture.tsx+++ b/apps/web/tests/functional/whatsapp-linked/fixture.tsx@@ -47,6 +47,7 @@ declare global {}}window.openedChats = [];+document.documentElement.dataset.touchDevice = String(isTouchDevice());/** The production adapter and real queries; only the network is the test's. *//**diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.jsonindex 0986c5a862..2591e727df 100644--- a/crates/agent_code_mode/src/domain/documentation.json+++ b/crates/agent_code_mode/src/domain/documentation.json@@ -68,7 +68,7 @@{"name": "channels","description": "Read and send channel messages; list the WhatsApp chat list (groups and direct chats) and add chats to Macro as external chats; read and share external chats, and send from the credential owner's own account with mentions, media and delivery. Pairing stays in the app.",- "index": "## channels\nRead and send channel messages; list the WhatsApp chat list (groups and direct chats) and add chats to Macro as external chats; read and share external chats, and send from the credential owner's own account with mentions, media and delivery. Pairing stays in the app.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### ChannelActivity\nA user's channel activity marker.\nFields: channel\n- `ChannelActivity.createdAt`: createdAt(): string — Creation time.\n- `ChannelActivity.recordInteraction`: recordInteraction(type): Promise<ChannelActivity> — Record a view or interaction in this channel.\n- `ChannelActivity.toJSON`: toJSON(): ApiActivity — Serialize activity without credentials.\n- `ChannelActivity.user`: user(): User — User who interacted.\n\n### Channel\nA channel.\nExtends `PropertiedEntity`.\nFields: entityType, id, name, type, search\n- `Channel.addParticipants`: addParticipants(users): Promise<void> — Add users to the channel.\n- `Channel.agentConversations`: agentConversations(): Promise<AgentConversation[]> — Conversations maintained by agents in this channel.\n- `Channel.attachments`: attachments(opts?): AsyncGenerator<ApiChannelAttachment> — The attachments posted in this channel, auto-paginated.\n- `Channel.delete`: delete(): Promise<void> — Delete the channel.\n- `Channel.join`: join(): Promise<void> — Join the channel as the current user.\n- `Channel.joinCode`: joinCode(): Promise<string> — A reusable code that lets a user join this channel.\n- `Channel.leave`: leave(): Promise<void> — Leave the channel as the current user.\n- `Channel.message`: message(id): Message — A handle to a message in this channel by id.\n- `Channel.messages`: messages(opts?): AsyncGenerator<Message> — Root messages in this channel, most recent first, auto-paginated.\n- `Channel.messagesAfter`: messagesAfter(after, opts?): AsyncGenerator<Message> — Root messages created or replied to at or after after, most recent first, auto-paginated.\n- `Channel.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `Channel.participants`: participants(): Promise<ApiChannelParticipant[]> — The channel's members, with their roles and join times.\n- `Channel.recordActivity`: recordActivity(type): Promise<ChannelActivity> — Record a view or interaction in this channel.\n- `Channel.removeParticipants`: removeParticipants(users): Promise<void> — Remove users from the channel.\n- `Channel.rename`: rename(name): Promise<void> — Rename the channel.\n- `Channel.send`: send(body, opts?): Promise<Message> — Post a message.\n- `Channel.setPicture`: setPicture(picture?): Promise<void> — Set an uploaded profile picture, or clear it.\n- `Channel.timelinePage`: timelinePage(selection?): Promise<{ entries: ({ activity: { action: string; actor: User; actor_id: string; id: string; occurred_at: string; payload?: unknown; }; message?: undefined; type: \"activity\"; } | { activity?: undefined; message: Message; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `Channel.typing`: typing(action, opts?): Promise<void> — Broadcast a typing indicator, optionally scoped to a thread.\n- `Channel.webUrl`: webUrl(): string — The channel's URL in the Macro web app.\n- `Channel.byId`: static byId(client, id): Channel — A handle to a channel by id.\n- `Channel.create`: static create(client, opts): Promise<Channel> — Create a channel.\n- `Channel.dm`: static dm(client, recipient): Promise<Channel> — Open (creating if needed) the DM channel with a user.\n- `Channel.private`: static private(client, recipients): Promise<Channel> — Open (creating if needed) the private group channel with a set of users.\n\n### ChannelLabelsNamespace\nShared or private channel labels: named groups of channels shown in the Chat sidebar.\n- `ChannelLabelsNamespace.create`: create(name, channels?): Promise<ChannelLabel> — Create a label and atomically move channels into it.\n- `ChannelLabelsNamespace.createSmartTag`: createSmartTag(name, rule): Promise<ChannelLabel> — Create a smart tag whose membership follows an attribute rule automatically.\n- `ChannelLabelsNamespace.delete`: delete(label): Promise<void> — Delete a label for the whole team; its channels return to the plain list.\n- `ChannelLabelsNamespace.list`: list(): Promise<ChannelLabel[]> — Every label in the authenticated user's shared or private scope.\n- `ChannelLabelsNamespace.previewSmartTag`: previewSmartTag(rule): Promise<SmartTagPreview> — Preview the first matches and total visible count without creating a tag.\n- `ChannelLabelsNamespace.rename`: rename(label, name): Promise<ChannelLabel> — Rename a label for the whole team.\n- `ChannelLabelsNamespace.setLabel`: setLabel(channel, label): Promise<void> — Move a channel into label, or out of any label when label is undefined.\n- `ChannelLabelsNamespace.updateSmartTag`: updateSmartTag(label, name, rule): Promise<ChannelLabel> — Update the name and matching rule of an existing smart tag.\n\n### Message\nA message in a channel.\nExtends `FavoritableEntity`.\nFields: channelId, content, createdAt, editedAt, entityType, id, mentions, updatedAt\n- `Message.author`: author(): Promise<User> — The user who sent this message.\n- `Message.channel`: channel(): Channel — The channel this message is in.\n- `Message.delete`: delete(): Promise<void> — Delete this message.\n- `Message.edit`: edit(body): Promise<Message> — Replace this message's body.\n- `Message.react`: react(emoji): Promise<Message> — Add an emoji reaction to this message.\n- `Message.reply`: reply(body): Promise<Message> — Post a reply in this message's thread.\n- `Message.thread`: thread(): Thread — The thread rooted at this message.\n- `Message.unreact`: unreact(emoji): Promise<Message> — Remove one of your emoji reactions from this message.\n- `Message.byId`: static byId(client, channelId, id, mentions?): Message — A handle to a message by id.\n- `Message.from`: static from(client, channelId, data): Message — Build a root or reply from a message record (pre-seeded, no fetch).\n\n### ChannelNamespace (`macro.channels`)\nFields: labels\n- `ChannelNamespace.activity`: activity(): Promise<ChannelActivity[]> — Recent channel activity, with channel and user handles.\n- `ChannelNamespace.byId`: byId(id): Channel — Channel\n- `ChannelNamespace.create`: create(opts): Promise<Channel> — Create a channel.\n- `ChannelNamespace.dm`: dm(recipient): Promise<Channel> — Promise<Channel>\n- `ChannelNamespace.list`: list(): Promise<Channel[]> — All channels the authenticated user is a member of.\n- `ChannelNamespace.private`: private(recipients): Promise<Channel> — Open (creating if needed) the private group channel with a set of users.\n- `ChannelNamespace.search`: search(query, opts?): AsyncGenerator<Channel> — Search channels by name (client-side fuzzy filter on the full channel list) or by content (server-side unified search).\n\n### ChannelPicture\nAn uploaded channel profile picture in static file storage.\nFields: id\n- `ChannelPicture.toJSON`: toJSON(): { id: string; } — Serialize the uploaded picture reference.\n- `ChannelPicture.byId`: static byId(id): ChannelPicture — Construct a reference from the upload receipt.\n\n### Thread\nA thread within a channel, rooted at a top-level message.\nFields: channelId, rootId\n- `Thread.channel`: channel(): Channel — The channel this thread is in.\n- `Thread.replies`: replies(): Promise<Message[]> — List the replies in this thread, oldest first.\n- `Thread.reply`: reply(body, opts?): Promise<Message> — Post a reply in this thread.\n- `Thread.root`: root(): Message — The message this thread hangs off.\n- `Thread.toJSON`: toJSON(): { channelId: string; rootId: string; } — Serialize the thread identity without its authenticated client.\n\n### ExternalChat\nA chat from an external messaging provider (WhatsApp today), added to Macro by its owner and shareable like any other entity: a group or a direct chat.\nExtends `FavoritableEntity`.\nFields: backfill, canSend, disappearingSeconds, entityType, id, kind, limits, members, name, owner, participants, provider, sendingIdentity, sendReason, unreadCount\n- `ExternalChat.community`: community(): Promise<WhatsAppCommunity | undefined> — The community a group belongs to, if any: the community's own provider chat, its name, and whether this is its announcement group.\n- `ExternalChat.delivery`: delivery(sends): Promise<ExternalChatSend[]> — Read delivery for selected caller-owned intents or messages.\n- `ExternalChat.markRead`: markRead(message): Promise<void> — Advance the caller's own read cursor.\n- `ExternalChat.messageAttachments`: messageAttachments(messages): Promise<{ attachments: { fileName: string; mime: string; ordinal: number; size: number; state: ExternalChatAttachmentState; url: string | undefined; }[]; message: ExternalChatMessage; }[]> — Read attachment states for selected messages.\n- `ExternalChat.messages`: messages(options?): AsyncGenerator<ExternalChatMessage> — Iterate newest-first timeline pages lazily.\n- `ExternalChat.permissions`: permissions(): Promise<storage.SharePermissionV2> — Read standard link/team sharing settings.\n- `ExternalChat.refresh`: refresh(): Promise<ExternalChat> — Reload detail, permissions and caller capabilities.\n- `ExternalChat.remove`: remove(): Promise<void> — Owner stops syncing the chat; history and established sharing stay.\n- `ExternalChat.send`: send(content, options): Promise<ExternalChatSend> — Personal sessions and owner API credentials can send.\n- `ExternalChat.sends`: sends(): Promise<ExternalChatSend[]> — Read only the caller's pending, uncertain or failed sends.\n- `ExternalChat.updatePermissions`: updatePermissions(update): Promise<void> — Actual owner updates standard link/team sharing settings.\n- `ExternalChat.upload`: upload(file): Promise<ExternalChatUpload> — Stage a supported attachment for a deliberate send.\n- `ExternalChat.byId`: static byId(client, id): ExternalChat — Reference an added chat; access is checked on each request.\n\n### ExternalChatMessage\nMessage in an added external chat.\nExtends `MacroEntity`.\nFields: attachments, body, chat, deleted, deliveryState, editedAt, forwarded, id, kind, mentions, reactions, replyTo, rich, sender, sentAt, viewOnce\n- `ExternalChatMessage.byId`: static byId(client, chat, id): ExternalChatMessage — Reference a message within its original chat.\n- `ExternalChatMessage.from`: static from(client, chat, record): ExternalChatMessage — Seed a message handle from a timeline response.\n\n### ExternalChatsNamespace (`macro.externalChats`)\nChats from external messaging providers (WhatsApp today) that someone added to Macro: read, share and send in them.\n- `ExternalChatsNamespace.byId`: byId(id): ExternalChat — Reference an added chat without fetching it.\n- `ExternalChatsNamespace.list`: list(): Promise<ExternalChat[]> — Added chats the caller can view, including without a provider account of their own.\n\n### ExternalChatParticipant\nSomeone in an added external chat, from its members; mention them in a text reply.\nFields: chat, id\n- `ExternalChatParticipant.toJSON`: toJSON(): { admin: boolean | undefined; chat: string; displayName: string | undefined; id: string; } — Serialize the participant reference without credentials.\n- `ExternalChatParticipant.byId`: static byId(chat, id): ExternalChatParticipant — Reference a participant of a chat by provider id.\n- `ExternalChatParticipant.from`: static from(chat, record): ExternalChatParticipant — Seed a participant from the chat's members.\n\n### ExternalChatSend\nOne deliberate send intent.\nExtends `MacroEntity`.\nFields: chat, createdAt, errorCode, id, message, state\n- `ExternalChatSend.refresh`: refresh(): Promise<ExternalChatSend> — Fetch current delivery state without retrying or submitting the message.\n- `ExternalChatSend.request`: request(): Promise<{ idempotencyKey: string; message: ExternalChatContent; replyTo?: ExternalChatMessage; }> — Inspect the original intent for reconciliation; never resubmit an unknown outcome automatically.\n- `ExternalChatSend.byId`: static byId(client, chat, id): ExternalChatSend — Reference a send intent within its original chat.\n- `ExternalChatSend.from`: static from(client, chat, record): ExternalChatSend — Seed a send handle from a server response.\n\n### ExternalChatUpload\nA staged attachment scoped to one added chat; use it in a deliberate media send.\nFields: chat, filename?, id, kind?\n- `ExternalChatUpload.toJSON`: toJSON(): { chat: string; filename: string | undefined; id: string; kind: ExternalChatMediaKind | undefined; } — Serialize the upload reference without credentials.\n- `ExternalChatUpload.byId`: static byId(chat, id): ExternalChatUpload — Reference a previously staged upload in its original chat.\n- `ExternalChatUpload.from`: static from(chat, record): ExternalChatUpload — Seed a handle from the server's upload receipt.\n\n### WhatsAppAccount\nThe current user's WhatsApp account, connected through the Macro app.\nExtends `MacroEntity`.\nFields: id, identity, owner, state\n- `WhatsAppAccount.refresh`: refresh(): Promise<WhatsAppAccount> — Discard cached connection state and load its current value.\n- `WhatsAppAccount.byId`: static byId(client, id): WhatsAppAccount — Reference an account; reads still enforce the authenticated owner's scope.\n- `WhatsAppAccount.from`: static from(client, record): WhatsAppAccount — Seed an account handle from an API record.\n\n### WhatsAppChat\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\nExtends `MacroEntity`.\nFields: added, archived, canAdd, cannotAddReason, community, id, kind, lastActivityAt, name, pinned, shared\n- `WhatsAppChat.add`: add(): Promise<ExternalChat> — Add the chat (a group or a direct chat) to Macro as the current user's own external chat; its earlier messages are imported from the phone.\n- `WhatsAppChat.refresh`: refresh(): Promise<WhatsAppChat> — Reload the chat's list entry.\n- `WhatsAppChat.byId`: static byId(client, id): WhatsAppChat — Reference a chat by its WhatsApp JID.\n- `WhatsAppChat.from`: static from(client, record): WhatsAppChat — Seed a chat handle from the chat list.\n\n### WhatsAppNamespace (`macro.whatsapp`)\nThe current user's WhatsApp account, paired through the Macro app, and its chat list.\n- `WhatsAppNamespace.account`: account(): Promise<WhatsAppAccount | undefined> — Current owner's account, or undefined when no account has been connected.\n- `WhatsAppNamespace.chats`: chats(): Promise<WhatsAppChat[]> — The caller's WhatsApp chat list (groups and direct chats), newest activity first: each chat says whether it is added, shared with the caller or addable, and ...\n\nFunctions: `postToChannel`, `communityOf`\n\nTypes: `ChannelAttachment`, `ChannelParticipant`, `MessageData`, `ExternalChatContent`, `WhatsAppCommunity`\n"+ "index": "## channels\nRead and send channel messages; list the WhatsApp chat list (groups and direct chats) and add chats to Macro as external chats; read and share external chats, and send from the credential owner's own account with mentions, media and delivery. Pairing stays in the app.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### ChannelActivity\nA user's channel activity marker.\nFields: channel\n- `ChannelActivity.createdAt`: createdAt(): string — Creation time.\n- `ChannelActivity.recordInteraction`: recordInteraction(type): Promise<ChannelActivity> — Record a view or interaction in this channel.\n- `ChannelActivity.toJSON`: toJSON(): ApiActivity — Serialize activity without credentials.\n- `ChannelActivity.user`: user(): User — User who interacted.\n\n### Channel\nA channel.\nExtends `PropertiedEntity`.\nFields: entityType, id, name, type, search\n- `Channel.addParticipants`: addParticipants(users): Promise<void> — Add users to the channel.\n- `Channel.agentConversations`: agentConversations(): Promise<AgentConversation[]> — Conversations maintained by agents in this channel.\n- `Channel.attachments`: attachments(opts?): AsyncGenerator<ApiChannelAttachment> — The attachments posted in this channel, auto-paginated.\n- `Channel.delete`: delete(): Promise<void> — Delete the channel.\n- `Channel.join`: join(): Promise<void> — Join the channel as the current user.\n- `Channel.joinCode`: joinCode(): Promise<string> — A reusable code that lets a user join this channel.\n- `Channel.leave`: leave(): Promise<void> — Leave the channel as the current user.\n- `Channel.message`: message(id): Message — A handle to a message in this channel by id.\n- `Channel.messages`: messages(opts?): AsyncGenerator<Message> — Root messages in this channel, most recent first, auto-paginated.\n- `Channel.messagesAfter`: messagesAfter(after, opts?): AsyncGenerator<Message> — Root messages created or replied to at or after after, most recent first, auto-paginated.\n- `Channel.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `Channel.participants`: participants(): Promise<ApiChannelParticipant[]> — The channel's members, with their roles and join times.\n- `Channel.recordActivity`: recordActivity(type): Promise<ChannelActivity> — Record a view or interaction in this channel.\n- `Channel.removeParticipants`: removeParticipants(users): Promise<void> — Remove users from the channel.\n- `Channel.rename`: rename(name): Promise<void> — Rename the channel.\n- `Channel.send`: send(body, opts?): Promise<Message> — Post a message.\n- `Channel.setPicture`: setPicture(picture?): Promise<void> — Set an uploaded profile picture, or clear it.\n- `Channel.timelinePage`: timelinePage(selection?): Promise<{ entries: ({ activity: { action: string; actor: User; actor_id: string; id: string; occurred_at: string; payload?: unknown; }; message?: undefined; type: \"activity\"; } | { activity?: undefined; message: Message; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `Channel.typing`: typing(action, opts?): Promise<void> — Broadcast a typing indicator, optionally scoped to a thread.\n- `Channel.webUrl`: webUrl(): string — The channel's URL in the Macro web app.\n- `Channel.byId`: static byId(client, id): Channel — A handle to a channel by id.\n- `Channel.create`: static create(client, opts): Promise<Channel> — Create a channel.\n- `Channel.dm`: static dm(client, recipient): Promise<Channel> — Open (creating if needed) the DM channel with a user.\n- `Channel.private`: static private(client, recipients): Promise<Channel> — Open (creating if needed) the private group channel with a set of users.\n\n### ChannelLabelsNamespace\nShared or private channel labels: named groups of channels shown in the Chat sidebar.\n- `ChannelLabelsNamespace.create`: create(name, channels?): Promise<ChannelLabel> — Create a label and atomically move channels into it.\n- `ChannelLabelsNamespace.createSmartTag`: createSmartTag(name, rule): Promise<ChannelLabel> — Create a smart tag whose membership follows an attribute rule automatically.\n- `ChannelLabelsNamespace.delete`: delete(label): Promise<void> — Delete a label for the whole team; its channels return to the plain list.\n- `ChannelLabelsNamespace.list`: list(): Promise<ChannelLabel[]> — Every label in the authenticated user's shared or private scope.\n- `ChannelLabelsNamespace.previewSmartTag`: previewSmartTag(rule): Promise<SmartTagPreview> — Preview the first matches and total visible count without creating a tag.\n- `ChannelLabelsNamespace.rename`: rename(label, name): Promise<ChannelLabel> — Rename a label for the whole team.\n- `ChannelLabelsNamespace.setLabel`: setLabel(channel, label): Promise<void> — Move a channel into label, or out of any label when label is undefined.\n- `ChannelLabelsNamespace.updateSmartTag`: updateSmartTag(label, name, rule): Promise<ChannelLabel> — Update the name and matching rule of an existing smart tag.\n\n### Message\nA message in a channel.\nExtends `FavoritableEntity`.\nFields: channelId, content, createdAt, editedAt, entityType, id, mentions, updatedAt\n- `Message.author`: author(): Promise<User> — The user who sent this message.\n- `Message.channel`: channel(): Channel — The channel this message is in.\n- `Message.delete`: delete(): Promise<void> — Delete this message.\n- `Message.edit`: edit(body): Promise<Message> — Replace this message's body.\n- `Message.react`: react(emoji): Promise<Message> — Add an emoji reaction to this message.\n- `Message.reply`: reply(body): Promise<Message> — Post a reply in this message's thread.\n- `Message.thread`: thread(): Thread — The thread rooted at this message.\n- `Message.unreact`: unreact(emoji): Promise<Message> — Remove one of your emoji reactions from this message.\n- `Message.byId`: static byId(client, channelId, id, mentions?): Message — A handle to a message by id.\n- `Message.from`: static from(client, channelId, data): Message — Build a root or reply from a message record (pre-seeded, no fetch).\n\n### ChannelNamespace (`macro.channels`)\nFields: labels\n- `ChannelNamespace.activity`: activity(): Promise<ChannelActivity[]> — Recent channel activity, with channel and user handles.\n- `ChannelNamespace.byId`: byId(id): Channel — Channel\n- `ChannelNamespace.create`: create(opts): Promise<Channel> — Create a channel.\n- `ChannelNamespace.dm`: dm(recipient): Promise<Channel> — Promise<Channel>\n- `ChannelNamespace.list`: list(): Promise<Channel[]> — All channels the authenticated user is a member of.\n- `ChannelNamespace.private`: private(recipients): Promise<Channel> — Open (creating if needed) the private group channel with a set of users.\n- `ChannelNamespace.search`: search(query, opts?): AsyncGenerator<Channel> — Search channels by name (client-side fuzzy filter on the full channel list) or by content (server-side unified search).\n\n### ChannelPicture\nAn uploaded channel profile picture in static file storage.\nFields: id\n- `ChannelPicture.toJSON`: toJSON(): { id: string; } — Serialize the uploaded picture reference.\n- `ChannelPicture.byId`: static byId(id): ChannelPicture — Construct a reference from the upload receipt.\n\n### Thread\nA thread within a channel, rooted at a top-level message.\nFields: channelId, rootId\n- `Thread.channel`: channel(): Channel — The channel this thread is in.\n- `Thread.replies`: replies(): Promise<Message[]> — List the replies in this thread, oldest first.\n- `Thread.reply`: reply(body, opts?): Promise<Message> — Post a reply in this thread.\n- `Thread.root`: root(): Message — The message this thread hangs off.\n- `Thread.toJSON`: toJSON(): { channelId: string; rootId: string; } — Serialize the thread identity without its authenticated client.\n\n### ExternalChat\nA chat from an external messaging provider (WhatsApp today), added to Macro by its owner and shareable like any other entity: a group or a direct chat.\nExtends `FavoritableEntity`.\nFields: backfill, canSend, disappearingSeconds, entityType, id, kind, limits, members, name, owner, participants, provider, sendingIdentity, sendReason, unreadCount\n- `ExternalChat.community`: community(): Promise<WhatsAppCommunity | undefined> — The community a group belongs to, if any: the community's own provider chat, its name, and whether this is its announcement group.\n- `ExternalChat.delivery`: delivery(sends): Promise<ExternalChatSend[]> — Read delivery for selected caller-owned intents or messages.\n- `ExternalChat.markRead`: markRead(message): Promise<void> — Advance the caller's own read cursor.\n- `ExternalChat.messageAttachments`: messageAttachments(messages): Promise<{ attachments: { fileName: string; mime: string; ordinal: number; size: number; state: ExternalChatAttachmentState; url: string | undefined; }[]; message: ExternalChatMessage; }[]> — Read attachment states for selected messages.\n- `ExternalChat.messages`: messages(options?): AsyncGenerator<ExternalChatMessage> — Iterate newest-first timeline pages lazily.\n- `ExternalChat.permissions`: permissions(): Promise<storage.SharePermissionV2> — Read standard link/team sharing settings.\n- `ExternalChat.refresh`: refresh(): Promise<ExternalChat> — Reload detail, permissions and caller capabilities.\n- `ExternalChat.remove`: remove(): Promise<void> — Owner stops syncing the chat; history and established sharing stay.\n- `ExternalChat.send`: send(content, options): Promise<ExternalChatSend> — Personal sessions and owner API credentials can send.\n- `ExternalChat.sends`: sends(): Promise<ExternalChatSend[]> — Read only the caller's pending, uncertain or failed sends.\n- `ExternalChat.updatePermissions`: updatePermissions(update): Promise<void> — Actual owner updates standard link/team sharing settings.\n- `ExternalChat.upload`: upload(file): Promise<ExternalChatUpload> — Stage a supported attachment for a deliberate send.\n- `ExternalChat.byId`: static byId(client, id): ExternalChat — Reference an added chat; access is checked on each request.\n\n### ExternalChatMessage\nMessage in an added external chat.\nExtends `MacroEntity`.\nFields: attachments, body, chat, deleted, deliveryState, editedAt, forwarded, id, kind, mentions, reactions, replyTo, rich, sender, sentAt, viewOnce\n- `ExternalChatMessage.byId`: static byId(client, chat, id): ExternalChatMessage — Reference a message within its original chat.\n- `ExternalChatMessage.from`: static from(client, chat, record): ExternalChatMessage — Seed a message handle from a timeline response.\n\n### ExternalChatsNamespace (`macro.externalChats`)\nChats from external messaging providers (WhatsApp today) that someone added to Macro: read, share and send in them.\n- `ExternalChatsNamespace.byId`: byId(id): ExternalChat — Reference an added chat without fetching it.\n- `ExternalChatsNamespace.list`: list(): Promise<ExternalChat[]> — Added chats the caller can view, including without a provider account of their own.\n\n### ExternalChatParticipant\nSomeone in an added external chat, from its members; mention them in a text reply.\nFields: chat, id\n- `ExternalChatParticipant.toJSON`: toJSON(): { admin: boolean | undefined; chat: string; displayName: string | undefined; id: string; } — Serialize the participant reference without credentials.\n- `ExternalChatParticipant.byId`: static byId(chat, id): ExternalChatParticipant — Reference a participant of a chat by provider id.\n- `ExternalChatParticipant.from`: static from(chat, record): ExternalChatParticipant — Seed a participant from the chat's members.\n\n### ExternalChatSend\nOne deliberate send intent.\nExtends `MacroEntity`.\nFields: chat, createdAt, errorCode, id, message, state\n- `ExternalChatSend.refresh`: refresh(): Promise<ExternalChatSend> — Fetch current delivery state without retrying or submitting the message.\n- `ExternalChatSend.request`: request(): Promise<{ idempotencyKey: string; message: ExternalChatContent; replyTo?: ExternalChatMessage; }> — Inspect the original intent for reconciliation; never resubmit an unknown outcome automatically.\n- `ExternalChatSend.byId`: static byId(client, chat, id): ExternalChatSend — Reference a send intent within its original chat.\n- `ExternalChatSend.from`: static from(client, chat, record): ExternalChatSend — Seed a send handle from a server response.\n\n### ExternalChatUpload\nA staged attachment scoped to one added chat; use it in a deliberate media send.\nFields: chat, filename?, id, kind?\n- `ExternalChatUpload.toJSON`: toJSON(): { chat: string; filename: string | undefined; id: string; kind: ExternalChatMediaKind | undefined; } — Serialize the upload reference without credentials.\n- `ExternalChatUpload.byId`: static byId(chat, id): ExternalChatUpload — Reference a previously staged upload in its original chat.\n- `ExternalChatUpload.from`: static from(chat, record): ExternalChatUpload — Seed a handle from the server's upload receipt.\n\n### WhatsAppAccount\nThe current user's WhatsApp account, connected through the Macro app.\nExtends `MacroEntity`.\nFields: id, identity, owner, state\n- `WhatsAppAccount.refresh`: refresh(): Promise<WhatsAppAccount> — Discard cached connection state and load its current value.\n- `WhatsAppAccount.byId`: static byId(client, id): WhatsAppAccount — Reference an account; reads still enforce the authenticated owner's scope.\n- `WhatsAppAccount.from`: static from(client, record): WhatsAppAccount — Seed an account handle from an API record.\n\n### WhatsAppChat\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\nExtends `MacroEntity`.\nFields: added, archived, canAdd, cannotAddReason, community, id, kind, lastActivityAt, name, phoneNumber, pinned, shared\n- `WhatsAppChat.add`: add(): Promise<ExternalChat> — Add the chat (a group or a direct chat) to Macro as the current user's own external chat; its earlier messages are imported from the phone.\n- `WhatsAppChat.refresh`: refresh(): Promise<WhatsAppChat> — Reload the chat's list entry.\n- `WhatsAppChat.byId`: static byId(client, id): WhatsAppChat — Reference a chat by its WhatsApp JID.\n- `WhatsAppChat.from`: static from(client, record): WhatsAppChat — Seed a chat handle from the chat list.\n\n### WhatsAppNamespace (`macro.whatsapp`)\nThe current user's WhatsApp account, paired through the Macro app, and its chat list.\n- `WhatsAppNamespace.account`: account(): Promise<WhatsAppAccount | undefined> — Current owner's account, or undefined when no account has been connected.\n- `WhatsAppNamespace.chats`: chats(): Promise<WhatsAppChat[]> — The caller's WhatsApp chat list (groups and direct chats), newest activity first: each chat says whether it is added, shared with the caller or addable, and ...\n\nFunctions: `postToChannel`, `communityOf`\n\nTypes: `ChannelAttachment`, `ChannelParticipant`, `MessageData`, `ExternalChatContent`, `WhatsAppCommunity`\n"},{"name": "crm",@@ -789,7 +789,7 @@"storage.WhatsAppAccount": "# Type Alias: WhatsAppAccount\n\n> **WhatsAppAccount** = \\{ `authorizationGeneration`: `number`; `id`: `string`; `identityJid?`: `string` \\| `null`; `state`: `WhatsAppAccountState`; `userId`: `string`; \\}\n\nOne person's account, never owned by a workspace.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorizationgeneration\"></a> `authorizationGeneration` | `number` | Explicit consent generation; reconnecting a socket never changes it. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable account identity. |\n| <a id=\"property-identityjid\"></a> `identityJid?` | `string` \\| `null` | WhatsApp-verified identity, absent until the first pairing succeeds. |\n| <a id=\"property-state\"></a> `state` | `WhatsAppAccountState` | Lifecycle. |\n| <a id=\"property-userid\"></a> `userId` | `string` | Authenticated owner. |","WhatsAppAccountState": "# Type Alias: WhatsAppAccountState\n\n> **WhatsAppAccountState** = `\"pairing\"` \\| `\"connected\"` \\| `\"logged_out\"` \\| `\"disconnected\"`\n\nAccount lifecycle. Transport outages are not stored: a connected account\nstays connected while its session service reconnects.","WhatsAppCannotAdd": "# Type Alias: WhatsAppCannotAdd\n\n> **WhatsAppCannotAdd** = `\"not_in_group\"` \\| `\"community\"` \\| `\"own_chat\"` \\| `\"not_in_chat_list\"`\n\nWhy a chat can't be added to Macro; the app words it from the code.",- "storage.WhatsAppChat": "# Type Alias: WhatsAppChat\n\n> **WhatsAppChat** = \\{ `added?`: `null` \\| `ExternalChatReference`; `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `null` \\| `WhatsAppCannotAdd`; `community?`: `null` \\| `ExternalChatCommunity`; `jid`: `string`; `kind`: `ExternalChatKind`; `lastActivityAt?`: `string` \\| `null`; `name`: `string`; `pinned`: `boolean`; `shared?`: `null` \\| `SharedExternalChatReference`; \\}\n\nOne chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-added\"></a> `added?` | `null` \\| `ExternalChatReference` | - |\n| <a id=\"property-archived\"></a> `archived` | `boolean` | Archived in WhatsApp. |\n| <a id=\"property-canadd\"></a> `canAdd` | `boolean` | \"Add to Macro\" works now. |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason?` | `null` \\| `WhatsAppCannotAdd` | - |\n| <a id=\"property-community\"></a> `community?` | `null` \\| `ExternalChatCommunity` | - |\n| <a id=\"property-jid\"></a> `jid` | `string` | WhatsApp chat JID: a group, or the other person's phone-number JID (LID when WhatsApp never told us the number). |\n| <a id=\"property-kind\"></a> `kind` | `ExternalChatKind` | Group or direct chat. |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt?` | `string` \\| `null` | Newest activity WhatsApp reported (message or history sync); `null` when unknown. The list is sorted by it, newest first, unknown last. |\n| <a id=\"property-name\"></a> `name` | `string` | Group: the subject, or member names for an unnamed group. Direct: the contact or WhatsApp name, else `+<phone>`. Always non-empty. |\n| <a id=\"property-pinned\"></a> `pinned` | `boolean` | Pinned in WhatsApp. |\n| <a id=\"property-shared\"></a> `shared?` | `null` \\| `SharedExternalChatReference` | - |",+ "storage.WhatsAppChat": "# Type Alias: WhatsAppChat\n\n> **WhatsAppChat** = \\{ `added?`: `null` \\| `ExternalChatReference`; `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `null` \\| `WhatsAppCannotAdd`; `community?`: `null` \\| `ExternalChatCommunity`; `jid`: `string`; `kind`: `ExternalChatKind`; `lastActivityAt?`: `string` \\| `null`; `name`: `string`; `phoneNumber?`: `string` \\| `null`; `pinned`: `boolean`; `shared?`: `null` \\| `SharedExternalChatReference`; \\}\n\nOne chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-added\"></a> `added?` | `null` \\| `ExternalChatReference` | - |\n| <a id=\"property-archived\"></a> `archived` | `boolean` | Archived in WhatsApp. |\n| <a id=\"property-canadd\"></a> `canAdd` | `boolean` | \"Add to Macro\" works now. |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason?` | `null` \\| `WhatsAppCannotAdd` | - |\n| <a id=\"property-community\"></a> `community?` | `null` \\| `ExternalChatCommunity` | - |\n| <a id=\"property-jid\"></a> `jid` | `string` | WhatsApp chat JID: a group, or the other person's phone-number JID (LID when WhatsApp never told us the number). |\n| <a id=\"property-kind\"></a> `kind` | `ExternalChatKind` | Group or direct chat. |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt?` | `string` \\| `null` | Newest activity WhatsApp reported (message or history sync); `null` when unknown, as for saved contacts never messaged. The list is sorted by it, newest first, unknown last. |\n| <a id=\"property-name\"></a> `name` | `string` | Group: the subject, or member names for an unnamed group. Direct: the contact or WhatsApp name, else `+<phone>`. Always non-empty. |\n| <a id=\"property-phonenumber\"></a> `phoneNumber?` | `string` \\| `null` | The other person's phone number (`+<digits>`) of a direct chat, when WhatsApp told us it. |\n| <a id=\"property-pinned\"></a> `pinned` | `boolean` | Pinned in WhatsApp. |\n| <a id=\"property-shared\"></a> `shared?` | `null` \\| `SharedExternalChatReference` | - |","Widget": "# Type Alias: Widget\n\n> **Widget** = `\"short\"` \\| `\"paragraph\"` \\| `\"datetime\"` \\| `\"date\"` \\| `\"url\"` \\| `\"file\"` \\| `\"choice\"` \\| `\"dropdown\"` \\| `\"checkboxes\"`\n\nHow a question is asked. Each column kind takes a few, the first its\ndefault; kinds asked one way only (numbers, checkboxes, date ranges,\nentity and row pickers) take none.","GetUnfurlBulkResponse": "# Type Alias: GetUnfurlBulkResponse\n\n> **GetUnfurlBulkResponse** = \\{ `responses`: `unfurl.Vec`; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-responses\"></a> `responses` | `unfurl.Vec` |","GetUnfurlResponse": "# Type Alias: GetUnfurlResponse\n\n> **GetUnfurlResponse** = \\{ `description?`: `string` \\| `null`; `embed_type?`: `UnfurlEmbedType`; `embed_url?`: `string` \\| `null`; `favicon_url?`: `string` \\| `null`; `image_url?`: `string` \\| `null`; `title`: `string`; `url`: `string`; \\}\n\nUnfurl response for a single URL: the URL itself plus any metadata that\nwas extracted from the page's `<head>` (title, description, image,\nfavicon).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | The page description (from `og:description`), if any. |\n| <a id=\"property-embed_type\"></a> `embed_type?` | `UnfurlEmbedType` | The type of embeddable content, if the URL supports iframe embedding. |\n| <a id=\"property-embed_url\"></a> `embed_url?` | `string` \\| `null` | The iframe-embeddable URL for services like Loom or Supercut. |\n| <a id=\"property-favicon_url\"></a> `favicon_url?` | `string` \\| `null` | The page's favicon URL, if any. |\n| <a id=\"property-image_url\"></a> `image_url?` | `string` \\| `null` | The page's preview image URL (from `og:image`), if any. |\n| <a id=\"property-title\"></a> `title` | `string` | The page title (from custom URL parser, Open Graph, or `<title>`). |\n| <a id=\"property-url\"></a> `url` | `string` | The URL that was unfurled. |",@@ -1944,7 +1944,7 @@"WhatsAppAccount.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `storage.WhatsAppAccount`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `storage.WhatsAppAccount`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `storage.WhatsAppAccount` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`","WhatsAppAccount.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppAccount`\n\nReference an account; reads still enforce the authenticated owner's scope.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppAccount`","WhatsAppAccount.from": "### from()\n\n> `static` **from**(`client`, `record`): `WhatsAppAccount`\n\nSeed an account handle from an API record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | `storage.WhatsAppAccount` |\n\n#### Returns\n\n`WhatsAppAccount`",- "WhatsAppChat": "# Class: WhatsAppChat\n\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\n\n## Extends\n\n- `MacroEntity`\\<`storage.WhatsAppChat`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-added\"></a> `added` | `readonly` | () => `Promise`\\<`ExternalChat` \\| `undefined`\\> | The current user's own external chat for this chat, once added. | - |\n| <a id=\"property-archived\"></a> `archived` | `readonly` | () => `Promise`\\<`boolean`\\> | Archived in WhatsApp. | - |\n| <a id=\"property-canadd\"></a> `canAdd` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether adding it to Macro works now. | - |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason` | `readonly` | () => `Promise`\\<`NonNullable`\\<WhatsAppCannotAdd \\| null \\| undefined\\> \\| `undefined`\\> | Why it can't be added (`not_in_group`, `community`, `own_chat`, `not_in_chat_list`), when it is neither added, shared nor addable. | - |\n| <a id=\"property-community\"></a> `community` | `readonly` | () => `Promise`\\<`WhatsAppCommunity` \\| `undefined`\\> | The WhatsApp community a group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<`ExternalChatKind`\\> | `group` or `direct`. | - |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Newest activity WhatsApp reported, when known. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Group subject (or member names), or the other person's name or number. | - |\n| <a id=\"property-pinned\"></a> `pinned` | `readonly` | () => `Promise`\\<`boolean`\\> | Pinned in WhatsApp. | - |\n| <a id=\"property-shared\"></a> `shared` | `readonly` | () => `Promise`\\<`ExternalChat` \\| `undefined`\\> | Someone else's external chat for this chat, shared with the current user. | - |",+ "WhatsAppChat": "# Class: WhatsAppChat\n\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\n\n## Extends\n\n- `MacroEntity`\\<`storage.WhatsAppChat`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-added\"></a> `added` | `readonly` | () => `Promise`\\<`ExternalChat` \\| `undefined`\\> | The current user's own external chat for this chat, once added. | - |\n| <a id=\"property-archived\"></a> `archived` | `readonly` | () => `Promise`\\<`boolean`\\> | Archived in WhatsApp. | - |\n| <a id=\"property-canadd\"></a> `canAdd` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether adding it to Macro works now. | - |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason` | `readonly` | () => `Promise`\\<`NonNullable`\\<WhatsAppCannotAdd \\| null \\| undefined\\> \\| `undefined`\\> | Why it can't be added (`not_in_group`, `community`, `own_chat`, `not_in_chat_list`), when it is neither added, shared nor addable. | - |\n| <a id=\"property-community\"></a> `community` | `readonly` | () => `Promise`\\<`WhatsAppCommunity` \\| `undefined`\\> | The WhatsApp community a group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<`ExternalChatKind`\\> | `group` or `direct`. | - |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Newest activity WhatsApp reported; unknown for saved contacts never written to. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Group subject (or member names), or the other person's name or number. | - |\n| <a id=\"property-phonenumber\"></a> `phoneNumber` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | The other person's phone number (`+<digits>`) of a direct chat, when known. | - |\n| <a id=\"property-pinned\"></a> `pinned` | `readonly` | () => `Promise`\\<`boolean`\\> | Pinned in WhatsApp. | - |\n| <a id=\"property-shared\"></a> `shared` | `readonly` | () => `Promise`\\<`ExternalChat` \\| `undefined`\\> | Someone else's external chat for this chat, shared with the current user. | - |","WhatsAppChat.add": "### add()\n\n> **add**(): `Promise`\\<`ExternalChat`\\>\n\nAdd the chat (a group or a direct chat) to Macro as the current user's\nown external chat; its earlier messages are imported from the phone.\nAdding it again returns the same chat. Only the owner sends in a direct\nchat.\n\n#### Returns\n\n`Promise`\\<`ExternalChat`\\>","WhatsAppChat.refresh": "### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppChat`\\>\n\nReload the chat's list entry.\n\n#### Returns\n\n`Promise`\\<`WhatsAppChat`\\>","WhatsAppChat.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `storage.WhatsAppChat`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `storage.WhatsAppChat`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `storage.WhatsAppChat` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex 88fcc25145..6f2efc6c5b 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -660,6 +660,8 @@"storage.whatsappChats": "Whatsapp Chats","storage.whatsappConnect": "Whatsapp Connect","storage.whatsappDisconnect": "Whatsapp Disconnect",+ "storage.whatsappStartLookup": "Whatsapp Start Lookup",+ "storage.whatsappLookup": "Whatsapp Lookup","storage.whatsappCancelPairing": "Whatsapp Cancel Pairing","storage.whatsappPairing": "Whatsapp Pairing","storage.whatsappPasskey": "Whatsapp Passkey"diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex 9a796c4abd..a4271534ee 100644--- a/crates/code_execution/src/outbound/deno/sdk.mjs+++ b/crates/code_execution/src/outbound/deno/sdk.mjs@@ -1,5 +1,5 @@// Generated by packages/code-mode-sdk/scripts/generate.ts.-async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class B${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*c($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class f extends Error{constructor($){super($);this.name="MacroError"}}class QO extends f{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function Y($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=Y(await $(this.client));return this.detail.clear(),O}}class H$ extends P{async permission(){return Y(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Y(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Y(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){Y(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Y(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){Y(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var hS={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function n$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>hS[x]??x);return`<${$}>${j}</${$}>`}function mS($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var uS={toMention:()=>({tag:n$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function cS($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(mS(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:dS(x)}}function dS($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class L$ extends P{static byId($,O){return new L$($,O)}static from($,O){return new L$($,O.id,O)}async fetch(){let $=Y(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends P{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=Y(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?L$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:m0($)}))}}function m0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:G}}async function Bj($,O,j,x=[]){let{channelId:S,thread:K}=rS(O);if(await pS($)){let{id:X}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((G)=>({entity_type:lS,entity_id:G.id,width:G.width??null,height:G.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:Z}=Y(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var lS="static/image";function rS($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function pS($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class m${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Y(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($,O){let j=await Bj(this.client,this,O$($),O?.images);return e.byId(this.client,this.channelId,j)}}class e extends H${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new m$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:l.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new u0(this.client,this,$))}async startFresh($){Y(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class u0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return l.byId(this.client,this.record.sessionId)}async retry($){Y(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class N$ extends P{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new N$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function w$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=Y(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:A.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var aS=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??aS;return c(async(Q)=>{let{results:J,next_cursor:I}=Y(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class JO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return A.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends X${async recordActivity($){return new JO(this.client,this,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return N$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Y(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=Y(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Y(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Y(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Bj(this.client,O?.thread??this,O$($),O?.images);return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return c(async(O)=>{let j=Y(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=Y(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return Y(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Y(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Y(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class A extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new A($,O)}static fromName($,O){return new A($,O.id,O)}static async me($){let{user_id:O}=Y(await $.auth.getUserInfo());return new A($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:n$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Y(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?A.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?HO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>HO.from(this.client,this,j))}}async submit($,O){return HO.from(this.client,this,Y(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Y(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Y(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:A.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Y(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Y(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return Y(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class HO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new HO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>A.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function s$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class U$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new U$($,O,j)}static fromRecord($,O,j){return new U$($,O,j.id,j)}static async create($,O,j){return U$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=Y(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return U$.fromRecord($,O,S)}static async list($,O){return Y(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>U$.fromRecord($,O.session(),x))}async fetch(){return Y(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new c0($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class c0{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class dO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return Y(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>U$.create(this.client,this,$),list:()=>U$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return Y(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Y(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Y(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return Y(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class l extends P{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:s$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=Y(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new l($,j.id,j)}static async repositories($){let{repositories:O}=Y(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Y(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Y(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Y(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=Y(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=Y(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?A.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Y(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Y(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Y(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Y(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Y(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Y(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=Y(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return Y(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Y(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Y(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Y(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>U$.createForSession(this.client,this,$),byId:($)=>U$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class d0{client;constructor($){this.client=$}byId($){return l.byId(this.client,$)}createManaged($){return l.createManaged(this.client,$)}chooseMode($){return l.chooseMode(this.client,$)}repositories(){return l.repositories(this.client)}repositoryBranches($){return l.repositoryBranches(this.client,$)}forPullRequest($){return l.forPullRequest(this.client,$)}defaultSandboxSize(){return l.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return l.setDefaultSandboxSize(this.client,$)}codingPreferences(){return l.codingPreferences(this.client)}setCodingPreferences($){return l.setCodingPreferences(this.client,$)}}class l0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return Y(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,Y(await this.client.storage.createAgent({body:m0($)})))}}class r0{client;async usage($={}){let{users:O,...j}=$;return Y(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Y(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Y(await this.client.cognition.decisions({body:$}))}}class t$ extends P{static byId($,O){return new t$($,O)}static from($,O){return new t$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Y(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class p0{client;constructor($){this.client=$}byId($){return t$.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>t$.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:t$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return Y(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Y(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class S$ extends P{async fetch(){let O=Y(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new S$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new S$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>A.byId(this.client,$));async members(){let $=Y(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new f("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:A.byId(this.client,O.user_id),role:O.role}))}}class R$ extends P{async fetch(){let{links:$}=Y(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new R$($,O)}static async list($){let{links:O}=Y(await $.email.listLinks());return O.map((j)=>new R$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return Y(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class u$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Y(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new u$($,O)}static async list($){let{calendars:O}=Y(await $.calendar.listCalendars());return O.map((j)=>new u$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Y(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Y(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Y(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),Y(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),Y(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.forDocument(this.client,this,O,$)}requireOwnOccurrence($){if($.eventId!==this.id)throw new f("The occurrence belongs to a different event")}async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new $$($,O)}static fromRecord($,O){return new $$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?u$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:iS($)}));return $$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=Y(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return Y(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return $$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}async ics(){return Y(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}}function iS($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class q$ extends P{event;occurrence;fromDocument;constructor($,O,j,x,S,K=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=K;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,w.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=Y(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).find((S)=>S.eventId===this.event.id&&S.occurrenceKey===this.occurrence.occurrenceKey);if(!x)throw new E("This meeting link has been removed");return{documentId:this.id,name:x.documentName,team:x.team,canManage:!0}}let O=Y(await this.client.calendar.eventNotes({path:{event_id:this.event.id},query:{occurrenceKey:this.occurrence.occurrenceKey}})).find((j)=>j.documentId===this.id);if(!O)throw new E("This document is no longer linked to the meeting");return O}document=this.mappedField("documentId",($)=>w.byId(this.client,$));name=this.field("name");team=this.mappedField("team",($)=>$?S$.byId(this.client,$.id):void 0);canManage=this.field("canManage");async setTeam($){await this.mutate((O)=>O.calendar.linkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey},body:{teamId:$?.id??null}}))}async unlink(){await this.mutate(($)=>$.calendar.unlinkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey}}))}}class n extends X${async sharePermissions(){return Y(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Y(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Y(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Y(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends P{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class c$ extends P{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return w.byId(this.client,this.documentId)}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class aO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new B$(async()=>Y(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var nS=8;class w extends X${async meetingNotes(){return Y(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,Y(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Y(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Y(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return N$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=Y(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=Y(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=Y(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=Y(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return c(async(x)=>{let S=Y(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=Y(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>A.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=Y(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Y(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=Y(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=c(async(x)=>{let S=Y(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return cO(j,nS,async(x)=>{let{state:S,root:K,replies:Z}=Y(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return Y(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Y(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=Y(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Y(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:n$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class a0{client;async noteDocuments($=""){let O=Y(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:w.byId(this.client,j.documentId),name:j.name})),teams:O.teams.map((j)=>({team:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:u$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Y(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Y(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Y(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=tS(this.client);let S=await O;return{items:x.items.map((K)=>({event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,inbox:K.event.calendarId?S.get(K.event.calendarId):void 0,role:eS(K.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:A.byId(this.client,j)})),members:O.members.map((j)=>({user:A.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Y(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:A.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return u$.list(this.client)}calendar($){return u$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:sS($)}));return $$.fromRecord(this.client,O)}}function sS($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}async function tS($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function eS($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class D$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return Y(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Y(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?J$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return Y(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Y(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Y(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class d$ extends P{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new d$($,O,j)}static from($,O,j){return new d$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return J$.byId(this.client,this.callId)}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Y(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return d$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class J$ extends H${messageThreadById($){return N$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>d$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return D$.from(this.client,Y(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return Y(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return d$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>A.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new J$($,O.call_id)})}class i0{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class n0{client;constructor($){this.client=$}async list(){let{labels:$}=Y(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Y(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Y(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Y(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Y(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Y(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class s0{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new n0($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async list(){let{items:$}=Y(await this.client.storage.getChannels());return $.map((O)=>b.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=Y(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield b.byId(this.client,S.id.toString())}else yield*b.search(this.client,$,O)}}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){Y(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=Y(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class K$ extends X${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=K$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Y(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new K$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new K$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new K$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Y(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new K$($,O.chat_id)});toMention(){return{tag:n$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class t0{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}create($){return K$.create(this.client,$)}search($,O){return K$.search(this.client,$,O)}}var oS=8;class P$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(K)=>{let Z=Y(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return cO(S,oS,async(K)=>{let{state:Z,root:X,replies:G}=Y(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=Y(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class f$ extends H${messageThreadById($){return N$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Y(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return N$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Y(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return Y(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class e$ extends P{tableDetail=new B$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new e$($,O)}static from($,O){return new e$($,O.id,O)}async fetch(){return Y(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>A.byId(this.client,$));team=this.mappedField("teamId",($)=>S$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Y(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:s$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Y(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>WO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return c(async(O)=>{let j=Y(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>WO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class zj extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return WO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class WO extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new WO($,O,j)}static from($,O,j){return new WO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Ij extends P{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Ij($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class e0{client;constructor($){this.client=$}byId($){return e$.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>e$.from(this.client,$))}async create($){return e$.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class o0{client;pipelines;constructor($){this.client=$;this.pipelines=new e0($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Y(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Y(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Y(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Y(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Y(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var Y$=Symbol.for("@ts-pattern/matcher"),l1=Symbol.for("@ts-pattern/isVariadic");var $x=($)=>Boolean($&&typeof $=="object"),Hj=($)=>$&&!!$[Y$],s=($,O,j)=>{if(Hj($)){let x=$[Y$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if($x($)){if(!$x(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Hj(X)&&X[l1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),G=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(K.length===0||s(K[0],G,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Hj(K=S)&&K[Y$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},G$=($)=>{var O,j,x;return $x($)?Hj($)?(O=(j=(x=$[Y$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,G$):tO(Object.values($),G$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function $7(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>xx($),and:(O)=>d($,O),or:(O)=>r1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function Ox($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[l1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>Ox(xx($)),select:(O)=>Ox(O===void 0?eO($):eO(O,$))})}function xx($){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(G$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>G$($),matcherType:"optional"})})}var O7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},j7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},x7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"and"})})}function r1(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,G$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"or"})})}function u($){return{[Y$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[Y$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:G$(j))})})}function p1($){return!0}function k$($){return typeof $=="number"}function o$($){return typeof $=="string"}function $O($){return typeof $=="bigint"}var a1=t(u(p1)),S7=t(u(p1)),Z7=a1,OO=($)=>Object.assign(t($),{startsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.endsWith(j)))));var j},minLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length>=j))(O))),length:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length===j))(O))),maxLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length<=j))(O))),includes:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.includes(j)))));var j},regex:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&Boolean(x.match(j))))));var j}}),d1=OO(u(o$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>u((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,u((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,u((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,u((O)=>k$(O)&&O>0))),negative:()=>g$(d($,u((O)=>k$(O)&&O<0)))}),X7=g$(u(k$)),jO=($)=>Object.assign(t($),{between:(O,j)=>jO(d($,((x,S)=>u((K)=>$O(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<j))(O))),gt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>j))(O))),lte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<=j))(O))),gte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>=j))(O))),positive:()=>jO(d($,u((O)=>$O(O)&&O>0))),negative:()=>jO(d($,u((O)=>$O(O)&&O<0)))}),K7=jO(u($O)),G7=t(u(function($){return typeof $=="boolean"})),Y7=t(u(function($){return typeof $=="symbol"})),Q7=t(u(function($){return $==null})),J7=t(u(function($){return $!=null})),Z$={__proto__:null,matcher:Y$,optional:xx,array:function(...$){return Ox({[Y$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return G$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:G$($[0])})})},set:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:O7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:G$($[0])})})},map:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,G)=>{j[X]=(j[X]||[]).concat([G])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:j7(O,(X,G)=>{let L=s(K,G,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[1])]})})},record:function(...$){return t({[Y$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,G)=>{x[X]=(x[X]||[]).concat([G])},[K,Z]=$.length===1?[d1,$[0]]:$;return{matched:x7(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,G,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[1])]})})},intersection:d,union:r1,not:function($){return t({[Y$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:eO,any:a1,unknown:S7,_:Z7,string:d1,number:X7,bigint:K7,boolean:G7,symbol:Y7,nullish:Q7,nonNullable:J7,instanceOf:function($){return t(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(u($7($)))}};class i1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var jx={matched:!1,value:void 0};function k($){return new Tj($,jx)}class Tj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(G,L)=>{S=!0,K[G]=L},X=!j.some((G)=>s(G,this.input,Z))||x&&!Boolean(x(this.input))?jx:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Tj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Tj(this.input,j?{matched:!0,value:O(this.input,this.input)}:jx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=V7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function V7($){throw new i1($)}var Sx,W7=new Uint8Array(16);function Rj(){if(!Sx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Sx=crypto.getRandomValues.bind(crypto)}return Sx(W7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function n1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var Zx={};function B7($,O,j){let x;if($)x=s1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();L7(Zx,S,K),x=s1(K,Zx.msecs,Zx.seq,O,j)}return O??n1(x)}function L7($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function s1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var l$=B7;class C${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new C$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>C$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=Y(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return V$.byId(Z(J),Q)},G=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Q of G)for(let J of K.get(Q)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:C$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?N7(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function N7($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Mj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Mj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Gx extends QO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Aj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var U7={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function z7($){return k($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>U7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Xx($){return $.map((O)=>({id:l$(),label:O}))}function t1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Kx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function r$($,O,j){let[x]=$;if($.length!==1||!t1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Kx).join(", ")||"none"}`);return x}class W$ extends P{access=new o(this.client,"database",this);async fetch(){return Y(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new W$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new W$($,j.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new W$($,j.database.id))}query($,O){return _j(this.client,W$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>A.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=r$(await this.applyOps([{kind:"table",table:l$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Gx(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new f(`expected one reorder_tables result, got ${O.map(Kx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=Y(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=Y(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return V$.byId(this,O.id)}webhookOf($){return Mj.fromRecord(V$.byId(this,$.tableId),A.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Y(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Y(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),Y(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Y(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Aj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Aj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${z7(O.to)})`,S=l$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Aj(O.to),options:Xx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:G})=>({row:X,cells:[{column:S,value:G}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!t1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Kx(Z):"none"}`);return C$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Aj(O.type),...O.options!==void 0?{options:Xx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=r$(await this.applyOps([{kind:"column",table:$.id,column:l$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return C$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Xx(O)}}]),"column","options_added")}}class Yx{client;constructor($){this.client=$}query($,O){return _j(this.client,W$.byId,$,O)}byId($){return W$.byId(this.client,$)}create($){return W$.create(this.client,$)}list(){return W$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class Qx{client;async byTeamSlug($){let O=Y(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Y(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?A.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=Y(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=Y(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class BO extends P{async fetch(){let{attachment:$}=Y(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new BO($,O)}static from($,O){return new BO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=Y(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class z$ extends X${access=new o(this.client,"email_thread",this);async followup(){return Y(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Y(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Y(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Y(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?s$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Y(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return Y(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>_$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>BO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?_$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=Y(await $.email.archiveThreads({body:{thread_ids:K.map((G)=>G.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let G of K)if(G.detail.clear(),X.has(G.id))x.push(G)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Y(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class _$ extends P{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new _$($,O)}static from($,O){return new _$($,O.db_id,O)}static async send($,O){let{message:j}=Y(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?_$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));async operationStatus(){return Y(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Y(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class LO extends _${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new LO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Jx($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:oO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return oO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class oO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new oO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Jx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:G,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:G?.id}}class NO extends P{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=Y(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class xO extends P{async fetch(){let{labels:$}=Y(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new xO($,O)}static async list($){let{labels:O}=Y(await $.email.listLabels());return O.map((j)=>new xO($,j.id,j))}static async create($,O){let{label:j}=Y(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new xO($,j.id)}async delete(){Y(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class Vx{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Jx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=Y(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield LO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Y(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,Y(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Y(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Y(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return _$.byId(this.client,$)}attachment($){return BO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return Y(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Y(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return _$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Y(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return xO.byId(this.client,$)}labels(){return xO.list(this.client)}createLabel($){return xO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){Y(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Y(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Y(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Y(await this.client.email.listBlockedSenders()).blocked_emails}}class TO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new TO($,O)}async delete(){Y(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Wx{client;constructor($){this.client=$}byId($){return TO.byId(this.client,$)}async create($,O){let j=Y(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return TO.byId(this.client,j.id)}}function Bx($,O){return{chat:UO.byId($,O.id),name:O.name,announcements:O.announcements}}class UO extends P{static byId($,O){return new UO($,O)}static from($,O){return new UO($,O.jid,O)}async fetch(){let{chats:$}=Y(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Bx(this.client,$):void 0);added=this.mappedField("added",($)=>$?y$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?y$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return y$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return Y(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?M$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class SO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new SO($,O)}static from($,O){return new SO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class ZO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new ZO(O,$)}static from($,O){return new ZO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class XO extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.id,j)}async fetch(){let O=Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:ZO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>SO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class y$ extends H${entityType="external_chat";static byId($,O){return new y$($,O)}async fetch(){return Y(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>SO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Bx(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Y(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Y(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Y(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return ZO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return XO.from(this.client,this,x)}async sends(){return Y(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>XO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>XO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Lx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>y$.byId(this.client,$.id))}byId($){return y$.byId(this.client,$)}}class Nx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Y(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Y(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Y(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class KO extends H${entityType="foreign_entity";async fetch(){return Y(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function e1({login:$,...O}){return{...O,login:$??void 0}}class Ux{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async bySource($,O){return KO.fromRecord(this.client,Y(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Y(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(e1),assignees:j.map(e1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return C$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>zO.byId(this,$.id))}}class zO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new zO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new B$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new RO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new B$(()=>this.load(),$),this}}class a${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new a$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>p$.byId(this.form,O.id)):[]}}class Cj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Cj($,O)}}class v$ extends P{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new v$($,O)}static async create($,O){let j=Y(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new v$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new v$($,S.id));return Y(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new v$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>A.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>W$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(W$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>a$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>p$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:k(G.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??l$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(G)=>({...X,kind:"booking",target:G.target})).with({kind:"gate"},(G)=>({...X,kind:"gate",rules:x(G.rules),message:G.message})).with({kind:"questions"},(G)=>({...X,kind:"questions",questions:G.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??l$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=k(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:a$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:a$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Y(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=p$.byId(this,K.question),X=await k(K.value).with({type:"options"},(G)=>({type:"options",value:G.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return zO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Cj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(G)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=V$.byId(W$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(G)=>G).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?a$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Y(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:a$.byId(this,O.section),count:O.count}))}}async tally(){return Y(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=p$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:zO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return Y(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class zx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}create($){return v$.create(this.client,$)}list($){return v$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return Y(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Y(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Ix(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Ix{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Y(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Hx{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return Y(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return L$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:L$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Tx{client;constructor($){this.client=$}byId($){return L$.byId(this.client,$)}async list(){return Y(await this.client.storage.listHarnesses()).map(($)=>L$.from(this.client,$))}async me(){return L$.from(this.client,Y(await this.client.storage.getSelfHarness()))}async deleteSelf(){Y(await this.client.storage.deleteSelfHarness())}async agents(){return Y(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return Y(await this.client.storage.listHarnessSessions()).map(($)=>l.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Y(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class Fj{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Fj(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class Ej extends Fj{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Rx{client;constructor($){this.client=$}async generate($){let O=Y(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(I7)}}));return new Ej(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function I7($){return $ instanceof w?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var H7="00000001-0000-0000-0000-000000000001",o1="00000001-0000-0000-0000-000000000002",T7="00000001-0000-0000-0000-000000000004",R7="00000001-0000-0000-0000-000000000014",D7="00000001-0000-0000-0002-000000000001",_7="00000001-0000-0000-0002-000000000004";function M7($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class Q$ extends w{static byId($,O){return new Q$($,O)}static async create($,O){let{documentId:j}=Y(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0,propertyValues:await A7($,O)}}));return new Q$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Y(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:A.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Y(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new Q$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=M7(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new Q$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===o1)?.value;return j?.type==="SelectOption"&&j.value.includes(_7)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new Q$($,O.document_id)})}async function A7($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await A.me($)],x=[{propertyId:o1,value:{type:"select_option",option_id:D7}}];if(j.length>0)x.push({propertyId:H7,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:R7,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:T7,value:{type:"date",value:O.dueDate.toISOString()}});return x}class i$ extends P{access=new o(this.client,"initiative",this);static byId($,O){return new i$($,O)}static from($,O){return new i$($,O.id,O)}async fetch(){return Y(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>A.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>A.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>Q$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?s$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Dx{client;constructor($){this.client=$}byId($){return i$.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>i$.byId(this.client,$.id))}async summaries(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:i$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return i$.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class _x{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,Y(await this.client.storage.meetingCreate({body:$})))}async list(){return Y(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return Y(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,Y(await this.client.storage.meetingLookup({path:{token:$}})))}}class IO extends P{async fetch(){return Y(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.id,O)}static list($,O){return c(async(j)=>{let x=Y(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>IO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>A.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?A.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Mx{client;constructor($){this.client=$}byId($){return IO.byId(this.client,$)}list($){return IO.list(this.client,$)}async markSeen($){Y(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Y(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Y(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Y(await this.client.notification.getNotificationTypePreferences())}async enableType($){Y(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Y(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Ax{client;constructor($){this.client=$}async list(){let{data:$}=Y(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Y(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Y(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Y(await this.client.storage.reorderPinsHandler({body:$}))}}class Px{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class MO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new MO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class GO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return Y(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Y(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new GO($,j.id,j)}static byId($,O){return new GO($,O)}static fromRecord($,O){return new GO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return Y(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Y(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Y(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Cx{client;constructor($){this.client=$}async list($){return Y(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return GO.fromRecord(this.client,x)})}create($){return GO.create(this.client,$)}definition($){return GO.byId(this.client,$)}async bulkEntityProperties($){return Y(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Y(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return Y(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Y(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Y(await this.client.properties.listTags({}))}}function Fx($){return k($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function P7($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Fx)})).with({type:"cron"},Fx).with({type:"events"},Fx).exhaustive()}class h$ extends P{static byId($,O){return new h$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new h$($,O.id,O)}async fetch(){return Y(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>A.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?h$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Y($))}async shareAsTemplate($){return this.toTemplate(Y(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return h$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...wj($),enabled:$.enabled??!0}})))}toTemplate($){return new $2(this,A.byId(this.client,$.author),$)}async stopSharingTemplate(){Y(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:wj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Y(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>l.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Ex(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class $2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class Ex{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function wj($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:P7($.trigger),task:{...O}}}class wx{client;constructor($){this.client=$}byId($){return h$.byId(this.client,$)}async create($){return h$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...wj($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>h$.from(this.client,O))}}class qx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}summaries($){return Q$.summaries(this.client,$)}findSimilar($){return Q$.findSimilar(this.client,$)}forPullRequest($){return Q$.forPullRequest(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class fx{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class bx{client;constructor($){this.client=$}async get($){return Y(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Y(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class kx{client;constructor($){this.client=$}byId($){return A.byId(this.client,$)}me(){return A.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=Y(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:G}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(G.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(A.fromName(this.client,J))}}return K}}class YO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Y(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Y(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new YO($,j.id,j,j.signing_secret)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>A.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class gx{client;constructor($){this.client=$}create($){return YO.create(this.client,$)}byId($){return YO.byId(this.client,$)}async list(){let{webhooks:$}=Y(await this.client.storage.listWebhooks());return $.map((O)=>YO.fromRecord(this.client,O))}}class AO extends P{static byId($,O){return new AO($,O)}static from($,O){return new AO($,O.id,O)}async fetch(){let{account:$}=Y(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class yx{client;constructor($){this.client=$}async account(){let{account:$}=Y(await this.client.storage.whatsappAccount());return $?AO.from(this.client,$):void 0}async chats(){return Y(await this.client.storage.whatsappChats()).chats.map(($)=>UO.from(this.client,$))}}function vx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function O2($,O,j){let x=[];for(let S of vx(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:w.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:K$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new m$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:KO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var j2="00000000-0000-0000-0000-000000000000",hx={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},qj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),x2=($,O)=>$==null?O:{"&":[$,O]};function mx($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){mx(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{mx(Z,`${O}.${S}[${X}]`)})}class fj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Y),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(hx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(hx).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)mx($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:j2}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=Y(await this.client.email.listLinks()),K=S.filter((X)=>qj(X.email_address)===qj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=x2(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(hx))if(!x.includes(S))O[K]={l:{[Z]:j2}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Q)=>qj(Q.label)===qj(G.label.trim())&&(!G.scope||Q.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((G)=>({l:{pd:G.definitionId,v:{so:G.id}}})).reduce((G,L)=>G===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[G,L]},void 0);O.propf=x2(O.propf,X)}return O}}class ux{client;constructor($){this.client=$}async page($={}){let O=new fj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new fj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Y(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>vx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>O2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function S2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class B${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*c($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class f extends Error{constructor($){super($);this.name="MacroError"}}class QO extends f{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function Y($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=Y(await $(this.client));return this.detail.clear(),O}}class H$ extends P{async permission(){return Y(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Y(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Y(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){Y(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Y(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){Y(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var hS={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function n$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>hS[x]??x);return`<${$}>${j}</${$}>`}function mS($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var uS={toMention:()=>({tag:n$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function cS($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(mS(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:dS(x)}}function dS($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class L$ extends P{static byId($,O){return new L$($,O)}static from($,O){return new L$($,O.id,O)}async fetch(){let $=Y(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends P{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=Y(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?L$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:m0($)}))}}function m0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:G}}async function Bj($,O,j,x=[]){let{channelId:S,thread:K}=rS(O);if(await pS($)){let{id:X}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((G)=>({entity_type:lS,entity_id:G.id,width:G.width??null,height:G.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:Z}=Y(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var lS="static/image";function rS($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function pS($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class m${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Y(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($,O){let j=await Bj(this.client,this,O$($),O?.images);return e.byId(this.client,this.channelId,j)}}class e extends H${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new m$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:l.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new u0(this.client,this,$))}async startFresh($){Y(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class u0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return l.byId(this.client,this.record.sessionId)}async retry($){Y(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class N$ extends P{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new N$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function w$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=Y(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:A.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var aS=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??aS;return c(async(Q)=>{let{results:J,next_cursor:I}=Y(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class JO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return A.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends X${async recordActivity($){return new JO(this.client,this,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return N$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Y(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=Y(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Y(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Y(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Bj(this.client,O?.thread??this,O$($),O?.images);return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return c(async(O)=>{let j=Y(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=Y(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return Y(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){Y(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Y(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class A extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new A($,O)}static fromName($,O){return new A($,O.id,O)}static async me($){let{user_id:O}=Y(await $.auth.getUserInfo());return new A($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:n$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=Y(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?A.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?HO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>HO.from(this.client,this,j))}}async submit($,O){return HO.from(this.client,this,Y(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Y(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Y(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:A.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Y(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Y(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return Y(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class HO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new HO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>A.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function s$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class U$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new U$($,O,j)}static fromRecord($,O,j){return new U$($,O,j.id,j)}static async create($,O,j){return U$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=Y(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return U$.fromRecord($,O,S)}static async list($,O){return Y(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>U$.fromRecord($,O.session(),x))}async fetch(){return Y(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new c0($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class c0{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class dO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return Y(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>U$.create(this.client,this,$),list:()=>U$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return Y(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Y(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Y(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return Y(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class l extends P{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:s$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=Y(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new l($,j.id,j)}static async repositories($){let{repositories:O}=Y(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Y(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Y(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Y(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=Y(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=Y(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?A.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Y(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Y(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return Y(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Y(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Y(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Y(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=Y(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return Y(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Y(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=Y(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Y(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>U$.createForSession(this.client,this,$),byId:($)=>U$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class d0{client;constructor($){this.client=$}byId($){return l.byId(this.client,$)}createManaged($){return l.createManaged(this.client,$)}chooseMode($){return l.chooseMode(this.client,$)}repositories(){return l.repositories(this.client)}repositoryBranches($){return l.repositoryBranches(this.client,$)}forPullRequest($){return l.forPullRequest(this.client,$)}defaultSandboxSize(){return l.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return l.setDefaultSandboxSize(this.client,$)}codingPreferences(){return l.codingPreferences(this.client)}setCodingPreferences($){return l.setCodingPreferences(this.client,$)}}class l0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return Y(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,Y(await this.client.storage.createAgent({body:m0($)})))}}class r0{client;async usage($={}){let{users:O,...j}=$;return Y(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Y(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Y(await this.client.cognition.decisions({body:$}))}}class t$ extends P{static byId($,O){return new t$($,O)}static from($,O){return new t$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Y(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class p0{client;constructor($){this.client=$}byId($){return t$.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>t$.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:t$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return Y(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Y(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class S$ extends P{async fetch(){let O=Y(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new S$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new S$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>A.byId(this.client,$));async members(){let $=Y(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new f("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:A.byId(this.client,O.user_id),role:O.role}))}}class R$ extends P{async fetch(){let{links:$}=Y(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new R$($,O)}static async list($){let{links:O}=Y(await $.email.listLinks());return O.map((j)=>new R$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return Y(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class u$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Y(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new u$($,O)}static async list($){let{calendars:O}=Y(await $.calendar.listCalendars());return O.map((j)=>new u$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Y(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Y(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Y(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),Y(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),Y(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.forDocument(this.client,this,O,$)}requireOwnOccurrence($){if($.eventId!==this.id)throw new f("The occurrence belongs to a different event")}async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new $$($,O)}static fromRecord($,O){return new $$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?u$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:iS($)}));return $$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=Y(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return Y(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return $$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}async ics(){return Y(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}}function iS($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class q$ extends P{event;occurrence;fromDocument;constructor($,O,j,x,S,K=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=K;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,w.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=Y(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).find((S)=>S.eventId===this.event.id&&S.occurrenceKey===this.occurrence.occurrenceKey);if(!x)throw new E("This meeting link has been removed");return{documentId:this.id,name:x.documentName,team:x.team,canManage:!0}}let O=Y(await this.client.calendar.eventNotes({path:{event_id:this.event.id},query:{occurrenceKey:this.occurrence.occurrenceKey}})).find((j)=>j.documentId===this.id);if(!O)throw new E("This document is no longer linked to the meeting");return O}document=this.mappedField("documentId",($)=>w.byId(this.client,$));name=this.field("name");team=this.mappedField("team",($)=>$?S$.byId(this.client,$.id):void 0);canManage=this.field("canManage");async setTeam($){await this.mutate((O)=>O.calendar.linkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey},body:{teamId:$?.id??null}}))}async unlink(){await this.mutate(($)=>$.calendar.unlinkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey}}))}}class n extends X${async sharePermissions(){return Y(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Y(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=Y(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=Y(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends P{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class c$ extends P{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return w.byId(this.client,this.documentId)}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class aO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new B$(async()=>Y(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var nS=8;class w extends X${async meetingNotes(){return Y(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return Y(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,Y(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Y(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Y(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return N$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=Y(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=Y(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=Y(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=Y(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return c(async(x)=>{let S=Y(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=Y(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>A.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=Y(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Y(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=Y(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=c(async(x)=>{let S=Y(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return cO(j,nS,async(x)=>{let{state:S,root:K,replies:Z}=Y(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return Y(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Y(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=Y(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Y(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:n$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class a0{client;async noteDocuments($=""){let O=Y(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:w.byId(this.client,j.documentId),name:j.name})),teams:O.teams.map((j)=>({team:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:u$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Y(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Y(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Y(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=tS(this.client);let S=await O;return{items:x.items.map((K)=>({event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,inbox:K.event.calendarId?S.get(K.event.calendarId):void 0,role:eS(K.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:A.byId(this.client,j)})),members:O.members.map((j)=>({user:A.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Y(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:A.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return u$.list(this.client)}calendar($){return u$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:sS($)}));return $$.fromRecord(this.client,O)}}function sS($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}async function tS($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function eS($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class D$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return Y(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Y(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?J$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return Y(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Y(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Y(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class d$ extends P{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new d$($,O,j)}static from($,O,j){return new d$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return J$.byId(this.client,this.callId)}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Y(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return d$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class J$ extends H${messageThreadById($){return N$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>d$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return D$.from(this.client,Y(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return Y(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return d$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>A.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new J$($,O.call_id)})}class i0{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class n0{client;constructor($){this.client=$}async list(){let{labels:$}=Y(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Y(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Y(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Y(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Y(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Y(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class s0{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new n0($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async list(){let{items:$}=Y(await this.client.storage.getChannels());return $.map((O)=>b.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=Y(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield b.byId(this.client,S.id.toString())}else yield*b.search(this.client,$,O)}}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){Y(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=Y(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class K$ extends X${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=K$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Y(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new K$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new K$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new K$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Y(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new K$($,O.chat_id)});toMention(){return{tag:n$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class t0{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}create($){return K$.create(this.client,$)}search($,O){return K$.search(this.client,$,O)}}var oS=8;class P$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(K)=>{let Z=Y(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return cO(S,oS,async(K)=>{let{state:Z,root:X,replies:G}=Y(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=Y(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class f$ extends H${messageThreadById($){return N$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Y(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return N$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Y(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return Y(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class e$ extends P{tableDetail=new B$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new e$($,O)}static from($,O){return new e$($,O.id,O)}async fetch(){return Y(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>A.byId(this.client,$));team=this.mappedField("teamId",($)=>S$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return Y(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:s$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Y(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>WO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return c(async(O)=>{let j=Y(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>WO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class zj extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return WO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class WO extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new WO($,O,j)}static from($,O,j){return new WO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Ij extends P{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Ij($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class e0{client;constructor($){this.client=$}byId($){return e$.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>e$.from(this.client,$))}async create($){return e$.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class o0{client;pipelines;constructor($){this.client=$;this.pipelines=new e0($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Y(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Y(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Y(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Y(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Y(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var Y$=Symbol.for("@ts-pattern/matcher"),l1=Symbol.for("@ts-pattern/isVariadic");var $x=($)=>Boolean($&&typeof $=="object"),Hj=($)=>$&&!!$[Y$],s=($,O,j)=>{if(Hj($)){let x=$[Y$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if($x($)){if(!$x(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Hj(X)&&X[l1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),G=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(K.length===0||s(K[0],G,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Hj(K=S)&&K[Y$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},G$=($)=>{var O,j,x;return $x($)?Hj($)?(O=(j=(x=$[Y$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,G$):tO(Object.values($),G$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function $7(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>xx($),and:(O)=>d($,O),or:(O)=>r1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function Ox($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[l1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>Ox(xx($)),select:(O)=>Ox(O===void 0?eO($):eO(O,$))})}function xx($){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(G$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>G$($),matcherType:"optional"})})}var O7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},j7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},x7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"and"})})}function r1(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,G$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"or"})})}function u($){return{[Y$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[Y$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:G$(j))})})}function p1($){return!0}function k$($){return typeof $=="number"}function o$($){return typeof $=="string"}function $O($){return typeof $=="bigint"}var a1=t(u(p1)),S7=t(u(p1)),Z7=a1,OO=($)=>Object.assign(t($),{startsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.endsWith(j)))));var j},minLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length>=j))(O))),length:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length===j))(O))),maxLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length<=j))(O))),includes:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.includes(j)))));var j},regex:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&Boolean(x.match(j))))));var j}}),d1=OO(u(o$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>u((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,u((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,u((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,u((O)=>k$(O)&&O>0))),negative:()=>g$(d($,u((O)=>k$(O)&&O<0)))}),X7=g$(u(k$)),jO=($)=>Object.assign(t($),{between:(O,j)=>jO(d($,((x,S)=>u((K)=>$O(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<j))(O))),gt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>j))(O))),lte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<=j))(O))),gte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>=j))(O))),positive:()=>jO(d($,u((O)=>$O(O)&&O>0))),negative:()=>jO(d($,u((O)=>$O(O)&&O<0)))}),K7=jO(u($O)),G7=t(u(function($){return typeof $=="boolean"})),Y7=t(u(function($){return typeof $=="symbol"})),Q7=t(u(function($){return $==null})),J7=t(u(function($){return $!=null})),Z$={__proto__:null,matcher:Y$,optional:xx,array:function(...$){return Ox({[Y$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return G$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:G$($[0])})})},set:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:O7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:G$($[0])})})},map:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,G)=>{j[X]=(j[X]||[]).concat([G])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:j7(O,(X,G)=>{let L=s(K,G,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[1])]})})},record:function(...$){return t({[Y$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,G)=>{x[X]=(x[X]||[]).concat([G])},[K,Z]=$.length===1?[d1,$[0]]:$;return{matched:x7(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,G,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[1])]})})},intersection:d,union:r1,not:function($){return t({[Y$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:eO,any:a1,unknown:S7,_:Z7,string:d1,number:X7,bigint:K7,boolean:G7,symbol:Y7,nullish:Q7,nonNullable:J7,instanceOf:function($){return t(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(u($7($)))}};class i1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var jx={matched:!1,value:void 0};function k($){return new Tj($,jx)}class Tj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(G,L)=>{S=!0,K[G]=L},X=!j.some((G)=>s(G,this.input,Z))||x&&!Boolean(x(this.input))?jx:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Tj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Tj(this.input,j?{matched:!0,value:O(this.input,this.input)}:jx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=V7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function V7($){throw new i1($)}var Sx,W7=new Uint8Array(16);function Rj(){if(!Sx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Sx=crypto.getRandomValues.bind(crypto)}return Sx(W7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function n1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var Zx={};function B7($,O,j){let x;if($)x=s1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();L7(Zx,S,K),x=s1(K,Zx.msecs,Zx.seq,O,j)}return O??n1(x)}function L7($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function s1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var l$=B7;class C${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new C$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>C$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=Y(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return V$.byId(Z(J),Q)},G=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Q of G)for(let J of K.get(Q)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:C$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?N7(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function N7($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Mj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Mj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Gx extends QO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Aj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var U7={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function z7($){return k($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>U7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Xx($){return $.map((O)=>({id:l$(),label:O}))}function t1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Kx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function r$($,O,j){let[x]=$;if($.length!==1||!t1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Kx).join(", ")||"none"}`);return x}class W$ extends P{access=new o(this.client,"database",this);async fetch(){return Y(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new W$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new W$($,j.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new W$($,j.database.id))}query($,O){return _j(this.client,W$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>A.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=r$(await this.applyOps([{kind:"table",table:l$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Gx(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new f(`expected one reorder_tables result, got ${O.map(Kx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=Y(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=Y(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return V$.byId(this,O.id)}webhookOf($){return Mj.fromRecord(V$.byId(this,$.tableId),A.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Y(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Y(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),Y(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Y(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Aj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Aj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${z7(O.to)})`,S=l$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Aj(O.to),options:Xx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:G})=>({row:X,cells:[{column:S,value:G}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!t1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Kx(Z):"none"}`);return C$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Aj(O.type),...O.options!==void 0?{options:Xx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=r$(await this.applyOps([{kind:"column",table:$.id,column:l$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return C$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Xx(O)}}]),"column","options_added")}}class Yx{client;constructor($){this.client=$}query($,O){return _j(this.client,W$.byId,$,O)}byId($){return W$.byId(this.client,$)}create($){return W$.create(this.client,$)}list(){return W$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class Qx{client;async byTeamSlug($){let O=Y(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Y(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?A.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=Y(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=Y(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class BO extends P{async fetch(){let{attachment:$}=Y(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new BO($,O)}static from($,O){return new BO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=Y(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class z$ extends X${access=new o(this.client,"email_thread",this);async followup(){return Y(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Y(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Y(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Y(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?s$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Y(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return Y(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>_$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>BO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?_$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=Y(await $.email.archiveThreads({body:{thread_ids:K.map((G)=>G.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let G of K)if(G.detail.clear(),X.has(G.id))x.push(G)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Y(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class _$ extends P{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new _$($,O)}static from($,O){return new _$($,O.db_id,O)}static async send($,O){let{message:j}=Y(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?_$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>R$.byId(this.client,$));async operationStatus(){return Y(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Y(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class LO extends _${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new LO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Jx($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:oO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return oO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class oO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new oO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Jx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:G,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:G?.id}}class NO extends P{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=Y(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class xO extends P{async fetch(){let{labels:$}=Y(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new xO($,O)}static async list($){let{labels:O}=Y(await $.email.listLabels());return O.map((j)=>new xO($,j.id,j))}static async create($,O){let{label:j}=Y(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new xO($,j.id)}async delete(){Y(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class Vx{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Jx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=Y(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield LO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Y(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,Y(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return Y(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Y(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return _$.byId(this.client,$)}attachment($){return BO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return Y(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Y(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return _$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Y(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return xO.byId(this.client,$)}labels(){return xO.list(this.client)}createLabel($){return xO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){Y(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Y(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Y(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Y(await this.client.email.listBlockedSenders()).blocked_emails}}class TO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new TO($,O)}async delete(){Y(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Wx{client;constructor($){this.client=$}byId($){return TO.byId(this.client,$)}async create($,O){let j=Y(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return TO.byId(this.client,j.id)}}function Bx($,O){return{chat:UO.byId($,O.id),name:O.name,announcements:O.announcements}}class UO extends P{static byId($,O){return new UO($,O)}static from($,O){return new UO($,O.jid,O)}async fetch(){let{chats:$}=Y(await this.client.storage.whatsappChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Bx(this.client,$):void 0);added=this.mappedField("added",($)=>$?y$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?y$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return y$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return Y(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?M$.byId(this.client,this.chat,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class SO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new SO($,O)}static from($,O){return new SO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class ZO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new ZO(O,$)}static from($,O){return new ZO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class XO extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.id,j)}async fetch(){let O=Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:ZO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>SO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class y$ extends H${entityType="external_chat";static byId($,O){return new y$($,O)}async fetch(){return Y(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>SO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Bx(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Y(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Y(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Y(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return ZO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return XO.from(this.client,this,x)}async sends(){return Y(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>XO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>XO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Lx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>y$.byId(this.client,$.id))}byId($){return y$.byId(this.client,$)}}class Nx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Y(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Y(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Y(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class KO extends H${entityType="foreign_entity";async fetch(){return Y(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function e1({login:$,...O}){return{...O,login:$??void 0}}class Ux{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async bySource($,O){return KO.fromRecord(this.client,Y(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Y(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(e1),assignees:j.map(e1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return C$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>zO.byId(this,$.id))}}class zO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new zO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new B$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new RO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new B$(()=>this.load(),$),this}}class a${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new a$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>p$.byId(this.form,O.id)):[]}}class Cj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Cj($,O)}}class v$ extends P{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new v$($,O)}static async create($,O){let j=Y(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new v$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new v$($,S.id));return Y(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new v$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>A.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>W$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(W$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>a$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>p$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:k(G.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??l$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(G)=>({...X,kind:"booking",target:G.target})).with({kind:"gate"},(G)=>({...X,kind:"gate",rules:x(G.rules),message:G.message})).with({kind:"questions"},(G)=>({...X,kind:"questions",questions:G.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??l$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=k(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:a$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:a$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Y(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=p$.byId(this,K.question),X=await k(K.value).with({type:"options"},(G)=>({type:"options",value:G.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return zO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Cj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(G)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=V$.byId(W$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(G)=>G).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?a$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Y(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:a$.byId(this,O.section),count:O.count}))}}async tally(){return Y(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=p$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:zO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return Y(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class zx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}create($){return v$.create(this.client,$)}list($){return v$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return Y(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Y(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Ix(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Ix{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Y(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Hx{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return Y(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return L$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:L$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Tx{client;constructor($){this.client=$}byId($){return L$.byId(this.client,$)}async list(){return Y(await this.client.storage.listHarnesses()).map(($)=>L$.from(this.client,$))}async me(){return L$.from(this.client,Y(await this.client.storage.getSelfHarness()))}async deleteSelf(){Y(await this.client.storage.deleteSelfHarness())}async agents(){return Y(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return Y(await this.client.storage.listHarnessSessions()).map(($)=>l.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Y(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class Fj{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Fj(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class Ej extends Fj{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Rx{client;constructor($){this.client=$}async generate($){let O=Y(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(I7)}}));return new Ej(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function I7($){return $ instanceof w?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var H7="00000001-0000-0000-0000-000000000001",o1="00000001-0000-0000-0000-000000000002",T7="00000001-0000-0000-0000-000000000004",R7="00000001-0000-0000-0000-000000000014",D7="00000001-0000-0000-0002-000000000001",_7="00000001-0000-0000-0002-000000000004";function M7($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class Q$ extends w{static byId($,O){return new Q$($,O)}static async create($,O){let{documentId:j}=Y(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0,propertyValues:await A7($,O)}}));return new Q$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Y(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:A.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Y(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new Q$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=M7(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new Q$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===o1)?.value;return j?.type==="SelectOption"&&j.value.includes(_7)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new Q$($,O.document_id)})}async function A7($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await A.me($)],x=[{propertyId:o1,value:{type:"select_option",option_id:D7}}];if(j.length>0)x.push({propertyId:H7,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:R7,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:T7,value:{type:"date",value:O.dueDate.toISOString()}});return x}class i$ extends P{access=new o(this.client,"initiative",this);static byId($,O){return new i$($,O)}static from($,O){return new i$($,O.id,O)}async fetch(){return Y(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>A.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>A.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>Q$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?s$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Dx{client;constructor($){this.client=$}byId($){return i$.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>i$.byId(this.client,$.id))}async summaries(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:i$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return i$.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class _x{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,Y(await this.client.storage.meetingCreate({body:$})))}async list(){return Y(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return Y(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,Y(await this.client.storage.meetingLookup({path:{token:$}})))}}class IO extends P{async fetch(){return Y(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.id,O)}static list($,O){return c(async(j)=>{let x=Y(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>IO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>A.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?A.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class Mx{client;constructor($){this.client=$}byId($){return IO.byId(this.client,$)}list($){return IO.list(this.client,$)}async markSeen($){Y(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Y(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Y(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Y(await this.client.notification.getNotificationTypePreferences())}async enableType($){Y(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Y(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Ax{client;constructor($){this.client=$}async list(){let{data:$}=Y(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Y(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Y(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Y(await this.client.storage.reorderPinsHandler({body:$}))}}class Px{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class MO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new MO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class GO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return Y(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Y(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new GO($,j.id,j)}static byId($,O){return new GO($,O)}static fromRecord($,O){return new GO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return Y(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Y(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Y(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Cx{client;constructor($){this.client=$}async list($){return Y(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return GO.fromRecord(this.client,x)})}create($){return GO.create(this.client,$)}definition($){return GO.byId(this.client,$)}async bulkEntityProperties($){return Y(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Y(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return Y(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Y(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Y(await this.client.properties.listTags({}))}}function Fx($){return k($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function P7($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Fx)})).with({type:"cron"},Fx).with({type:"events"},Fx).exhaustive()}class h$ extends P{static byId($,O){return new h$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new h$($,O.id,O)}async fetch(){return Y(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>A.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?h$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Y($))}async shareAsTemplate($){return this.toTemplate(Y(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return h$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...wj($),enabled:$.enabled??!0}})))}toTemplate($){return new $2(this,A.byId(this.client,$.author),$)}async stopSharingTemplate(){Y(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:wj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Y(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>l.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Ex(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class $2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class Ex{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function wj($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:P7($.trigger),task:{...O}}}class wx{client;constructor($){this.client=$}byId($){return h$.byId(this.client,$)}async create($){return h$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...wj($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>h$.from(this.client,O))}}class qx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}summaries($){return Q$.summaries(this.client,$)}findSimilar($){return Q$.findSimilar(this.client,$)}forPullRequest($){return Q$.forPullRequest(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class fx{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class bx{client;constructor($){this.client=$}async get($){return Y(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Y(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class kx{client;constructor($){this.client=$}byId($){return A.byId(this.client,$)}me(){return A.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=Y(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:G}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(G.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(A.fromName(this.client,J))}}return K}}class YO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Y(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Y(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new YO($,j.id,j,j.signing_secret)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>A.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class gx{client;constructor($){this.client=$}create($){return YO.create(this.client,$)}byId($){return YO.byId(this.client,$)}async list(){let{webhooks:$}=Y(await this.client.storage.listWebhooks());return $.map((O)=>YO.fromRecord(this.client,O))}}class AO extends P{static byId($,O){return new AO($,O)}static from($,O){return new AO($,O.id,O)}async fetch(){let{account:$}=Y(await this.client.storage.whatsappAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class yx{client;constructor($){this.client=$}async account(){let{account:$}=Y(await this.client.storage.whatsappAccount());return $?AO.from(this.client,$):void 0}async chats(){return Y(await this.client.storage.whatsappChats()).chats.map(($)=>UO.from(this.client,$))}}function vx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function O2($,O,j){let x=[];for(let S of vx(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:w.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:K$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new m$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:J$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:KO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var j2="00000000-0000-0000-0000-000000000000",hx={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},qj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),x2=($,O)=>$==null?O:{"&":[$,O]};function mx($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){mx(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{mx(Z,`${O}.${S}[${X}]`)})}class fj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Y),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(hx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(hx).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)mx($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:j2}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=Y(await this.client.email.listLinks()),K=S.filter((X)=>qj(X.email_address)===qj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=x2(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(hx))if(!x.includes(S))O[K]={l:{[Z]:j2}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Q)=>qj(Q.label)===qj(G.label.trim())&&(!G.scope||Q.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((G)=>({l:{pd:G.definitionId,v:{so:G.id}}})).reduce((G,L)=>G===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[G,L]},void 0);O.propf=x2(O.propf,X)}return O}}class ux{client;constructor($){this.client=$}async page($={}){let O=new fj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new fj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Y(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>vx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>O2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function S2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`@@ -54,7 +54,7 @@ async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre`);U=y.pop()??"";for(let a of y){let i=a.split(``),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var Q4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},J4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},V4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},E0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(J4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=Q4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},w0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=V4(x),X=Object.entries(S).map(([G,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var W4=/\{[^{}]+\}/g,B4=({path:$,url:O})=>{let j=O,x=O.match(W4);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,E0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,w0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},GS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=B4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function E1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var YS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var QS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=E0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=w0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=yO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},JS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},L4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function VS($){for(let O of $.security??[]){if(L4($,O.name))continue;let j=await YS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var w1=($)=>GS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:QS($.querySerializer),url:$.url}),q1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=f0($.headers,O.headers),j},N4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},f0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?N4(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class q0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var WS=()=>({error:new q0,request:new q0,response:new q0}),U4=QS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),z4={"Content-Type":"application/json"},Jj=($={})=>({...F1,headers:z4,parseAs:"auto",querySerializer:U4,...$});var Vj=($={})=>{let O=q1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=q1(O,Q),j()},S=WS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:f0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await VS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=w1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:E1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?JS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return KS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:E1(I),url:z})};return{buildUrl:(Q)=>w1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var BS=Vj(Jj());class LS{client;constructor($){this.client=$?.client??BS}}class NS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class b0 extends LS{static __registry=new NS;constructor($){super($);b0.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}taskSimilaritySearchHandler($){return($.client??this.client).post({url:"/documents/similarity_search",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}externalChats($){return($?.client??this.client).get({url:"/external-chats",...$})}externalChatAdd($){return($.client??this.client).post({url:"/external-chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRemove($){return($.client??this.client).delete({url:"/external-chats/{chat_id}",...$})}externalChat($){return($.client??this.client).get({url:"/external-chats/{chat_id}",...$})}externalChatUpload($){return($.client??this.client).post({...C1,url:"/external-chats/{chat_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}externalChatDelivery($){return($.client??this.client).post({url:"/external-chats/{chat_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessages($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages",...$})}externalChatMessageAttachments($){return($.client??this.client).post({url:"/external-chats/{chat_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessage($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages/{message_id}",...$})}externalChatPermissions($){return($.client??this.client).get({url:"/external-chats/{chat_id}/permissions",...$})}externalChatUpdatePermissions($){return($.client??this.client).patch({url:"/external-chats/{chat_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRead($){return($.client??this.client).post({url:"/external-chats/{chat_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatSends($){return($.client??this.client).get({url:"/external-chats/{chat_id}/sends",...$})}externalChatSend($){return($.client??this.client).post({url:"/external-chats/{chat_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}whatsappAccount($){return($?.client??this.client).get({url:"/whatsapp/account",...$})}whatsappChats($){return($?.client??this.client).get({url:"/whatsapp/chats",...$})}whatsappConnect($){return($.client??this.client).post({url:"/whatsapp/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappDisconnect($){return($.client??this.client).post({url:"/whatsapp/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappCancelPairing($){return($.client??this.client).delete({url:"/whatsapp/pairing/{id}",...$})}whatsappPairing($){return($.client??this.client).get({url:"/whatsapp/pairing/{id}",...$})}whatsappPasskey($){return($.client??this.client).post({url:"/whatsapp/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function US({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var Q4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},J4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},V4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},E0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(J4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=Q4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},w0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=V4(x),X=Object.entries(S).map(([G,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var W4=/\{[^{}]+\}/g,B4=({path:$,url:O})=>{let j=O,x=O.match(W4);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,E0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,w0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},GS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=B4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function E1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var YS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var QS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=E0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=w0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=yO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},JS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},L4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function VS($){for(let O of $.security??[]){if(L4($,O.name))continue;let j=await YS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var w1=($)=>GS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:QS($.querySerializer),url:$.url}),q1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=f0($.headers,O.headers),j},N4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},f0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?N4(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class q0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var WS=()=>({error:new q0,request:new q0,response:new q0}),U4=QS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),z4={"Content-Type":"application/json"},Jj=($={})=>({...F1,headers:z4,parseAs:"auto",querySerializer:U4,...$});var Vj=($={})=>{let O=q1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=q1(O,Q),j()},S=WS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:f0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await VS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=w1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:E1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?JS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return KS({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:E1(I),url:z})};return{buildUrl:(Q)=>w1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var BS=Vj(Jj());class LS{client;constructor($){this.client=$?.client??BS}}class NS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class b0 extends LS{static __registry=new NS;constructor($){super($);b0.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}taskSimilaritySearchHandler($){return($.client??this.client).post({url:"/documents/similarity_search",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}externalChats($){return($?.client??this.client).get({url:"/external-chats",...$})}externalChatAdd($){return($.client??this.client).post({url:"/external-chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRemove($){return($.client??this.client).delete({url:"/external-chats/{chat_id}",...$})}externalChat($){return($.client??this.client).get({url:"/external-chats/{chat_id}",...$})}externalChatUpload($){return($.client??this.client).post({...C1,url:"/external-chats/{chat_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}externalChatDelivery($){return($.client??this.client).post({url:"/external-chats/{chat_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessages($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages",...$})}externalChatMessageAttachments($){return($.client??this.client).post({url:"/external-chats/{chat_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessage($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages/{message_id}",...$})}externalChatPermissions($){return($.client??this.client).get({url:"/external-chats/{chat_id}/permissions",...$})}externalChatUpdatePermissions($){return($.client??this.client).patch({url:"/external-chats/{chat_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRead($){return($.client??this.client).post({url:"/external-chats/{chat_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatSends($){return($.client??this.client).get({url:"/external-chats/{chat_id}/sends",...$})}externalChatSend($){return($.client??this.client).post({url:"/external-chats/{chat_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}whatsappAccount($){return($?.client??this.client).get({url:"/whatsapp/account",...$})}whatsappChats($){return($?.client??this.client).get({url:"/whatsapp/chats",...$})}whatsappConnect($){return($.client??this.client).post({url:"/whatsapp/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappDisconnect($){return($.client??this.client).post({url:"/whatsapp/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappStartLookup($){return($.client??this.client).post({url:"/whatsapp/lookups",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappLookup($){return($.client??this.client).get({url:"/whatsapp/lookups/{id}",...$})}whatsappCancelPairing($){return($.client??this.client).delete({url:"/whatsapp/pairing/{id}",...$})}whatsappPairing($){return($.client??this.client).get({url:"/whatsapp/pairing/{id}",...$})}whatsappPasskey($){return($.client??this.client).post({url:"/whatsapp/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function US({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`diff --git a/crates/macro_db_client/migrations/20261030150403_whatsapp_lookup.sql b/crates/macro_db_client/migrations/20261030150403_whatsapp_lookup.sqlnew file mode 100644index 0000000000..a27e8b108a--- /dev/null+++ b/crates/macro_db_client/migrations/20261030150403_whatsapp_lookup.sql@@ -0,0 +1,16 @@+-- An owner asking whether a phone number has a WhatsApp account, to start a+-- direct chat with it. DSS records the request; the session service holding+-- the account asks WhatsApp and records the answer. Rows count toward the+-- per-account lookup budget and are deleted once outside it.+CREATE TABLE whatsapp_lookup (+ id uuid PRIMARY KEY,+ account_id uuid NOT NULL REFERENCES whatsapp_linked_account(id) ON DELETE CASCADE,+ phone_number text NOT NULL CHECK (phone_number ~ '^[+][1-9][0-9]{6,14}$'),+ state text NOT NULL CHECK (state IN ('pending', 'found', 'not_on_whatsapp', 'failed')),+ chat_jid text CHECK (chat_jid ~ '^[0-9]+@s[.]whatsapp[.]net$'),+ created_at timestamptz NOT NULL DEFAULT now(),+ completed_at timestamptz,+ CHECK ((state = 'found') = (chat_jid IS NOT NULL)),+ CHECK ((state = 'pending') = (completed_at IS NULL))+);+CREATE INDEX whatsapp_lookup_account_created ON whatsapp_lookup(account_id, created_at);diff --git a/crates/whatsapp_e2e/src/test.rs b/crates/whatsapp_e2e/src/test.rsindex 3162bbf7f3..f8971f560b 100644--- a/crates/whatsapp_e2e/src/test.rs+++ b/crates/whatsapp_e2e/src/test.rs@@ -31,6 +31,7 @@ use super::*;mod direct_chats;mod group_kinds;mod message_types;+mod new_chats;const TIMEOUT: Duration = Duration::from_secs(60);/// A test user's id, typed.diff --git a/crates/whatsapp_e2e/src/test/new_chats.rs b/crates/whatsapp_e2e/src/test/new_chats.rsnew file mode 100644index 0000000000..20414611f5--- /dev/null+++ b/crates/whatsapp_e2e/src/test/new_chats.rs@@ -0,0 +1,137 @@+//! Starting a chat with someone never written to: their number looked up,+//! the chat added and messaged first from Macro, and their answer by LID+//! landing in the same chat.++use whatsapp_linked::domain::models::{Lookup, LookupState};++use super::*;++/// The lookup once WhatsApp answered it.+async fn answered(world: &World, lookup: &Lookup) -> Lookup {+ let answered = wait_for_rows(&world.pool, TIMEOUT, || async {+ let read = world+ .linked+ .lookup_state(&person(ALICE), lookup.id, SendAuthority::Human)+ .await+ .unwrap();+ (read.state != LookupState::Pending).then_some(read)+ })+ .await;+ world.expect(answered, "WhatsApp answers the lookup").await+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_looked_up_number_is_added_messaged_and_answers_in_the_same_chat(pool: PgPool) {+ let world = World::new(pool).await;+ let replica = world.replica().await;+ world.pair(ALICE, &world.alice).await;+ // In no group with Alice and never written to.+ let dana = world.whatsapp.add_user("15557770001", "Dana").await;+ let phone = format!("+{}", dana.phone());++ let lookup = world+ .linked+ .lookup(&person(ALICE), &phone, SendAuthority::Human)+ .await+ .unwrap();+ let found = answered(&world, &lookup).await;+ assert_eq!(+ (found.state, found.chat_jid.clone()),+ (LookupState::Found, Some(dana.jid().to_string()))+ );+ let nobody = world+ .linked+ .lookup(&person(ALICE), "+5550009", SendAuthority::Human)+ .await+ .unwrap();+ assert_eq!(+ answered(&world, &nobody).await.state,+ LookupState::NotOnWhatsApp+ );++ let listed = world.linked.chats(&person(ALICE)).await.unwrap().chats;+ let chat = listed+ .iter()+ .find(|chat| Some(&chat.jid) == found.chat_jid.as_ref())+ .expect("the found number is in the chat list");+ assert_eq!(+ (+ chat.kind,+ chat.name.as_str(),+ chat.phone_number.as_deref(),+ chat.last_activity_at,+ chat.can_add+ ),+ (+ ExternalChatKind::Direct,+ phone.as_str(),+ Some(phone.as_str()),+ None,+ true+ )+ );+ let binding = world+ .external+ .add(+ &person(ALICE),+ &AddChat {+ provider: ExternalChatProvider::WhatsApp,+ remote_id: chat.jid.clone(),+ kind: ExternalChatKind::Direct,+ },+ SendAuthority::Human,+ )+ .await+ .unwrap();+ assert_eq!(+ backfill_state(+ &world,+ &binding,+ &["done", "waiting_for_message", "pending"]+ )+ .await+ .0,+ "done",+ "nothing was ever written, so there is nothing to wait for"+ );++ // The first message ever: the client fetches Dana's devices and keys.+ let send = world.send(ALICE, &binding, "hi Dana, it's Alice").await;+ dana.wait_for_message(TIMEOUT, |message| {+ message.text() == Some("hi Dana, it's Alice")+ })+ .await+ .expect("Dana's phone receives Alice's first message");+ world+ .wait_send(send, &["accepted", "sent", "delivered", "read"])+ .await;++ let reply = dana+ .send_text(&world.alice.lid(), "hi Alice!")+ .await+ .unwrap();+ assert_eq!(world.timeline(&binding, &reply).await, ["hi Alice!"]);+ let direct_chats = sqlx::query_scalar!(+ r#"SELECT c.chat_jid FROM whatsapp_chat c JOIN whatsapp_linked_account a ON a.id = c.account_id+ WHERE a.user_id = $1 AND c.kind = 'direct'"#,+ ALICE+ )+ .fetch_all(&world.pool)+ .await+ .unwrap();+ assert_eq!(+ direct_chats,+ [dana.jid().to_string()],+ "Dana's LID is the same person, not a second chat"+ );+ let added = sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM external_chat WHERE user_id = $1 AND kind = 'direct'"#,+ ALICE+ )+ .fetch_one(&world.pool)+ .await+ .unwrap();+ assert_eq!(added, 1);++ replica.drain(TIMEOUT).await.unwrap();+}diff --git a/crates/whatsapp_e2e/src/watch_tables.sql b/crates/whatsapp_e2e/src/watch_tables.sqlindex fcdf54a23c..0aedc7be7d 100644--- a/crates/whatsapp_e2e/src/watch_tables.sql+++ b/crates/whatsapp_e2e/src/watch_tables.sql@@ -30,3 +30,5 @@ CREATE TRIGGER e2e_changed AFTER INSERT OR UPDATE OR DELETE ON whatsapp_chatFOR EACH STATEMENT EXECUTE FUNCTION e2e_notify_changed();CREATE TRIGGER e2e_changed AFTER INSERT OR UPDATE OR DELETE ON external_chat_poll_voteFOR EACH STATEMENT EXECUTE FUNCTION e2e_notify_changed();+CREATE TRIGGER e2e_changed AFTER INSERT OR UPDATE OR DELETE ON whatsapp_lookup+ FOR EACH STATEMENT EXECUTE FUNCTION e2e_notify_changed();diff --git a/crates/whatsapp_fake_server/src/state.rs b/crates/whatsapp_fake_server/src/state.rsindex 8b56036b39..63cc81b330 100644--- a/crates/whatsapp_fake_server/src/state.rs+++ b/crates/whatsapp_fake_server/src/state.rs@@ -715,7 +715,9 @@ impl State {.get_children().iter().filter_map(|user| {- let requested = attr_jid(user, "jid")?;+ let Some(requested) = attr_jid(user, "jid") else {+ return self.contact_lookup(user);+ };let phone = self.phone_of(&requested)?;let record = self.users.get(&phone)?;let lid = requested.server == HIDDEN_USER_SERVER;@@ -777,6 +779,40 @@ impl State {)],)}++ /// Whether a phone number (`<contact>+<digits>@c.us</contact>`, as+ /// `IsOnWhatsApp` asks) is registered, answered LID-first like WhatsApp:+ /// the LID as `jid` with the number as `pn_jid`. Unknown numbers are `out`.+ fn contact_lookup(&self, user: &Node) -> Option<Node> {+ let contact = user.get_child_by_tag(&["contact"]);+ let query = match &contact.content {+ Some(NodeContent::String(query)) => query.clone(),+ Some(NodeContent::Bytes(query)) => String::from_utf8_lossy(query).into_owned(),+ _ => return None,+ };+ let phone = query.strip_prefix('+')?.strip_suffix("@c.us")?;+ let answer = |user_attrs: Vec<(&str, AttributeValue)>, registered: &str| {+ node(+ "user",+ user_attrs,+ children(vec![node(+ "contact",+ vec![("type", text(registered))],+ bytes(query.as_bytes()),+ )]),+ )+ };+ Some(match self.users.get(phone) {+ Some(record) => answer(+ vec![+ ("jid", jid(&device_jid(&record.lid, 0, true))),+ ("pn_jid", jid(&device_jid(&record.phone, 0, false))),+ ],+ "in",+ ),+ None => answer(vec![("jid", jid(&device_jid(phone, 0, false)))], "out"),+ })+ }}fn with_error(mut ack: Node, code: u16) -> Node {diff --git a/crates/whatsapp_linked/AGENTS.md b/crates/whatsapp_linked/AGENTS.mdindex d6fb6aa6c6..cb89dd514a 100644--- a/crates/whatsapp_linked/AGENTS.md+++ b/crates/whatsapp_linked/AGENTS.md@@ -41,10 +41,20 @@ They share no HTTP: only MacroDB rows and `NOTIFY` (`external_chat`'sadded chats (`backfill_*` columns on `external_chat`; limits`BACKFILL_MESSAGE_LIMIT` / `BACKFILL_MAX_AGE_DAYS` in `models.rs`). Theanchor is the chat's `whatsapp_chat.anchor`, else the newest stored message- the account saw; without one the group is `waiting_for_message` until a chat- update brings one. History+ the account saw; without one a group is `waiting_for_message` until a chat+ update brings one, and a direct chat (a saved contact, a looked-up number)+ is added `done`, reopened to `pending` only by an anchor older than its+ adoption while nothing was imported. Saved contacts are chat-list rows with no activity. Historymessages skip the adoption-time boundary but only reach the account owner'sown groups (`observed_bindings_in`).+- `src/outbound/pg/lookups.rs`: phone-number lookups (`whatsapp_lookup`,+ `POST`/`GET /whatsapp/lookups`): DSS records one (E.164 `PhoneNumber` in+ `domain/jid.rs`, human sessions only, `LOOKUP_LIMIT` per+ `LOOKUP_WINDOW_MINUTES`, a pending one of the same number is reused) and+ signals `whatsapp_lookup_requested`; the session records the answer, and a+ found number joins the chat list so `adopt` accepts it unchanged. Pending+ past `LOOKUP_EXPIRY_SECONDS` reads `failed`; rows go with the account's+ consent and after the window.- `src/outbound/pg/sends.rs`: enqueue, claim, dispatch fence, outcome. Arepeated intent key returns the stored send before any other check.- `src/signals.rs`: the DSS ↔ session-service `NOTIFY` channels; payloads,@@ -59,7 +69,8 @@ They share no HTTP: only MacroDB rows and `NOTIFY` (`external_chat`'sstatic `file_id`), then `*_external_chat.sql` (the generic `external_chat*`tables, the view rule `external_chat_access_level` that entity_access alsocalls, and `whatsapp_roster`/`whatsapp_chat_membership`; released files- queue in `external_chat_file_deletion`) and its entity type validation.+ queue in `external_chat_file_deletion`) and its entity type validation, then+ `*_whatsapp_lookup.sql` (phone-number lookups).Deleting a user cascades to their account,chats (with their grants, entity record and sharing settings) and sends;aliases outlive the account that saw them.diff --git a/crates/whatsapp_linked/src/domain/events.rs b/crates/whatsapp_linked/src/domain/events.rsindex 7d5f985878..e7fa7bbe78 100644--- a/crates/whatsapp_linked/src/domain/events.rs+++ b/crates/whatsapp_linked/src/domain/events.rs@@ -1,7 +1,10 @@//! Types exchanged in-process with the WhatsApp session service. They carry no//! whatsmeow types: the session service maps protocol events onto them.-use super::models::{Identity, PairingState};+use super::{+ jid::PhoneNumber,+ models::{Identity, PairingState},+};use chrono::{DateTime, Utc};use external_chat::domain::{models::{@@ -470,3 +473,29 @@ pub struct HistoryPage {/// The phone says there is nothing older.pub complete: bool,}++/// A phone-number lookup the account's session should answer.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct LookupWork {+ /// The lookup.+ pub id: Uuid,+ /// The number to ask WhatsApp about.+ pub phone_number: PhoneNumber,+}++/// What WhatsApp answered about a number.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum LookupAnswer {+ /// Registered as this phone-number JID, with the name WhatsApp or the+ /// address book gives it.+ Found {+ /// Phone-number JID.+ jid: String,+ /// Business, address-book or WhatsApp name, when known.+ name: Option<String>,+ },+ /// No WhatsApp account has this number.+ NotOnWhatsApp,+ /// The question could not be asked or was not answered.+ Failed,+}diff --git a/crates/whatsapp_linked/src/domain/jid.rs b/crates/whatsapp_linked/src/domain/jid.rsindex 13bbfff525..c7e3a1f425 100644--- a/crates/whatsapp_linked/src/domain/jid.rs+++ b/crates/whatsapp_linked/src/domain/jid.rs@@ -75,6 +75,36 @@ impl<'a> Jid<'a> {}}+/// Shortest and longest E.164 numbers WhatsApp registers, in digits.+const PHONE_DIGITS: std::ops::RangeInclusive<usize> = 7..=15;++/// A phone number in E.164 form (`+<country code><number>`, no spacing).+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PhoneNumber(String);++fn e164(input: &str) -> IResult<&str, &str> {+ all_consuming(preceded(char('+'), digits)).parse(input)+}++impl PhoneNumber {+ /// Accept only E.164: `+`, then 7 to 15 digits, the first not `0`.+ pub fn parse(text: &str) -> Option<Self> {+ let (_, digits) = e164(text).ok()?;+ (PHONE_DIGITS.contains(&digits.len()) && !digits.starts_with('0'))+ .then(|| Self(text.to_owned()))+ }++ /// The number as stored and shown, `+<digits>`.+ pub fn as_str(&self) -> &str {+ &self.0+ }++ /// The person's phone-number JID.+ pub fn jid(&self) -> String {+ format!("{}@s.whatsapp.net", self.0.trim_start_matches('+'))+ }+}+/// A group JID.pub fn is_group_jid(text: &str) -> bool {Jid::parse(text).is_some_and(|jid| jid.kind == JidKind::Group)diff --git a/crates/whatsapp_linked/src/domain/jid/test.rs b/crates/whatsapp_linked/src/domain/jid/test.rsindex cd150205f5..ad9dd6f723 100644--- a/crates/whatsapp_linked/src/domain/jid/test.rs+++ b/crates/whatsapp_linked/src/domain/jid/test.rs@@ -37,3 +37,26 @@ fn only_phone_number_jids_have_a_number() {assert_eq!(phone_number("987654321@lid"), None);assert_eq!(phone_number("[email protected]"), None);}++#[test]+fn phone_numbers_are_strict_e164() {+ let digits = |count: usize| "1".repeat(count);+ for (text, valid) in [+ (format!("+{}", digits(*PHONE_DIGITS.start())), true),+ (format!("+{}", digits(*PHONE_DIGITS.end())), true),+ (format!("+{}", digits(PHONE_DIGITS.start() - 1)), false),+ (format!("+{}", digits(PHONE_DIGITS.end() + 1)), false),+ ("+0555000".to_owned(), false),+ ("5550001".to_owned(), false),+ ("+555 0001".to_owned(), false),+ ("+555-0001".to_owned(), false),+ ("++5550001".to_owned(), false),+ ("+".to_owned(), false),+ (String::new(), false),+ ] {+ assert_eq!(PhoneNumber::parse(&text).is_some(), valid, "{text}");+ }+ let phone = PhoneNumber::parse("+5550001").unwrap();+ assert_eq!(phone.as_str(), "+5550001");+ assert_eq!(phone.jid(), format!("{}@s.whatsapp.net", "5550001"));+}diff --git a/crates/whatsapp_linked/src/domain/models.rs b/crates/whatsapp_linked/src/domain/models.rsindex a9ef701f2d..4ad1ba4ad0 100644--- a/crates/whatsapp_linked/src/domain/models.rs+++ b/crates/whatsapp_linked/src/domain/models.rs@@ -317,8 +317,12 @@ pub struct Chat {/// Group: the subject, or member names for an unnamed group. Direct: the/// contact or WhatsApp name, else `+<phone>`. Always non-empty.pub name: String,+ /// The other person's phone number (`+<digits>`) of a direct chat, when+ /// WhatsApp told us it.+ pub phone_number: Option<String>,/// Newest activity WhatsApp reported (message or history sync); `null`- /// when unknown. The list is sorted by it, newest first, unknown last.+ /// when unknown, as for saved contacts never messaged. The list is+ /// sorted by it, newest first, unknown last.pub last_activity_at: Option<DateTime<Utc>>,/// Archived in WhatsApp.pub archived: bool,@@ -348,6 +352,72 @@ pub struct ChatList {pub chats: Vec<Chat>,}+/// Where a phone-number lookup is.+#[derive(+ Debug,+ Clone,+ Copy,+ Serialize,+ Deserialize,+ PartialEq,+ Eq,+ strum::IntoStaticStr,+ strum::EnumString,+)]+#[serde(rename_all = "snake_case")]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "schema", schema(as = WhatsAppLookupState))]+#[strum(serialize_all = "snake_case")]+pub enum LookupState {+ /// The account's session has not answered yet.+ Pending,+ /// The number has a WhatsApp account; its direct chat is in the chat list.+ Found,+ /// The number has no WhatsApp account.+ #[serde(rename = "not_on_whatsapp")]+ #[strum(serialize = "not_on_whatsapp")]+ NotOnWhatsApp,+ /// WhatsApp did not answer in time, or the account's session is offline.+ Failed,+}++impl LookupState {+ /// Stable storage spelling.+ pub fn as_str(self) -> &'static str {+ self.into()+ }++ /// Parse the storage spelling.+ pub fn parse(value: &str) -> Option<Self> {+ value.parse().ok()+ }+}++/// The owner asking whether a phone number has a WhatsApp account, to start+/// a direct chat with it.+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "schema", schema(as = WhatsAppLookup))]+pub struct Lookup {+ /// Poll `GET /whatsapp/lookups/{id}` with it.+ pub id: Uuid,+ /// The number asked about, E.164 (`+<digits>`).+ pub phone_number: String,+ /// Progress.+ pub state: LookupState,+ /// Found: the direct chat's JID, now addable from the chat list.+ pub chat_jid: Option<String>,+}++/// Lookups one account may start per [`LOOKUP_WINDOW_MINUTES`]. WhatsApp+/// bans accounts that query many numbers.+pub const LOOKUP_LIMIT: i64 = 20;+/// The window [`LOOKUP_LIMIT`] counts over; older lookups are deleted.+pub const LOOKUP_WINDOW_MINUTES: i32 = 60;+/// A lookup still pending this long after it started has failed.+pub const LOOKUP_EXPIRY_SECONDS: i32 = 60;+/// Most people one text send may @-mention.pub const MENTION_LIMIT: usize = 64;diff --git a/crates/whatsapp_linked/src/domain/ports.rs b/crates/whatsapp_linked/src/domain/ports.rsindex cafc5cbc61..8395729ab0 100644--- a/crates/whatsapp_linked/src/domain/ports.rs+++ b/crates/whatsapp_linked/src/domain/ports.rs@@ -7,7 +7,7 @@//! `NOTIFY` inside the same transaction, so a signal is never sent for a change//! that did not commit.-use super::{events::*, models::*};+use super::{events::*, jid::PhoneNumber, models::*};use async_trait::async_trait;use chrono::{DateTime, Utc};use external_chat::domain::{@@ -69,9 +69,23 @@ pub trait AccountRepository: Send + Sync {) -> ExternalChatResult<bool>;/// The Macro user who linked this account.async fn account_owner(&self, account: Uuid) -> ExternalChatResult<Option<String>>;- /// Delete participant receipts older than [`RECEIPT_RETENTION_DAYS`] and- /// pairings consumed over a day ago (they keep the expected identity).+ /// Delete participant receipts older than [`RECEIPT_RETENTION_DAYS`],+ /// pairings consumed over a day ago (they keep the expected identity) and+ /// lookups older than [`LOOKUP_WINDOW_MINUTES`].async fn expire_retained(&self) -> ExternalChatResult<u64>;+ /// Start asking whether `phone` has a WhatsApp account, for the connected+ /// account at its current generation (`Disconnected` otherwise). Returns+ /// the account's pending lookup of the same number when there is one;+ /// otherwise `RateLimited` once [`LOOKUP_LIMIT`] lookups started within+ /// [`LOOKUP_WINDOW_MINUTES`]. Signals `whatsapp_lookup_requested`.+ async fn begin_lookup(+ &self,+ account: &Account,+ phone: &PhoneNumber,+ ) -> ExternalChatResult<Lookup>;+ /// The account's lookup; one pending past [`LOOKUP_EXPIRY_SECONDS`] reads+ /// as `failed`. `NotFound` for another account's.+ async fn lookup(&self, account: Uuid, lookup: Uuid) -> ExternalChatResult<Lookup>;}/// An external chat bound to a remote chat, as one viewer can see it.@@ -344,6 +358,21 @@ pub trait SessionRepository: Send + Sync {/// The account owner's groups still importing earlier messages.async fn backfill_work(&self, scope: SessionScope) -> ExternalChatResult<Vec<BackfillWork>>;+ /// Lookups waiting for this account's answer, started within+ /// [`LOOKUP_EXPIRY_SECONDS`].+ async fn pending_lookups(&self, scope: SessionScope) -> ExternalChatResult<Vec<LookupWork>>;++ /// Record WhatsApp's answer to a pending lookup; a found number's direct+ /// chat joins the chat list (named when given, never renamed by a lookup+ /// that has no name). Ignores a lookup that is no longer pending.+ /// Signals the owner's chat list.+ async fn complete_lookup(+ &self,+ scope: SessionScope,+ lookup: Uuid,+ answer: &LookupAnswer,+ ) -> ExternalChatResult<()>;+/// No message of the chat is known to start from (`waiting_for_message`).async fn backfill_waiting_for_message(&self,diff --git a/crates/whatsapp_linked/src/domain/service.rs b/crates/whatsapp_linked/src/domain/service.rsindex 4b5d2e84ca..3e4d476e23 100644--- a/crates/whatsapp_linked/src/domain/service.rs+++ b/crates/whatsapp_linked/src/domain/service.rs@@ -1,7 +1,7 @@//! Owner-bound account lifecycle and the WhatsApp chat list, as served by DSS.//! Added chats are `external_chat`'s; [`super::provider`] adds and sends.-use super::{models::*, ports::*};+use super::{jid::PhoneNumber, models::*, ports::*};use external_chat::domain::{models::*, ports::ExternalChatResult};use macro_user_id::user_id::MacroUserIdStr;use std::sync::Arc;@@ -153,6 +153,7 @@ impl WhatsAppService {} else {name},+ phone_number: super::jid::phone_number(&chat.jid),jid: chat.jid,kind: chat.kind,last_activity_at: chat.last_activity_at,@@ -173,6 +174,7 @@ impl WhatsAppService {jid: info.jid.clone(),kind: ExternalChatKind::Group,name: String::new(),+ phone_number: None,last_activity_at: None,archived: false,pinned: false,@@ -214,7 +216,51 @@ impl WhatsAppService {Ok(ChatList { chats })}- /// Delete old participant receipts and old consumed pairings.+ /// Ask whether a phone number has a WhatsApp account, to start a direct+ /// chat with someone not in the chat list. Only on the owner's explicit+ /// action (a human session): WhatsApp bans accounts that query many+ /// numbers, so lookups are also limited per account.+ #[tracing::instrument(+ name = "whatsapp.linked.lookup",+ skip_all,+ err,+ fields(lookup_id, account_id)+ )]+ pub async fn lookup(+ &self,+ user: &MacroUserIdStr<'_>,+ phone_number: &str,+ authority: SendAuthority,+ ) -> ExternalChatResult<Lookup> {+ human(authority)?;+ let phone = PhoneNumber::parse(phone_number).ok_or(ExternalChatError::Invalid(+ "enter the phone number with its country code, starting with +",+ ))?;+ let (account, _) = connected(self.accounts.as_ref(), user).await?;+ let lookup = self.accounts.begin_lookup(&account, &phone).await?;+ let span = tracing::Span::current();+ span.record("lookup_id", tracing::field::display(lookup.id));+ span.record("account_id", tracing::field::display(account.id));+ Ok(lookup)+ }++ /// Poll the owner's lookup.+ pub async fn lookup_state(+ &self,+ user: &MacroUserIdStr<'_>,+ lookup: Uuid,+ authority: SendAuthority,+ ) -> ExternalChatResult<Lookup> {+ human(authority)?;+ let account = self+ .accounts+ .owned_account(user)+ .await?+ .ok_or(ExternalChatError::NotFound)?;+ self.accounts.lookup(account.id, lookup).await+ }++ /// Delete old participant receipts, old consumed pairings and lookups.pub async fn expire_retained(&self) -> ExternalChatResult<u64> {self.accounts.expire_retained().await}diff --git a/crates/whatsapp_linked/src/domain/session.rs b/crates/whatsapp_linked/src/domain/session.rsindex 028ec86c35..96b49009e5 100644--- a/crates/whatsapp_linked/src/domain/session.rs+++ b/crates/whatsapp_linked/src/domain/session.rs@@ -294,6 +294,31 @@ impl SessionService {Ok(work)}+ /// Phone-number lookups the account's session should answer now.+ pub async fn pending_lookups(+ &self,+ scope: SessionScope,+ ) -> ExternalChatResult<Vec<LookupWork>> {+ self.repository.pending_lookups(scope).await+ }++ /// Record what WhatsApp answered about a looked-up number; a registered+ /// number's direct chat joins the chat list, ready to add.+ #[tracing::instrument(name = "whatsapp.session.complete_lookup", skip_all, err, fields(account_id = %scope.account_id, lookup_id = %lookup))]+ pub async fn complete_lookup(+ &self,+ scope: SessionScope,+ lookup: Uuid,+ answer: &LookupAnswer,+ ) -> ExternalChatResult<()> {+ if let LookupAnswer::Found { jid, .. } = answer+ && Jid::parse(jid).is_none_or(|jid| jid.kind != JidKind::Phone)+ {+ return Err(ExternalChatError::Invalid("a lookup found no phone-number JID").into());+ }+ self.repository.complete_lookup(scope, lookup, answer).await+ }+/// No message of an added chat is known to start importing from.#[tracing::instrument(name = "whatsapp.session.backfill_waiting_for_message", skip_all, err, fields(account_id = %scope.account_id, chat_id = %group))]pub async fn backfill_waiting_for_message(diff --git a/crates/whatsapp_linked/src/inbound/router.rs b/crates/whatsapp_linked/src/inbound/router.rsindex b99fa7d641..f02c6c15ac 100644--- a/crates/whatsapp_linked/src/inbound/router.rs+++ b/crates/whatsapp_linked/src/inbound/router.rs@@ -60,6 +60,15 @@ pub struct DisconnectRequest {pub authorization_generation: i64,}+/// A phone number to start a direct chat with.+#[derive(Deserialize, Serialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+#[schema(as = WhatsAppLookupRequest)]+pub struct LookupRequest {+ /// E.164: `+`, the country code and the number, without spacing.+ pub phone_number: String,+}+/// The caller's WhatsApp account, pairing and chat list, under `/whatsapp`.pub fn whatsapp_router<Auth, S>(state: WhatsAppRouterState<Auth>) -> Router<S>where@@ -73,7 +82,9 @@ where.route("/disconnect", post(disconnect::<Auth>)).route("/pairing/{id}", get(pairing::<Auth>).delete(cancel::<Auth>)).route("/pairing/{id}/passkey", post(passkey::<Auth>))- .route("/chats", get(chats::<Auth>)),+ .route("/chats", get(chats::<Auth>))+ .route("/lookups", post(start_lookup::<Auth>))+ .route("/lookups/{id}", get(lookup::<Auth>)),).with_state(state)}@@ -202,5 +213,45 @@ pub async fn chats<Auth: MacroAuthorizationService>())}+/// Ask whether a phone number has a WhatsApp account, to start a direct chat+/// with it; poll the lookup until it is no longer `pending`. Found numbers+/// join the chat list, so `POST /external-chats` adds them.+#[utoipa::path(post, path = "/whatsapp/lookups", operation_id = "whatsapp_start_lookup", request_body = LookupRequest, responses((status = 200, body = Lookup)))]+pub async fn start_lookup<Auth: MacroAuthorizationService>(+ State(state): State<WhatsAppRouterState<Auth>>,+ auth: MacroAuthorizationExtractor<Auth, UserOnly>,+ Json(body): Json<LookupRequest>,+) -> Result<Json<Lookup>, ApiError> {+ Ok(Json(+ state+ .service+ .lookup(+ &auth.authorization.macro_user_id,+ &body.phone_number,+ authority(&auth.authorization),+ )+ .await?,+ ))+}++/// Poll the caller's phone-number lookup.+#[utoipa::path(get, path = "/whatsapp/lookups/{id}", operation_id = "whatsapp_lookup", params(("id" = Uuid, Path)), responses((status = 200, body = Lookup)))]+pub async fn lookup<Auth: MacroAuthorizationService>(+ State(state): State<WhatsAppRouterState<Auth>>,+ auth: MacroAuthorizationExtractor<Auth, UserOnly>,+ Path(id): Path<Uuid>,+) -> Result<Json<Lookup>, ApiError> {+ Ok(Json(+ state+ .service+ .lookup_state(+ &auth.authorization.macro_user_id,+ id,+ authority(&auth.authorization),+ )+ .await?,+ ))+}+#[cfg(test)]mod test;diff --git a/crates/whatsapp_linked/src/outbound/pg.rs b/crates/whatsapp_linked/src/outbound/pg.rsindex abb9ed0e90..95a3d15b07 100644--- a/crates/whatsapp_linked/src/outbound/pg.rs+++ b/crates/whatsapp_linked/src/outbound/pg.rs@@ -19,6 +19,7 @@ mod adoptions;mod chats;mod groups;mod ingest;+mod lookups;mod media;mod sends;mod session;@@ -148,5 +149,9 @@ pub(crate) async fn end_consent_in(.execute(&mut **tx).await.map_err(failure)?;+ sqlx::query!("DELETE FROM whatsapp_lookup WHERE account_id = $1", account)+ .execute(&mut **tx)+ .await+ .map_err(failure)?;Ok(())}diff --git a/crates/whatsapp_linked/src/outbound/pg/accounts.rs b/crates/whatsapp_linked/src/outbound/pg/accounts.rsindex 91af3a239f..afcbf00425 100644--- a/crates/whatsapp_linked/src/outbound/pg/accounts.rs+++ b/crates/whatsapp_linked/src/outbound/pg/accounts.rs@@ -375,6 +375,26 @@ impl AccountRepository for PgWhatsAppRepository {.await.map_err(failure)?.rows_affected();- Ok(receipts + pairings)+ let lookups = sqlx::query!(+ "DELETE FROM whatsapp_lookup WHERE created_at < now() - make_interval(mins => $1)",+ crate::domain::models::LOOKUP_WINDOW_MINUTES+ )+ .execute(&self.pool)+ .await+ .map_err(failure)?+ .rows_affected();+ Ok(receipts + pairings + lookups)+ }++ async fn begin_lookup(+ &self,+ account: &Account,+ phone: &crate::domain::jid::PhoneNumber,+ ) -> ExternalChatResult<Lookup> {+ lookups::begin_lookup(&self.pool, account, phone).await+ }++ async fn lookup(&self, account: Uuid, lookup: Uuid) -> ExternalChatResult<Lookup> {+ lookups::lookup_of(&self.pool, account, lookup).await}}diff --git a/crates/whatsapp_linked/src/outbound/pg/adoptions.rs b/crates/whatsapp_linked/src/outbound/pg/adoptions.rsindex a16de5b110..405117eb52 100644--- a/crates/whatsapp_linked/src/outbound/pg/adoptions.rs+++ b/crates/whatsapp_linked/src/outbound/pg/adoptions.rs@@ -42,7 +42,8 @@ impl AdoptionRepository for PgWhatsAppRepository {.await.map_err(failure)?;// Importing starts from a message of the chat; with none known yet- // it waits for the first one.+ // a group waits for the first one, and a direct chat nobody wrote+ // in (a saved contact, a looked-up number) has nothing to import.let row = sqlx::query_as!(ChatRow,r#"INSERT INTO external_chat (id, provider, remote_id, kind, name, user_id, state, share_permission_id, backfill_state)VALUES ($1,'whatsapp',$2,$3,$4,$5,'active',$6,CASE WHEN EXISTS (SELECT 1 FROM whatsapp_chat WHERE account_id = $7 AND chat_jid = $2 AND anchor IS NOT NULL)@@ -50,7 +51,7 @@ impl AdoptionRepository for PgWhatsAppRepository {WHERE g.provider = 'whatsapp' AND g.remote_id = $2 AND m.kind = 'message' AND m.message_id IS NOT NULLAND EXISTS (SELECT 1 FROM whatsapp_message_observation o WHERE o.chat_id = m.chat_idAND o.person_id = m.person_id AND o.source_id = m.source_id AND o.account_id = $7))- THEN 'pending' ELSE 'waiting_for_message' END)+ THEN 'pending' WHEN $3 = 'direct' THEN 'done' ELSE 'waiting_for_message' END)RETURNING id, provider, remote_id, kind, user_id, state, adopted_at"#,id,adoption.jid,adoption.kind.as_ref(),adoption.name,user,permission,account.id).fetch_one(&mut *tx).await.map_err(failure)?;let owner = Owner::from_principal_str(user).map_err(failure)?;diff --git a/crates/whatsapp_linked/src/outbound/pg/chats.rs b/crates/whatsapp_linked/src/outbound/pg/chats.rsindex 59766e1a42..de220aae67 100644--- a/crates/whatsapp_linked/src/outbound/pg/chats.rs+++ b/crates/whatsapp_linked/src/outbound/pg/chats.rs@@ -126,18 +126,24 @@ pub(super) async fn update_chats_in(.map_err(failure)?.rows_affected();let changed = inserted + renamed_rows > 0;- let anchored_jids: Vec<String> = merged+ let (anchored_jids, anchored_at): (Vec<String>, Vec<chrono::DateTime<Utc>>) = merged.values()- .filter(|chat| chat.anchor.is_some())- .map(|chat| chat.jid.clone())- .collect();+ .filter_map(|chat| Some((chat.jid.clone(), chat.anchor.as_ref()?.at)))+ .unzip();+ // A chat waiting for its first message is ready. So is a direct chat added+ // with nothing to import once a message older than its adoption shows the+ // phone has earlier history after all; newer messages arrive live.let ready = sqlx::query_scalar!(- r#"UPDATE external_chat SET backfill_state = 'pending'- WHERE user_id = $1 AND provider = 'whatsapp' AND remote_id = ANY($2) AND state = 'active'- AND backfill_state = 'waiting_for_message'- RETURNING id"#,+ r#"UPDATE external_chat g SET backfill_state = 'pending'+ FROM UNNEST($2::text[], $3::timestamptz[]) AS i(jid, at)+ WHERE g.user_id = $1 AND g.provider = 'whatsapp' AND g.remote_id = i.jid AND g.state = 'active'+ AND (g.backfill_state = 'waiting_for_message'+ OR (g.kind = 'direct' AND g.backfill_state = 'done' AND g.backfill_imported = 0+ AND g.backfill_cursor IS NULL AND i.at < g.adopted_at))+ RETURNING g.id"#,account.user_id,- &anchored_jids+ &anchored_jids,+ &anchored_at).fetch_all(&mut **tx).awaitdiff --git a/crates/whatsapp_linked/src/outbound/pg/lookups.rs b/crates/whatsapp_linked/src/outbound/pg/lookups.rsnew file mode 100644index 0000000000..c19113bedc--- /dev/null+++ b/crates/whatsapp_linked/src/outbound/pg/lookups.rs@@ -0,0 +1,185 @@+//! Phone-number lookups: DSS records the owner's request, the account's+//! session records WhatsApp's answer.++use super::*;+use crate::domain::{+ events::{ChatUpdate, LookupAnswer, LookupWork},+ jid::PhoneNumber,+};++struct LookupRow {+ id: Uuid,+ phone_number: String,+ state: String,+ chat_jid: Option<String>,+}++fn lookup(row: LookupRow) -> ExternalChatResult<Lookup> {+ Ok(Lookup {+ id: row.id,+ phone_number: row.phone_number,+ state: LookupState::parse(&row.state)+ .ok_or_else(|| corrupt(format_args!("lookup state {:?}", row.state)))?,+ chat_jid: row.chat_jid,+ })+}++pub(super) async fn begin_lookup(+ pool: &PgPool,+ account: &Account,+ phone: &PhoneNumber,+) -> ExternalChatResult<Lookup> {+ let mut tx = pool.begin().await.map_err(failure)?;+ // Serializes the budget check per account.+ let current = sqlx::query!(+ "SELECT state, generation FROM whatsapp_linked_account WHERE id = $1 FOR NO KEY UPDATE",+ account.id+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(failure)?+ .ok_or(ExternalChatError::Disconnected)?;+ if account_state(¤t.state)? != AccountState::Connected+ || current.generation != account.authorization_generation+ {+ return Err(ExternalChatError::Disconnected.into());+ }+ let pending = sqlx::query_as!(+ LookupRow,+ r#"SELECT id, phone_number, state, chat_jid FROM whatsapp_lookup+ WHERE account_id = $1 AND phone_number = $2 AND state = 'pending'+ AND created_at > now() - make_interval(secs => $3)+ ORDER BY created_at DESC LIMIT 1"#,+ account.id,+ phone.as_str(),+ f64::from(LOOKUP_EXPIRY_SECONDS)+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(failure)?;+ let row = match pending {+ Some(row) => row,+ None => {+ let started = sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM whatsapp_lookup+ WHERE account_id = $1 AND created_at > now() - make_interval(mins => $2)"#,+ account.id,+ LOOKUP_WINDOW_MINUTES+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(failure)?;+ if started >= LOOKUP_LIMIT {+ return Err(ExternalChatError::RateLimited.into());+ }+ sqlx::query_as!(+ LookupRow,+ r#"INSERT INTO whatsapp_lookup (id, account_id, phone_number, state)+ VALUES ($1, $2, $3, 'pending')+ RETURNING id, phone_number, state, chat_jid"#,+ Uuid::now_v7(),+ account.id,+ phone.as_str()+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(failure)?+ }+ };+ notify(&mut tx, signals::LOOKUP_REQUESTED, account.id).await?;+ tx.commit().await.map_err(failure)?;+ lookup(row)+}++pub(super) async fn lookup_of(+ pool: &PgPool,+ account: Uuid,+ id: Uuid,+) -> ExternalChatResult<Lookup> {+ let row = sqlx::query_as!(+ LookupRow,+ r#"SELECT id, phone_number, chat_jid,+ CASE WHEN state = 'pending' AND created_at <= now() - make_interval(secs => $3)+ THEN 'failed' ELSE state END AS "state!"+ FROM whatsapp_lookup WHERE id = $1 AND account_id = $2"#,+ id,+ account,+ f64::from(LOOKUP_EXPIRY_SECONDS)+ )+ .fetch_optional(pool)+ .await+ .map_err(failure)?+ .ok_or(ExternalChatError::NotFound)?;+ lookup(row)+}++pub(super) async fn pending_lookups_in(+ tx: &mut Transaction<'_, Postgres>,+ account: &Fenced,+) -> ExternalChatResult<Vec<LookupWork>> {+ sqlx::query!(+ r#"SELECT id, phone_number FROM whatsapp_lookup+ WHERE account_id = $1 AND state = 'pending'+ AND created_at > now() - make_interval(secs => $2)+ ORDER BY created_at, id"#,+ account.id,+ f64::from(LOOKUP_EXPIRY_SECONDS)+ )+ .fetch_all(&mut **tx)+ .await+ .map_err(failure)?+ .into_iter()+ .map(|row| {+ Ok(LookupWork {+ id: row.id,+ phone_number: PhoneNumber::parse(&row.phone_number)+ .ok_or_else(|| corrupt(format_args!("lookup phone number")))?,+ })+ })+ .collect()+}++pub(super) async fn complete_lookup_in(+ tx: &mut Transaction<'_, Postgres>,+ account: &Fenced,+ id: Uuid,+ answer: &LookupAnswer,+) -> ExternalChatResult<()> {+ let (state, jid, name) = match answer {+ LookupAnswer::Found { jid, name } => (LookupState::Found, Some(jid), name.clone()),+ LookupAnswer::NotOnWhatsApp => (LookupState::NotOnWhatsApp, None, None),+ LookupAnswer::Failed => (LookupState::Failed, None, None),+ };+ let completed = sqlx::query_scalar!(+ r#"UPDATE whatsapp_lookup SET state = $3, chat_jid = $4, completed_at = now()+ WHERE id = $1 AND account_id = $2 AND state = 'pending'+ AND created_at > now() - make_interval(secs => $5)+ RETURNING id"#,+ id,+ account.id,+ state.as_str(),+ jid,+ f64::from(LOOKUP_EXPIRY_SECONDS)+ )+ .fetch_optional(&mut **tx)+ .await+ .map_err(failure)?;+ if let (Some(_), Some(jid)) = (completed, jid) {+ super::chats::update_chats_in(+ tx,+ account,+ &[ChatUpdate {+ jid: jid.clone(),+ kind: ExternalChatKind::Direct,+ name,+ last_activity_at: None,+ archived: None,+ pinned: None,+ anchor: None,+ create: true,+ }],+ )+ .await?;+ }+ Ok(())+}diff --git a/crates/whatsapp_linked/src/outbound/pg/session.rs b/crates/whatsapp_linked/src/outbound/pg/session.rsindex 3e7ff7d3d4..9fc303022c 100644--- a/crates/whatsapp_linked/src/outbound/pg/session.rs+++ b/crates/whatsapp_linked/src/outbound/pg/session.rs@@ -509,6 +509,32 @@ impl SessionRepository for PgWhatsAppRepository {tx.commit().await.map_err(failure)}+ async fn pending_lookups(&self, scope: SessionScope) -> ExternalChatResult<Vec<LookupWork>> {+ let mut tx = self.pool.begin().await.map_err(failure)?;+ let account = fence_in(&mut tx, scope).await?;+ if account.state != AccountState::Connected {+ return Ok(vec![]);+ }+ let work = lookups::pending_lookups_in(&mut tx, &account).await?;+ tx.commit().await.map_err(failure)?;+ Ok(work)+ }++ async fn complete_lookup(+ &self,+ scope: SessionScope,+ lookup: Uuid,+ answer: &LookupAnswer,+ ) -> ExternalChatResult<()> {+ let mut tx = self.pool.begin().await.map_err(failure)?;+ let account = fence_in(&mut tx, scope).await?;+ if account.state != AccountState::Connected {+ return Ok(());+ }+ lookups::complete_lookup_in(&mut tx, &account, lookup, answer).await?;+ tx.commit().await.map_err(failure)+ }+async fn backfill_requested(&self, scope: SessionScope, group: Uuid) -> ExternalChatResult<()> {let mut tx = self.pool.begin().await.map_err(failure)?;let account = fence_in(&mut tx, scope).await?;diff --git a/crates/whatsapp_linked/src/outbound/pg/test.rs b/crates/whatsapp_linked/src/outbound/pg/test.rsindex b8655d2f4b..b2e2d50d80 100644--- a/crates/whatsapp_linked/src/outbound/pg/test.rs+++ b/crates/whatsapp_linked/src/outbound/pg/test.rs@@ -1129,3 +1129,4 @@ async fn rate_limited_send_never_creates_a_dispatchable_intent(pool: PgPool) {mod chats;mod communities;mod direct;+mod lookups;diff --git a/crates/whatsapp_linked/src/outbound/pg/test/lookups.rs b/crates/whatsapp_linked/src/outbound/pg/test/lookups.rsnew file mode 100644index 0000000000..026d0a3349--- /dev/null+++ b/crates/whatsapp_linked/src/outbound/pg/test/lookups.rs@@ -0,0 +1,368 @@+//! Starting a direct chat with someone not in the chat list: saved contacts+//! listed without activity, and phone-number lookups answered by the session.++use super::*;+use crate::domain::{+ jid::PhoneNumber,+ models::{LOOKUP_LIMIT, LookupState},+};+use chrono::DurationRound;+use external_chat::signals::{self as signals, ChangeSignal};+use sqlx::postgres::PgListener;++// Short numbers (still E.164), so they never read as anyone's real number.+const CUSTOMER: &str = "+5550001";+const DANA: &str = "+5550002";+const STRANGER: &str = "+5550003";+const LATE: &str = "+5550004";++fn contact(jid: &str, name: &str) -> ChatUpdate {+ ChatUpdate {+ jid: jid.to_owned(),+ kind: ExternalChatKind::Direct,+ name: Some(name.to_owned()),+ last_activity_at: None,+ archived: None,+ pinned: None,+ anchor: None,+ create: true,+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn lookups_need_a_valid_number_a_person_and_stay_within_the_budget(pool: PgPool) {+ workspace(&pool).await;+ let (linked, session, _) = services(&pool);+ let alice = pair(&linked, &session, ALICE, ALICE_JID).await;+ let lookup = |phone: &'static str| {+ let whatsapp = linked.whatsapp.clone();+ async move {+ .lookup(&person(ALICE), phone, SendAuthority::Human)+ .await+ }+ };++ for invalid in ["5550002", "+555 0002", "+0555000", "+12"] {+ assert!(matches!(+ lookup(invalid).await.unwrap_err().current_context(),+ ExternalChatError::Invalid(_)+ ));+ }+ assert_eq!(+ linked+ .lookup(&person(ALICE), DANA, SendAuthority::UserApiToken)+ .await+ .unwrap_err()+ .current_context(),+ &ExternalChatError::Forbidden,+ "only the owner's own action looks numbers up"+ );+ assert_eq!(+ linked+ .lookup(&person(BOB), DANA, SendAuthority::Human)+ .await+ .unwrap_err()+ .current_context(),+ &ExternalChatError::Disconnected+ );++ let first = lookup(DANA).await.unwrap();+ assert_eq!(+ (first.phone_number.as_str(), first.state, first.chat_jid),+ (DANA, LookupState::Pending, None)+ );+ assert_eq!(+ lookup(DANA).await.unwrap().id,+ first.id,+ "asking again while pending joins the same lookup"+ );+ assert_eq!(+ session+ .pending_lookups(alice)+ .await+ .unwrap()+ .into_iter()+ .map(|work| (work.id, work.phone_number.as_str().to_owned()))+ .collect::<Vec<_>>(),+ [(first.id, DANA.to_owned())]+ );+ assert_eq!(+ linked+ .lookup_state(&person(BOB), first.id, SendAuthority::Human)+ .await+ .unwrap_err()+ .current_context(),+ &ExternalChatError::NotFound,+ "another person's lookup is not theirs to read"+ );++ for number in 1..LOOKUP_LIMIT {+ let phone = format!("+556{number:04}");+ linked+ .lookup(&person(ALICE), &phone, SendAuthority::Human)+ .await+ .unwrap();+ }+ assert_eq!(+ lookup(STRANGER).await.unwrap_err().current_context(),+ &ExternalChatError::RateLimited+ );+ // An hour later the budget is back, and the old lookups are deleted.+ sqlx::query!("UPDATE whatsapp_lookup SET created_at = now() - interval '61 minutes'")+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(+ linked.whatsapp.expire_retained().await.unwrap(),+ u64::try_from(LOOKUP_LIMIT).unwrap()+ );+ assert_eq!(lookup(STRANGER).await.unwrap().state, LookupState::Pending);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_found_number_joins_the_chat_list_without_clobbering_it(pool: PgPool) {+ workspace(&pool).await;+ let (linked, session, _) = services(&pool);+ let alice = pair(&linked, &session, ALICE, ALICE_JID).await;+ let customer_jid = PhoneNumber::parse(CUSTOMER).unwrap().jid();+ let dana_jid = PhoneNumber::parse(DANA).unwrap().jid();+ let activity = Utc::now().duration_trunc(Duration::seconds(1)).unwrap() - Duration::days(1);+ session+ .update_chats(+ alice,+ &[ChatUpdate {+ last_activity_at: Some(activity),+ ..contact(&customer_jid, "Customer")+ }],+ )+ .await+ .unwrap();+ let start = |phone: &'static str| {+ let whatsapp = linked.whatsapp.clone();+ async move {+ .lookup(&person(ALICE), phone, SendAuthority::Human)+ .await+ .unwrap()+ }+ };+ let known = start(CUSTOMER).await;+ let dana = start(DANA).await;+ let stranger = start(STRANGER).await;+ let late = start(LATE).await;+ session+ .complete_lookup(+ alice,+ known.id,+ &LookupAnswer::Found {+ jid: customer_jid.clone(),+ name: None,+ },+ )+ .await+ .unwrap();+ session+ .complete_lookup(+ alice,+ dana.id,+ &LookupAnswer::Found {+ jid: dana_jid.clone(),+ name: Some("Dana".to_owned()),+ },+ )+ .await+ .unwrap();+ session+ .complete_lookup(alice, stranger.id, &LookupAnswer::NotOnWhatsApp)+ .await+ .unwrap();+ // WhatsApp answered after the person stopped waiting: it stays failed.+ sqlx::query!(+ "UPDATE whatsapp_lookup SET created_at = now() - interval '2 minutes' WHERE id = $1",+ late.id+ )+ .execute(&pool)+ .await+ .unwrap();+ session+ .complete_lookup(alice, late.id, &LookupAnswer::NotOnWhatsApp)+ .await+ .unwrap();+ // A redelivered answer changes nothing.+ session+ .complete_lookup(alice, stranger.id, &LookupAnswer::Failed)+ .await+ .unwrap();+ assert!(matches!(+ session+ .complete_lookup(+ alice,+ stranger.id,+ &LookupAnswer::Found {+ jid: "987654321@lid".to_owned(),+ name: None,+ },+ )+ .await+ .unwrap_err()+ .current_context(),+ ExternalChatError::Invalid(_)+ ));++ let states = |lookup: Uuid| {+ let whatsapp = linked.whatsapp.clone();+ async move {+ let read = whatsapp+ .lookup_state(&person(ALICE), lookup, SendAuthority::Human)+ .await+ .unwrap();+ (read.state, read.chat_jid)+ }+ };+ assert_eq!(+ states(known.id).await,+ (LookupState::Found, Some(customer_jid.clone()))+ );+ assert_eq!(+ states(dana.id).await,+ (LookupState::Found, Some(dana_jid.clone()))+ );+ assert_eq!(+ states(stranger.id).await,+ (LookupState::NotOnWhatsApp, None)+ );+ assert_eq!(states(late.id).await, (LookupState::Failed, None));+ assert!(session.pending_lookups(alice).await.unwrap().is_empty());++ let listed = linked.whatsapp.chats(&person(ALICE)).await.unwrap().chats;+ let summary: Vec<_> = listed+ .iter()+ .map(|chat| {+ (+ chat.jid.as_str(),+ chat.name.as_str(),+ chat.phone_number.as_deref(),+ chat.last_activity_at,+ chat.can_add,+ )+ })+ .collect();+ assert_eq!(+ summary,+ [+ (+ customer_jid.as_str(),+ "Customer",+ Some(CUSTOMER),+ Some(activity),+ true+ ),+ (dana_jid.as_str(), "Dana", Some(DANA), None, true),+ ],+ "a lookup without a name keeps the stored name and activity"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_contact_added_before_anyone_wrote_has_nothing_to_import(pool: PgPool) {+ workspace(&pool).await;+ let (linked, session, _) = services(&pool);+ let alice = pair(&linked, &session, ALICE, ALICE_JID).await;+ let dana_jid = PhoneNumber::parse(DANA).unwrap().jid();+ let mut listener = PgListener::connect_with(&pool).await.unwrap();+ listener.listen(signals::CHANGED).await.unwrap();+ session+ .update_chats(alice, &[contact(&dana_jid, "Dana")])+ .await+ .unwrap();+ // The same address book again changes nothing; a rename does.+ session+ .update_chats(alice, &[contact(&dana_jid, "Dana")])+ .await+ .unwrap();+ session+ .update_chats(alice, &[contact(&dana_jid, "Dana Smith")])+ .await+ .unwrap();+ for _ in 0..2 {+ let notification = listener.recv().await.unwrap();+ assert_eq!(+ ChangeSignal::parse(notification.payload()).unwrap().change,+ Change::Chats {+ account_id: alice.account_id+ }+ );+ }++ let added = linked+ .chats+ .add(+ &person(ALICE),+ &AddChat {+ provider: ExternalChatProvider::WhatsApp,+ remote_id: dana_jid.clone(),+ kind: ExternalChatKind::Direct,+ },+ SendAuthority::Human,+ )+ .await+ .unwrap();+ let name = sqlx::query_scalar!("SELECT name FROM external_chat WHERE id = $1", added.id)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(name, "Dana Smith");+ assert!(+ session.backfill_work(alice).await.unwrap().is_empty(),+ "nobody wrote yet, so there is nothing to wait for"+ );+ let state = sqlx::query_scalar!(+ "SELECT backfill_state FROM external_chat WHERE id = $1",+ added.id+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(state.as_deref(), Some("done"));++ let anchored = |minutes: i64| ChatUpdate {+ anchor: Some(MessageAnchor {+ id: format!("3EB0{minutes:04}"),+ at: Utc::now() + Duration::minutes(minutes),+ from_me: false,+ sender_jid: None,+ }),+ ..contact(&dana_jid, "Dana Smith")+ };+ assert!(+ !session.update_chats(alice, &[anchored(5)]).await.unwrap(),+ "a message after adding arrives live; nothing to import"+ );+ assert!(session.backfill_work(alice).await.unwrap().is_empty());+ sqlx::query!(+ "UPDATE whatsapp_chat SET anchor = NULL WHERE chat_jid = $1",+ dana_jid+ )+ .execute(&pool)+ .await+ .unwrap();+ assert!(+ session.update_chats(alice, &[anchored(-60)]).await.unwrap(),+ "a message from before adding means the phone has earlier history"+ );+ assert_eq!(+ session+ .backfill_work(alice)+ .await+ .unwrap()+ .into_iter()+ .map(|work| (work.chat_id, work.state))+ .collect::<Vec<_>>(),+ [(added.id, BackfillState::Pending)]+ );+}diff --git a/crates/whatsapp_linked/src/signals.rs b/crates/whatsapp_linked/src/signals.rsindex 98eabe79d2..b400594979 100644--- a/crates/whatsapp_linked/src/signals.rs+++ b/crates/whatsapp_linked/src/signals.rs@@ -6,6 +6,8 @@pub const PAIRING_REQUESTED: &str = "whatsapp_pairing_requested";/// `<account_id>`: claim pending sends.pub const SEND_REQUESTED: &str = "whatsapp_send_requested";+/// `<account_id>`: answer pending phone-number lookups.+pub const LOOKUP_REQUESTED: &str = "whatsapp_lookup_requested";/// `<account_id>`: re-read the account's groups.pub const GROUPS_REQUESTED: &str = "whatsapp_roster_requested";/// `<account_id>`: consent or adopted groups changed; re-read the account.diff --git a/docs/agent-guide/external.md b/docs/agent-guide/external.mdindex 4b207e37f7..97f420f0bb 100644--- a/docs/agent-guide/external.md+++ b/docs/agent-guide/external.md@@ -41,7 +41,7 @@ without one, External re-fetches once ~3 s after opening.| Not linked | Outlined WhatsApp row and **Connect**. A signed-out device reads **Reconnect**. A phone can't scan its own screen, so at phone width (touch, under 640px) there is no **Connect**; the row says to open Macro on a computer and scan its code with the phone. Tablets keep **Connect**. || Passkey | When WhatsApp asks for a passkey, the dialog says **Confirm on your desktop**. In Macro desktop, **Confirm with passkey** runs the native `whatsapp_passkey_authenticate` command (its caBLE QR shows in the dialog) and posts the assertion to `/whatsapp/pairing/<id>/passkey`; a returned code then shows to type on the phone. In a browser, **Continue in Macro desktop** opens `macro:///external?whatsappPairing=<id>`, which reopens the same pairing there; closing the browser dialog then doesn't cancel it. || Pairing | Dialog **Link WhatsApp**: a locally encoded QR (`role="img"`, name "Scan this code with WhatsApp on your phone") that follows WhatsApp's rotating codes, four numbered steps, **Cancel**. The dialog carries `ph-no-capture`. When a pairing expires (WhatsApp ran out of codes, ~2.7 minutes, or the 5-minute deadline) while the tab stays visible, the dialog shows **Refreshing code…** and starts a new pairing on its own, up to three times; after that, or if the tab was hidden, the QR square reads **Code expired** with **Show a new code**. A failure (not expiry) says **Linking didn't finish.** with **Show a new code**. |-| Linked | A full-width list like Drive's. Its header has **Search chats** (filters every section by name or phone digits) and a slim account strip: the phone number, "Connected" and a **WhatsApp account options** menu with **Disconnect** (asks to confirm). One account at a time: to switch, disconnect and connect again. Below, the account's WhatsApp chat list (`GET /whatsapp/chats`), newest activity first, one line per chat: a group, person or (announcement group) megaphone icon, the name ("Community · Group", or "Community · Announcements"), "Group" / "Community group" / "Announcement group" / "Direct chat · Archived", and the last activity on the right. Row actions show on hover or keyboard focus (always on touch). Chats sit in folding sections like the sidebar's (**Direct messages**, **Groups**, **Communities** with one section per community), remembered per person; a search opens every section and also lists matching added chats with **Open** (otherwise they are only in the sidebar). Addable chats (direct chats, community groups and disappearing-message groups included) have a one-click **Add to Macro** (no dialog, no name: the Macro chat follows the WhatsApp name; unnamed groups show member names), and groups someone already shared with the viewer as "Shared with you by <owner>" with **Open**. **Can't be added (n)** is collapsed (searching unfolds it) and lists the chat with yourself, communities themselves ("A community has no messages of its own; add one of its groups"), and groups the account left, each with its reason. A refused add shows DSS's specific reason in that chat's row. An account paired before the chat list existed shows only groups and chats with new messages until it is re-linked. |+| Linked | A full-width list like Drive's. Its header has **Search chats and contacts** (filters every section by name or phone digits) and a slim account strip: the phone number, "Connected" and a **WhatsApp account options** menu with **Disconnect** (asks to confirm). One account at a time: to switch, disconnect and connect again. Below, the account's WhatsApp chat list (`GET /whatsapp/chats`), newest activity first, one line per chat: a group, person or (announcement group) megaphone icon, the name ("Community · Group", or "Community · Announcements"), "Group" / "Community group" / "Announcement group" / "Direct chat · <number> · Archived" (the number when the name isn't it), and the last activity on the right. Row actions show on hover or keyboard focus (always on touch). Chats sit in folding sections like the sidebar's (**Direct messages**, **Groups**, **Communities** with one section per community), remembered per person; a search opens every section and also lists matching added chats with **Open** (otherwise they are only in the sidebar). Addable chats (direct chats, community groups and disappearing-message groups included) have a one-click **Add to Macro** (no dialog, no name: the Macro chat follows the WhatsApp name; unnamed groups show member names), and groups someone already shared with the viewer as "Shared with you by <owner>" with **Open**. **Can't be added (n)** is collapsed (searching unfolds it) and lists the chat with yourself, communities themselves ("A community has no messages of its own; add one of its groups"), and groups the account left, each with its reason. Saved contacts nobody wrote to yet (no last activity) are listed apart in a **Contacts** section below the others, name and "Direct chat · <number>", each with **Add to Macro**; search matches them by name or number. **New chat** beside the search (just the icon at phone width) opens **New WhatsApp chat**: a **Phone number** field (spaces, dashes, brackets and a leading `00` are fine; it needs the country code) and **Start chat**, which reads **Looking up…** while WhatsApp answers, then adds and opens the chat; otherwise the field says why ("<number> isn't on WhatsApp.", no answer, the hourly lookup limit, or the add's refusal) and the dialog stays open. A refused add shows DSS's specific reason in that chat's row. An account paired before the chat list existed shows only groups and chats with new messages until it is re-linked. |Cancel sends `DELETE /whatsapp/pairing/<id>`; closing after the phone linksdoes not; closing while a new code is starting cancels that pairing too.@@ -55,6 +55,7 @@ No environment has the WhatsApp session service yet, so intercept DSSThe functional test `apps/web/tests/functional/whatsapp-linked.spec.ts` is thereference mock: it answers `whatsapp/account`, `whatsapp/connect`,`whatsapp/pairing/<id>` (poll and `DELETE`), `whatsapp/chats` (`GET`),+`whatsapp/lookups` (`POST {phoneNumber}`) and `whatsapp/lookups/<id>` (poll),`whatsapp/disconnect`, `external-chats` (`GET` the list; `POST` adds, body`{provider: "whatsapp", remoteId: <jid>, kind}`), the `external-chats/<id>/…`routes and `entities/external_chat/<id>/…`, and flips the pairing to `success`diff --git a/docs/architecture/external-chats.md b/docs/architecture/external-chats.mdindex f3b0ea31f4..633c6f5ee5 100644--- a/docs/architecture/external-chats.md+++ b/docs/architecture/external-chats.md@@ -109,7 +109,8 @@ tables. It reaches a provider only through its `ChatProvider` portoutbox); `ExternalChatService<P: ChatProvider>` is generic over it, with notrait objects or registry. `crates/whatsapp_linked` implements the port(`WhatsAppProvider`) and keeps everything WhatsApp: pairing, the account's-chat list, rosters, ingest, dispatch and the `/whatsapp` router; its ingest+chat list (with saved contacts) and phone-number lookups, rosters, ingest,+dispatch and the `/whatsapp` router; its ingestwrites the generic tables with `external_chat::outbound::pg` helpers.Dependencies point from `whatsapp_linked` to `external_chat`, never back.DSS composes `ExternalChatService<WhatsAppProvider>` indiff --git a/docs/architecture/whatsapp-linked-devices.md b/docs/architecture/whatsapp-linked-devices.mdindex 04c0aafb88..67230a4ab7 100644--- a/docs/architecture/whatsapp-linked-devices.md+++ b/docs/architecture/whatsapp-linked-devices.md@@ -97,10 +97,26 @@ one shared with them by someone else (`shared`, with its owner).and direct chats: name, last activity, archived and pinned, and the newestknown message (the anchor). WhatsApp's history sync right after pairing fillsit (initial, recent and full bundles; push-name bundles rename direct chats);-live messages in any chat bump activity and add new chats; contact, push-name,-archive and pin updates change existing rows. It never holds message content.+live messages in any chat bump activity and add new chats; push-name, archive+and pin updates change existing rows. The phone's saved contacts (address-book+names from app state) are listed as direct chats with no activity, so the owner+can start a chat with someone never written to: all of them on connect and+after each app-state sync, each contact change as it arrives; a row that didn't+change signals nothing. It never holds message content.`GET /whatsapp/chats` merges it with the roster (the roster names groups and decides-which groups can be added), newest first.+which groups can be added), newest first, and gives a direct chat's phone+number.++Anyone else is reached by phone number: `POST /whatsapp/lookups {phoneNumber}`+(E.164; the owner's own session only, at most 20 per account per hour, since+WhatsApp bans accounts that check many numbers) records a `whatsapp_lookup`+and signals `whatsapp_lookup_requested`; the session holding the account asks+WhatsApp once (`IsOnWhatsApp`, which also stores the number's LID pairing) and+records `found`, `not_on_whatsapp` or `failed`. A found number joins the chat+list as a direct chat by phone number, so the ordinary add accepts it; the web+polls `GET /whatsapp/lookups/{id}`, then adds and opens the chat. A lookup still+pending after 60 seconds reads as `failed`. Lookups are deleted an hour later,+and with the account's consent.Direct chats are added like groups (`external_chat.kind = 'direct'`,`remote_id` the other person's JID, by phone number when known) and named after the@@ -118,6 +134,11 @@ messages: WhatsApp sends the full list once, at pairing.Adding a group sets `backfill_state = 'pending'` when a message of the chat isknown to start from (the chat list's anchor, or a stored message the accountsaw), else `waiting_for_message`: nothing to import from until someone posts.+A direct chat with no known message (a saved contact or looked-up number)+starts `done`: there is nothing earlier to import, and its first message+arrives live. If a chat update later brings a message from before the chat+was added (the phone had history after all), it goes back to `pending` once+and imports like any chat.The chat's first message (live, history sync or chat-list update) makes it`pending` and starts the import at once. The owner's account thenimports the chat's earlier messages from the phone, on demand only: it asks fordiff --git a/packages/sdk-docs/reference/generated/storage/types.gen/README.md b/packages/sdk-docs/reference/generated/storage/types.gen/README.mdindex ce340335d4..2ea804991c 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/README.md@@ -2292,6 +2292,12 @@- [WhatsAppDisconnectRequest](type-aliases/WhatsAppDisconnectRequest.md)- [WhatsappDisconnectResponse](type-aliases/WhatsappDisconnectResponse.md)- [WhatsappDisconnectResponses](type-aliases/WhatsappDisconnectResponses.md)+- [WhatsAppLookup](type-aliases/WhatsAppLookup.md)+- [WhatsappLookupData](type-aliases/WhatsappLookupData.md)+- [WhatsAppLookupRequest](type-aliases/WhatsAppLookupRequest.md)+- [WhatsappLookupResponse](type-aliases/WhatsappLookupResponse.md)+- [WhatsappLookupResponses](type-aliases/WhatsappLookupResponses.md)+- [WhatsAppLookupState](type-aliases/WhatsAppLookupState.md)- [WhatsAppPairing](type-aliases/WhatsAppPairing.md)- [WhatsappPairingData](type-aliases/WhatsappPairingData.md)- [WhatsappPairingResponse](type-aliases/WhatsappPairingResponse.md)@@ -2301,6 +2307,9 @@- [WhatsappPasskeyData](type-aliases/WhatsappPasskeyData.md)- [WhatsappPasskeyResponse](type-aliases/WhatsappPasskeyResponse.md)- [WhatsappPasskeyResponses](type-aliases/WhatsappPasskeyResponses.md)+- [WhatsappStartLookupData](type-aliases/WhatsappStartLookupData.md)+- [WhatsappStartLookupResponse](type-aliases/WhatsappStartLookupResponse.md)+- [WhatsappStartLookupResponses](type-aliases/WhatsappStartLookupResponses.md)- [Widget](type-aliases/Widget.md)- [WithCallId](type-aliases/WithCallId.md)- [WithChannelId](type-aliases/WithChannelId.md)diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppChat.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppChat.mdindex 859a6165a5..f4c452ee60 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppChat.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppChat.md@@ -1,6 +1,6 @@# Type Alias: WhatsAppChat-> **WhatsAppChat** = \{ `added?`: `null` \| [`ExternalChatReference`](ExternalChatReference.md); `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `null` \| [`WhatsAppCannotAdd`](WhatsAppCannotAdd.md); `community?`: `null` \| [`ExternalChatCommunity`](ExternalChatCommunity.md); `jid`: `string`; `kind`: [`ExternalChatKind`](ExternalChatKind.md); `lastActivityAt?`: `string` \| `null`; `name`: `string`; `pinned`: `boolean`; `shared?`: `null` \| [`SharedExternalChatReference`](SharedExternalChatReference.md); \}+> **WhatsAppChat** = \{ `added?`: `null` \| [`ExternalChatReference`](ExternalChatReference.md); `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `null` \| [`WhatsAppCannotAdd`](WhatsAppCannotAdd.md); `community?`: `null` \| [`ExternalChatCommunity`](ExternalChatCommunity.md); `jid`: `string`; `kind`: [`ExternalChatKind`](ExternalChatKind.md); `lastActivityAt?`: `string` \| `null`; `name`: `string`; `phoneNumber?`: `string` \| `null`; `pinned`: `boolean`; `shared?`: `null` \| [`SharedExternalChatReference`](SharedExternalChatReference.md); \}One chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.@@ -15,7 +15,8 @@ One chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.| <a id="property-community"></a> `community?` | `null` \| [`ExternalChatCommunity`](ExternalChatCommunity.md) | - || <a id="property-jid"></a> `jid` | `string` | WhatsApp chat JID: a group, or the other person's phone-number JID (LID when WhatsApp never told us the number). || <a id="property-kind"></a> `kind` | [`ExternalChatKind`](ExternalChatKind.md) | Group or direct chat. |-| <a id="property-lastactivityat"></a> `lastActivityAt?` | `string` \| `null` | Newest activity WhatsApp reported (message or history sync); `null` when unknown. The list is sorted by it, newest first, unknown last. |+| <a id="property-lastactivityat"></a> `lastActivityAt?` | `string` \| `null` | Newest activity WhatsApp reported (message or history sync); `null` when unknown, as for saved contacts never messaged. The list is sorted by it, newest first, unknown last. || <a id="property-name"></a> `name` | `string` | Group: the subject, or member names for an unnamed group. Direct: the contact or WhatsApp name, else `+<phone>`. Always non-empty. |+| <a id="property-phonenumber"></a> `phoneNumber?` | `string` \| `null` | The other person's phone number (`+<digits>`) of a direct chat, when WhatsApp told us it. || <a id="property-pinned"></a> `pinned` | `boolean` | Pinned in WhatsApp. || <a id="property-shared"></a> `shared?` | `null` \| [`SharedExternalChatReference`](SharedExternalChatReference.md) | - |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppLookup.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppLookup.mdnew file mode 100644index 0000000000..1c236702bd--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppLookup.md@@ -0,0 +1,15 @@+# Type Alias: WhatsAppLookup++> **WhatsAppLookup** = \{ `chatJid?`: `string` \| `null`; `id`: `string`; `phoneNumber`: `string`; `state`: [`WhatsAppLookupState`](WhatsAppLookupState.md); \}++The owner asking whether a phone number has a WhatsApp account, to start+a direct chat with it.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-chatjid"></a> `chatJid?` | `string` \| `null` | Found: the direct chat's JID, now addable from the chat list. |+| <a id="property-id"></a> `id` | `string` | Poll `GET /whatsapp/lookups/{id}` with it. |+| <a id="property-phonenumber"></a> `phoneNumber` | `string` | The number asked about, E.164 (`+<digits>`). |+| <a id="property-state"></a> `state` | [`WhatsAppLookupState`](WhatsAppLookupState.md) | Progress. |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppLookupRequest.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppLookupRequest.mdnew file mode 100644index 0000000000..36360aa6da--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppLookupRequest.md@@ -0,0 +1,11 @@+# Type Alias: WhatsAppLookupRequest++> **WhatsAppLookupRequest** = \{ `phoneNumber`: `string`; \}++A phone number to start a direct chat with.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-phonenumber"></a> `phoneNumber` | `string` | E.164: `+`, the country code and the number, without spacing. |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppLookupState.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppLookupState.mdnew file mode 100644index 0000000000..b36f368d2b--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppLookupState.md@@ -0,0 +1,5 @@+# Type Alias: WhatsAppLookupState++> **WhatsAppLookupState** = `"pending"` \| `"found"` \| `"not_on_whatsapp"` \| `"failed"`++Where a phone-number lookup is.diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappLookupData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappLookupData.mdnew file mode 100644index 0000000000..5a6edafee8--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappLookupData.md@@ -0,0 +1,13 @@+# Type Alias: WhatsappLookupData++> **WhatsappLookupData** = \{ `body?`: `never`; `path`: \{ `id`: `string`; \}; `query?`: `never`; `url`: `"/whatsapp/lookups/{id}"`; \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-body"></a> `body?` | `never` |+| <a id="property-path"></a> `path` | \{ `id`: `string`; \} |+| `path.id` | `string` |+| <a id="property-query"></a> `query?` | `never` |+| <a id="property-url"></a> `url` | `"/whatsapp/lookups/{id}"` |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappLookupResponse.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappLookupResponse.mdnew file mode 100644index 0000000000..fa0133b5a6--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappLookupResponse.md@@ -0,0 +1,3 @@+# Type Alias: WhatsappLookupResponse++> **WhatsappLookupResponse** = [`WhatsappLookupResponses`](WhatsappLookupResponses.md)\[keyof [`WhatsappLookupResponses`](WhatsappLookupResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappLookupResponses.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappLookupResponses.mdnew file mode 100644index 0000000000..da930c2b00--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappLookupResponses.md@@ -0,0 +1,9 @@+# Type Alias: WhatsappLookupResponses++> **WhatsappLookupResponses** = \{ `200`: [`WhatsAppLookup`](WhatsAppLookup.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-200"></a> `200` | [`WhatsAppLookup`](WhatsAppLookup.md) |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappStartLookupData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappStartLookupData.mdnew file mode 100644index 0000000000..a9aa6e9a05--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappStartLookupData.md@@ -0,0 +1,12 @@+# Type Alias: WhatsappStartLookupData++> **WhatsappStartLookupData** = \{ `body`: [`WhatsAppLookupRequest`](WhatsAppLookupRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/whatsapp/lookups"`; \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-body"></a> `body` | [`WhatsAppLookupRequest`](WhatsAppLookupRequest.md) |+| <a id="property-path"></a> `path?` | `never` |+| <a id="property-query"></a> `query?` | `never` |+| <a id="property-url"></a> `url` | `"/whatsapp/lookups"` |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappStartLookupResponse.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappStartLookupResponse.mdnew file mode 100644index 0000000000..69c3f86530--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappStartLookupResponse.md@@ -0,0 +1,3 @@+# Type Alias: WhatsappStartLookupResponse++> **WhatsappStartLookupResponse** = [`WhatsappStartLookupResponses`](WhatsappStartLookupResponses.md)\[keyof [`WhatsappStartLookupResponses`](WhatsappStartLookupResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappStartLookupResponses.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappStartLookupResponses.mdnew file mode 100644index 0000000000..12a3d5bb6c--- /dev/null+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappStartLookupResponses.md@@ -0,0 +1,9 @@+# Type Alias: WhatsappStartLookupResponses++> **WhatsappStartLookupResponses** = \{ `200`: [`WhatsAppLookup`](WhatsAppLookup.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-200"></a> `200` | [`WhatsAppLookup`](WhatsAppLookup.md) |diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/chat/classes/WhatsAppChat.md b/packages/sdk-docs/reference/src/entities/whatsapp/chat/classes/WhatsAppChat.mdindex 177be09979..e99da835f3 100644--- a/packages/sdk-docs/reference/src/entities/whatsapp/chat/classes/WhatsAppChat.md+++ b/packages/sdk-docs/reference/src/entities/whatsapp/chat/classes/WhatsAppChat.md@@ -17,8 +17,9 @@ One chat of the current user's WhatsApp chat list: a group or a direct chat.| <a id="property-community"></a> `community` | `readonly` | () => `Promise`\<[`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md) \| `undefined`\> | The WhatsApp community a group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - || <a id="property-id"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) || <a id="property-kind"></a> `kind` | `readonly` | () => `Promise`\<[`ExternalChatKind`](../../../../../generated/storage/types.gen/type-aliases/ExternalChatKind.md)\> | `group` or `direct`. | - |-| <a id="property-lastactivityat"></a> `lastActivityAt` | `readonly` | () => `Promise`\<`string` \| `undefined`\> | Newest activity WhatsApp reported, when known. | - |+| <a id="property-lastactivityat"></a> `lastActivityAt` | `readonly` | () => `Promise`\<`string` \| `undefined`\> | Newest activity WhatsApp reported; unknown for saved contacts never written to. | - || <a id="property-name"></a> `name` | `readonly` | () => `Promise`\<`string`\> | Group subject (or member names), or the other person's name or number. | - |+| <a id="property-phonenumber"></a> `phoneNumber` | `readonly` | () => `Promise`\<`string` \| `undefined`\> | The other person's phone number (`+<digits>`) of a direct chat, when known. | - || <a id="property-pinned"></a> `pinned` | `readonly` | () => `Promise`\<`boolean`\> | Pinned in WhatsApp. | - || <a id="property-shared"></a> `shared` | `readonly` | () => `Promise`\<[`ExternalChat`](../../../external-chat/chat/classes/ExternalChat.md) \| `undefined`\> | Someone else's external chat for this chat, shared with the current user. | - |diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex 29356c78d4..f4a6315d81 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessiblePipeline, AccessLevel, AccessRequest, AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponse, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponse, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponse, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponse, AccessRequestsSubmitResponses, AccessRequestState, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentDmProfile, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, AgentSessionSource, AgentSessionVisibility, AgentTyping, AgentTypingPhase, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentCommentReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarJoinRequest, CalendarJoinRequestApiError, CalendarJoinRequestErrorCode, CalendarJoinRequestsResponse, CalendarJoinRequestStatus, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarMentionViewerCopy, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallProvider, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordSource, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnId, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateCanvasDocumentRequest, CreateCanvasDocumentResponse, CreateCanvasHandlerData, CreateCanvasHandlerError, CreateCanvasHandlerErrors, CreateCanvasHandlerResponse, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseId, DatabaseOp, DatabaseQueryRequest, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DateRange, DateRangeOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DirectAccess, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTextContent, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventIcsData, EventIcsErrors, EventIcsResponse, EventIcsResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, ExternalChatAdd, ExternalChatAddData, ExternalChatAdded, ExternalChatAddResponse, ExternalChatAddResponses, ExternalChatAttachment, ExternalChatAttachmentState, ExternalChatBackfill, ExternalChatBackfillState, ExternalChatCall, ExternalChatCallOutcome, ExternalChatCapabilities, ExternalChatCommunity, ExternalChatContactCard, ExternalChatContacts, ExternalChatData, ExternalChatDeliveryData, ExternalChatDeliveryResponse, ExternalChatDeliveryResponses, ExternalChatDeliveryState, ExternalChatDetail, ExternalChatEvent, ExternalChatKind, ExternalChatLocation, ExternalChatMediaKind, ExternalChatMediaPresentation, ExternalChatMembers, ExternalChatMention, ExternalChatMessage, ExternalChatMessageAttachments, ExternalChatMessageAttachmentsData, ExternalChatMessageAttachmentsResponse, ExternalChatMessageAttachmentsResponses, ExternalChatMessageData, ExternalChatMessageKind, ExternalChatMessageResponse, ExternalChatMessageResponses, ExternalChatMessages, ExternalChatMessagesData, ExternalChatMessagesResponse, ExternalChatMessagesResponses, ExternalChatMutation, ExternalChatParticipant, ExternalChatPermissionsData, ExternalChatPermissionsResponse, ExternalChatPermissionsResponses, ExternalChatPersonRef, ExternalChatPoll, ExternalChatPollOption, ExternalChatProvider, ExternalChatReaction, ExternalChatReadData, ExternalChatReadResponse, ExternalChatReadResponses, ExternalChatReference, ExternalChatRemoveData, ExternalChatRemoveResponse, ExternalChatRemoveResponses, ExternalChatReplyBlock, ExternalChatReplyContent, ExternalChatResponse, ExternalChatResponses, ExternalChatRichContent, ExternalChatsData, ExternalChatSendData, ExternalChatSender, ExternalChatSendErrors, ExternalChatSendProgress, ExternalChatSendReply, ExternalChatSendResponse, ExternalChatSendResponses, ExternalChatSendsData, ExternalChatSendsResponse, ExternalChatSendsResponses, ExternalChatsResponse, ExternalChatsResponses, ExternalChatSummary, ExternalChatSystemAction, ExternalChatSystemLine, ExternalChatUpdatePermissionsData, ExternalChatUpdatePermissionsResponse, ExternalChatUpdatePermissionsResponses, ExternalChatUploadData, ExternalChatUploadedAttachment, ExternalChatUploadRequest, ExternalChatUploadResponse, ExternalChatUploadResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponse, GetDocumentTextContentResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponse, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponse, GuestCallChatReadResponses, GuestChatMessage, GuestChatPage, GuestChatPost, GuestId, GuestJoinRequest, GuestPolicy, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsError, ListJoinRequestsErrors, ListJoinRequestsResponse, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MarkRead, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionId, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesError, QueryDatabasesErrors, QueryDatabasesResponse, QueryDatabasesResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestAccess, RequestedHarnessScope, RequestedLayout, RequestStatus, RequestToJoinData, RequestToJoinError, RequestToJoinErrors, RequestToJoinResponse, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveRequest, ResponseStatus, ResponseSummary, ResultColumn, ResultSet, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionSource, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDirectAccess, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharedExternalChatReference, ShareEntity, ShareEntityType, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, SqlCell, SqlEntityKind, SqlOutcome, SqlOutcomeKind, SqlSelectOption, SqlStatement, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableId, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TaskSimilarityResult, TaskSimilaritySearchHandlerData, TaskSimilaritySearchHandlerError, TaskSimilaritySearchHandlerErrors, TaskSimilaritySearchHandlerResponse, TaskSimilaritySearchHandlerResponses, TaskSimilaritySearchRequest, TaskSimilaritySearchResponse, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewerCapabilities, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WhatsAppAccount, WhatsappAccountData, WhatsappAccountResponse, WhatsappAccountResponses, WhatsAppAccountState, WhatsAppAccountView, WhatsappCancelPairingData, WhatsappCancelPairingResponse, WhatsappCancelPairingResponses, WhatsAppCannotAdd, WhatsAppChat, WhatsAppChats, WhatsappChatsData, WhatsappChatsResponse, WhatsappChatsResponses, WhatsAppConnect, WhatsappConnectData, WhatsappConnectResponse, WhatsappConnectResponses, WhatsAppDisconnect, WhatsappDisconnectData, WhatsAppDisconnectRequest, WhatsappDisconnectResponse, WhatsappDisconnectResponses, WhatsAppPairing, WhatsappPairingData, WhatsappPairingResponse, WhatsappPairingResponses, WhatsAppPairingState, WhatsAppPairState, WhatsappPasskeyData, WhatsappPasskeyResponse, WhatsappPasskeyResponses, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessiblePipeline, AccessLevel, AccessRequest, AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponse, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponse, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponse, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponse, AccessRequestsSubmitResponses, AccessRequestState, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentDmProfile, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, AgentSessionSource, AgentSessionVisibility, AgentTyping, AgentTypingPhase, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentCommentReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarJoinRequest, CalendarJoinRequestApiError, CalendarJoinRequestErrorCode, CalendarJoinRequestsResponse, CalendarJoinRequestStatus, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarMentionViewerCopy, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallProvider, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordSource, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnId, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateCanvasDocumentRequest, CreateCanvasDocumentResponse, CreateCanvasHandlerData, CreateCanvasHandlerError, CreateCanvasHandlerErrors, CreateCanvasHandlerResponse, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseId, DatabaseOp, DatabaseQueryRequest, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DateRange, DateRangeOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DirectAccess, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTextContent, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventIcsData, EventIcsErrors, EventIcsResponse, EventIcsResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, ExternalChatAdd, ExternalChatAddData, ExternalChatAdded, ExternalChatAddResponse, ExternalChatAddResponses, ExternalChatAttachment, ExternalChatAttachmentState, ExternalChatBackfill, ExternalChatBackfillState, ExternalChatCall, ExternalChatCallOutcome, ExternalChatCapabilities, ExternalChatCommunity, ExternalChatContactCard, ExternalChatContacts, ExternalChatData, ExternalChatDeliveryData, ExternalChatDeliveryResponse, ExternalChatDeliveryResponses, ExternalChatDeliveryState, ExternalChatDetail, ExternalChatEvent, ExternalChatKind, ExternalChatLocation, ExternalChatMediaKind, ExternalChatMediaPresentation, ExternalChatMembers, ExternalChatMention, ExternalChatMessage, ExternalChatMessageAttachments, ExternalChatMessageAttachmentsData, ExternalChatMessageAttachmentsResponse, ExternalChatMessageAttachmentsResponses, ExternalChatMessageData, ExternalChatMessageKind, ExternalChatMessageResponse, ExternalChatMessageResponses, ExternalChatMessages, ExternalChatMessagesData, ExternalChatMessagesResponse, ExternalChatMessagesResponses, ExternalChatMutation, ExternalChatParticipant, ExternalChatPermissionsData, ExternalChatPermissionsResponse, ExternalChatPermissionsResponses, ExternalChatPersonRef, ExternalChatPoll, ExternalChatPollOption, ExternalChatProvider, ExternalChatReaction, ExternalChatReadData, ExternalChatReadResponse, ExternalChatReadResponses, ExternalChatReference, ExternalChatRemoveData, ExternalChatRemoveResponse, ExternalChatRemoveResponses, ExternalChatReplyBlock, ExternalChatReplyContent, ExternalChatResponse, ExternalChatResponses, ExternalChatRichContent, ExternalChatsData, ExternalChatSendData, ExternalChatSender, ExternalChatSendErrors, ExternalChatSendProgress, ExternalChatSendReply, ExternalChatSendResponse, ExternalChatSendResponses, ExternalChatSendsData, ExternalChatSendsResponse, ExternalChatSendsResponses, ExternalChatsResponse, ExternalChatsResponses, ExternalChatSummary, ExternalChatSystemAction, ExternalChatSystemLine, ExternalChatUpdatePermissionsData, ExternalChatUpdatePermissionsResponse, ExternalChatUpdatePermissionsResponses, ExternalChatUploadData, ExternalChatUploadedAttachment, ExternalChatUploadRequest, ExternalChatUploadResponse, ExternalChatUploadResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponse, GetDocumentTextContentResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponse, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponse, GuestCallChatReadResponses, GuestChatMessage, GuestChatPage, GuestChatPost, GuestId, GuestJoinRequest, GuestPolicy, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsError, ListJoinRequestsErrors, ListJoinRequestsResponse, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MarkRead, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionId, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesError, QueryDatabasesErrors, QueryDatabasesResponse, QueryDatabasesResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestAccess, RequestedHarnessScope, RequestedLayout, RequestStatus, RequestToJoinData, RequestToJoinError, RequestToJoinErrors, RequestToJoinResponse, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveRequest, ResponseStatus, ResponseSummary, ResultColumn, ResultSet, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionSource, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDirectAccess, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharedExternalChatReference, ShareEntity, ShareEntityType, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, SqlCell, SqlEntityKind, SqlOutcome, SqlOutcomeKind, SqlSelectOption, SqlStatement, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableId, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TaskSimilarityResult, TaskSimilaritySearchHandlerData, TaskSimilaritySearchHandlerError, TaskSimilaritySearchHandlerErrors, TaskSimilaritySearchHandlerResponse, TaskSimilaritySearchHandlerResponses, TaskSimilaritySearchRequest, TaskSimilaritySearchResponse, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewerCapabilities, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WhatsAppAccount, WhatsappAccountData, WhatsappAccountResponse, WhatsappAccountResponses, WhatsAppAccountState, WhatsAppAccountView, WhatsappCancelPairingData, WhatsappCancelPairingResponse, WhatsappCancelPairingResponses, WhatsAppCannotAdd, WhatsAppChat, WhatsAppChats, WhatsappChatsData, WhatsappChatsResponse, WhatsappChatsResponses, WhatsAppConnect, WhatsappConnectData, WhatsappConnectResponse, WhatsappConnectResponses, WhatsAppDisconnect, WhatsappDisconnectData, WhatsAppDisconnectRequest, WhatsappDisconnectResponse, WhatsappDisconnectResponses, WhatsAppLookup, WhatsappLookupData, WhatsAppLookupRequest, WhatsappLookupResponse, WhatsappLookupResponses, WhatsAppLookupState, WhatsAppPairing, WhatsappPairingData, WhatsappPairingResponse, WhatsappPairingResponses, WhatsAppPairingState, WhatsAppPairState, WhatsappPasskeyData, WhatsappPasskeyResponse, WhatsappPasskeyResponses, WhatsappStartLookupData, WhatsappStartLookupResponse, WhatsappStartLookupResponses, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex ff89543fc7..6dc1fd7c64 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -2,7 +2,7 @@import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type ServerSentEventsResult, type TDataShape } from './client';import { client } from './client.gen';-import type { AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponses, AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateCanvasHandlerData, CreateCanvasHandlerErrors, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookErrors, CreateDatabaseWebhookResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeclineCallData, DeclineCallErrors, DeclineCallResponses, DeclineRingData, DeclineRingErrors, DeclineRingResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, EventIcsData, EventIcsErrors, EventIcsResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, ExternalChatAddData, ExternalChatAddResponses, ExternalChatData, ExternalChatDeliveryData, ExternalChatDeliveryResponses, ExternalChatMessageAttachmentsData, ExternalChatMessageAttachmentsResponses, ExternalChatMessageData, ExternalChatMessageResponses, ExternalChatMessagesData, ExternalChatMessagesResponses, ExternalChatPermissionsData, ExternalChatPermissionsResponses, ExternalChatReadData, ExternalChatReadResponses, ExternalChatRemoveData, ExternalChatRemoveResponses, ExternalChatResponses, ExternalChatsData, ExternalChatSendData, ExternalChatSendErrors, ExternalChatSendResponses, ExternalChatSendsData, ExternalChatSendsResponses, ExternalChatsResponses, ExternalChatUpdatePermissionsData, ExternalChatUpdatePermissionsResponses, ExternalChatUploadData, ExternalChatUploadResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsErrors, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponses, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesErrors, QueryDatabasesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, RequestToJoinData, RequestToJoinErrors, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareCrmPipelineData, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, TaskSimilaritySearchHandlerData, TaskSimilaritySearchHandlerErrors, TaskSimilaritySearchHandlerResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, TrashCrmPipelineData, TrashCrmPipelineResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses, WhatsappAccountData, WhatsappAccountResponses, WhatsappCancelPairingData, WhatsappCancelPairingResponses, WhatsappChatsData, WhatsappChatsResponses, WhatsappConnectData, WhatsappConnectResponses, WhatsappDisconnectData, WhatsappDisconnectResponses, WhatsappPairingData, WhatsappPairingResponses, WhatsappPasskeyData, WhatsappPasskeyResponses } from './types.gen';+import type { AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponses, AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateCanvasHandlerData, CreateCanvasHandlerErrors, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookErrors, CreateDatabaseWebhookResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeclineCallData, DeclineCallErrors, DeclineCallResponses, DeclineRingData, DeclineRingErrors, DeclineRingResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, EventIcsData, EventIcsErrors, EventIcsResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, ExternalChatAddData, ExternalChatAddResponses, ExternalChatData, ExternalChatDeliveryData, ExternalChatDeliveryResponses, ExternalChatMessageAttachmentsData, ExternalChatMessageAttachmentsResponses, ExternalChatMessageData, ExternalChatMessageResponses, ExternalChatMessagesData, ExternalChatMessagesResponses, ExternalChatPermissionsData, ExternalChatPermissionsResponses, ExternalChatReadData, ExternalChatReadResponses, ExternalChatRemoveData, ExternalChatRemoveResponses, ExternalChatResponses, ExternalChatsData, ExternalChatSendData, ExternalChatSendErrors, ExternalChatSendResponses, ExternalChatSendsData, ExternalChatSendsResponses, ExternalChatsResponses, ExternalChatUpdatePermissionsData, ExternalChatUpdatePermissionsResponses, ExternalChatUploadData, ExternalChatUploadResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsErrors, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponses, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesErrors, QueryDatabasesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, RequestToJoinData, RequestToJoinErrors, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareCrmPipelineData, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, TaskSimilaritySearchHandlerData, TaskSimilaritySearchHandlerErrors, TaskSimilaritySearchHandlerResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, TrashCrmPipelineData, TrashCrmPipelineResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses, WhatsappAccountData, WhatsappAccountResponses, WhatsappCancelPairingData, WhatsappCancelPairingResponses, WhatsappChatsData, WhatsappChatsResponses, WhatsappConnectData, WhatsappConnectResponses, WhatsappDisconnectData, WhatsappDisconnectResponses, WhatsappLookupData, WhatsappLookupResponses, WhatsappPairingData, WhatsappPairingResponses, WhatsappPasskeyData, WhatsappPasskeyResponses, WhatsappStartLookupData, WhatsappStartLookupResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -3410,6 +3410,29 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Ask whether a phone number has a WhatsApp account, to start a direct chat+ * with it; poll the lookup until it is no longer `pending`. Found numbers+ * join the chat list, so `POST /external-chats` adds them.+ */+ public whatsappStartLookup<ThrowOnError extends boolean = false>(options: Options<WhatsappStartLookupData, ThrowOnError>): RequestResult<WhatsappStartLookupResponses, unknown, ThrowOnError> {+ return (options.client ?? this.client).post<WhatsappStartLookupResponses, unknown, ThrowOnError>({+ url: '/whatsapp/lookups',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Poll the caller's phone-number lookup.+ */+ public whatsappLookup<ThrowOnError extends boolean = false>(options: Options<WhatsappLookupData, ThrowOnError>): RequestResult<WhatsappLookupResponses, unknown, ThrowOnError> {+ return (options.client ?? this.client).get<WhatsappLookupResponses, unknown, ThrowOnError>({ url: '/whatsapp/lookups/{id}', ...options });+ }+/*** Cancel the caller's pairing transaction.*/diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 7b2578066d..f398968921 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -16549,7 +16549,8 @@ export type WhatsAppChat = {kind: ExternalChatKind;/*** Newest activity WhatsApp reported (message or history sync); `null`- * when unknown. The list is sorted by it, newest first, unknown last.+ * when unknown, as for saved contacts never messaged. The list is+ * sorted by it, newest first, unknown last.*/lastActivityAt?: string | null;/**@@ -16557,6 +16558,11 @@ export type WhatsAppChat = {* contact or WhatsApp name, else `+<phone>`. Always non-empty.*/name: string;+ /**+ * The other person's phone number (`+<digits>`) of a direct chat, when+ * WhatsApp told us it.+ */+ phoneNumber?: string | null;/*** Pinned in WhatsApp.*/@@ -16605,6 +16611,44 @@ export type WhatsAppDisconnectRequest = {authorizationGeneration: number;};+/**+ * The owner asking whether a phone number has a WhatsApp account, to start+ * a direct chat with it.+ */+export type WhatsAppLookup = {+ /**+ * Found: the direct chat's JID, now addable from the chat list.+ */+ chatJid?: string | null;+ /**+ * Poll `GET /whatsapp/lookups/{id}` with it.+ */+ id: string;+ /**+ * The number asked about, E.164 (`+<digits>`).+ */+ phoneNumber: string;+ /**+ * Progress.+ */+ state: WhatsAppLookupState;+};++/**+ * A phone number to start a direct chat with.+ */+export type WhatsAppLookupRequest = {+ /**+ * E.164: `+`, the country code and the number, without spacing.+ */+ phoneNumber: string;+};++/**+ * Where a phone-number lookup is.+ */+export type WhatsAppLookupState = 'pending' | 'found' | 'not_on_whatsapp' | 'failed';+/*** Owner-only pairing status. Deliberately has no `Debug` implementation: the* QR and pairing code are secrets for the duration of the transaction.@@ -24984,6 +25028,34 @@ export type WhatsappDisconnectResponses = {export type WhatsappDisconnectResponse = WhatsappDisconnectResponses[keyof WhatsappDisconnectResponses];+export type WhatsappStartLookupData = {+ body: WhatsAppLookupRequest;+ path?: never;+ query?: never;+ url: '/whatsapp/lookups';+};++export type WhatsappStartLookupResponses = {+ 200: WhatsAppLookup;+};++export type WhatsappStartLookupResponse = WhatsappStartLookupResponses[keyof WhatsappStartLookupResponses];++export type WhatsappLookupData = {+ body?: never;+ path: {+ id: string;+ };+ query?: never;+ url: '/whatsapp/lookups/{id}';+};++export type WhatsappLookupResponses = {+ 200: WhatsAppLookup;+};++export type WhatsappLookupResponse = WhatsappLookupResponses[keyof WhatsappLookupResponses];+export type WhatsappCancelPairingData = {body?: never;path: {diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex fe321da710..1dc3365b7c 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -19464,6 +19464,65 @@}}},+ "/whatsapp/lookups": {+ "post": {+ "tags": ["whatsapp_linked::inbound::router"],+ "summary": "Ask whether a phone number has a WhatsApp account, to start a direct chat\nwith it; poll the lookup until it is no longer `pending`. Found numbers\njoin the chat list, so `POST /external-chats` adds them.",+ "operationId": "whatsapp_start_lookup",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WhatsAppLookupRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WhatsAppLookup"+ }+ }+ }+ }+ }+ }+ },+ "/whatsapp/lookups/{id}": {+ "get": {+ "tags": ["whatsapp_linked::inbound::router"],+ "summary": "Poll the caller's phone-number lookup.",+ "operationId": "whatsapp_lookup",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WhatsAppLookup"+ }+ }+ }+ }+ }+ }+ },"/whatsapp/pairing/{id}": {"get": {"tags": ["whatsapp_linked::inbound::router"],@@ -45437,12 +45496,16 @@"lastActivityAt": {"type": ["string", "null"],"format": "date-time",- "description": "Newest activity WhatsApp reported (message or history sync); `null`\nwhen unknown. The list is sorted by it, newest first, unknown last."+ "description": "Newest activity WhatsApp reported (message or history sync); `null`\nwhen unknown, as for saved contacts never messaged. The list is\nsorted by it, newest first, unknown last."},"name": {"type": "string","description": "Group: the subject, or member names for an unnamed group. Direct: the\ncontact or WhatsApp name, else `+<phone>`. Always non-empty."},+ "phoneNumber": {+ "type": ["string", "null"],+ "description": "The other person's phone number (`+<digits>`) of a direct chat, when\nWhatsApp told us it."+ },"pinned": {"type": "boolean","description": "Pinned in WhatsApp."@@ -45507,6 +45570,46 @@}}},+ "WhatsAppLookup": {+ "type": "object",+ "description": "The owner asking whether a phone number has a WhatsApp account, to start\na direct chat with it.",+ "required": ["id", "phoneNumber", "state"],+ "properties": {+ "chatJid": {+ "type": ["string", "null"],+ "description": "Found: the direct chat's JID, now addable from the chat list."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Poll `GET /whatsapp/lookups/{id}` with it."+ },+ "phoneNumber": {+ "type": "string",+ "description": "The number asked about, E.164 (`+<digits>`)."+ },+ "state": {+ "$ref": "#/components/schemas/WhatsAppLookupState",+ "description": "Progress."+ }+ }+ },+ "WhatsAppLookupRequest": {+ "type": "object",+ "description": "A phone number to start a direct chat with.",+ "required": ["phoneNumber"],+ "properties": {+ "phoneNumber": {+ "type": "string",+ "description": "E.164: `+`, the country code and the number, without spacing."+ }+ }+ },+ "WhatsAppLookupState": {+ "type": "string",+ "description": "Where a phone-number lookup is.",+ "enum": ["pending", "found", "not_on_whatsapp", "failed"]+ },"WhatsAppPairState": {"type": "object","description": "Owner-only pairing status. Deliberately has no `Debug` implementation: the\nQR and pairing code are secrets for the duration of the transaction.",diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 1a6bf49f84..68b757fe2c 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -401,8 +401,11 @@ export const storageExcluded = ['whatsappCancelPairing','whatsappConnect','whatsappDisconnect',+ // Phone-number lookups need the owner's own session: WhatsApp bans bulk checks.+ 'whatsappLookup','whatsappPairing','whatsappPasskey',+ 'whatsappStartLookup',] as const satisfies readonly (keyof StorageSdk)[];export const storageBacklog =diff --git a/packages/sdk/src/entities/whatsapp/chat.ts b/packages/sdk/src/entities/whatsapp/chat.tsindex e124faad2e..0247177352 100644--- a/packages/sdk/src/entities/whatsapp/chat.ts+++ b/packages/sdk/src/entities/whatsapp/chat.ts@@ -54,7 +54,10 @@ export class WhatsAppChat extends MacroEntity<WhatsAppChatRecord> {/** Group subject (or member names), or the other person's name or number. */readonly name = this.field('name');- /** Newest activity WhatsApp reported, when known. */+ /** The other person's phone number (`+<digits>`) of a direct chat, when known. */+ readonly phoneNumber = this.field('phoneNumber');++ /** Newest activity WhatsApp reported; unknown for saved contacts never written to. */readonly lastActivityAt = this.field('lastActivityAt');/** Archived in WhatsApp. */diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex 392856ebb7..fa4575500b 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -474,6 +474,8 @@ use utoipa::OpenApi;whatsapp_linked::inbound::router::passkey,whatsapp_linked::inbound::router::disconnect,whatsapp_linked::inbound::router::chats,+ whatsapp_linked::inbound::router::start_lookup,+ whatsapp_linked::inbound::router::lookup,access_requests::inbound::axum_router::state_handler,access_requests::inbound::axum_router::submit_handler,diff --git a/services/whatsapp_session_service/AGENTS.md b/services/whatsapp_session_service/AGENTS.mdindex d51df2d1ad..9b27b3eabf 100644--- a/services/whatsapp_session_service/AGENTS.md+++ b/services/whatsapp_session_service/AGENTS.md@@ -43,7 +43,8 @@ current, ingests the traffic of added chats (`external_chat`) through `whatsapp_non-zero so ECS replaces it), release announcements, and discovery through`SessionService` (`discoverable_accounts`, `fleet_health`).- `outbound/signals.rs`: `LISTEN` for `whatsapp_{account_released,- pairing_requested, send_requested, groups_requested, account_changed}`.+ pairing_requested, send_requested, roster_requested, lookup_requested,+ account_changed}`.Payloads are `external_chat::signals::Signal` JSON; eachone's `traceparent` parents a `whatsapp.signal.receive` span that travelswith the signal (`ports::Traced`): the supervisor's work and the runner's@@ -87,7 +88,17 @@ current, ingests the traffic of added chats (`external_chat`) through `whatsapp_sync bundles, live messages (any chat) and contact/archive/pin events into`ChatUpdate`s (`events.rs`: `history_chats`, `message_chat`,`chat_setting`; direct chats by phone number) that the runner stores with- `update_chats`. On-demand history answers are parsed with+ `update_chats`. The device store's saved contacts (`events::contact_chats`:+ address-book names only, not people merely seen in groups) are listed on+ `Connected` and every `AppStateSyncComplete`, and a `Contact` event lists+ its contact, so the owner can start a chat with them.+- Phone-number lookups (`domain/account/lookups.rs`): on+ `whatsapp_lookup_requested`, on connect and on every tick, the runner+ answers pending lookups with one `IsOnWhatsApp` usync each+ (`WhatsAppSession::look_up`; whatsmeow stores the number's LID pairing, so a+ later message by LID lands in the same chat) and records the answer+ (`events::lookup_answer` names it like any chat). Only explicit owner+ lookups, rate-limited in DSS: WhatsApp bans bulk usync. On-demand history answers are parsed with`Client::parse_web_message`, ingested as history events through the inboundgate, then reported as a `HistoryPage`. The runner's `backfill` asks thephone for pages of added groups (`request_history`, plus `request_message`@@ -126,7 +137,8 @@ current, ingests the traffic of added chats (`external_chat`) through `whatsapp_Spans: `whatsapp.account.{lease,release,rescan,connect}`,`whatsapp.inbound.ingest`, `whatsapp.media.import`, `whatsapp.send.dispatch`(parented on the trace of the request that recorded the send),-`whatsapp.groups.{refresh,event}`, `whatsapp.signal.receive`,+`whatsapp.groups.{refresh,event}`, `whatsapp.contacts.sync`, `whatsapp.lookup`+(outcome `found`/`not_on_whatsapp`/`failed`), `whatsapp.signal.receive`,`whatsapp.account.signal`, `whatsapp.drain`,`whatsapp.history.{sync,page}`, `whatsapp.backfill.request`(`whatsapp.inbound.ingest` records the message `kind`; `whatsapp.history.page`diff --git a/services/whatsapp_session_service/src/domain/account.rs b/services/whatsapp_session_service/src/domain/account.rsindex eef18ab5b3..255402dcdc 100644--- a/services/whatsapp_session_service/src/domain/account.rs+++ b/services/whatsapp_session_service/src/domain/account.rs@@ -5,15 +5,14 @@use std::sync::Arc;use std::time::Duration;-use external_chat::domain::models::{BackfillState, ExternalChatError};+use external_chat::domain::models::ExternalChatError;use external_chat::domain::ports::ExternalChatResult;use tokio::sync::{Notify, Semaphore, mpsc, watch};use tokio_util::sync::CancellationToken;use tracing::Instrument;use uuid::Uuid;use whatsapp_linked::domain::events::{- BackfillWork, ClaimedSend, HistoryPage, Lease, OutgoingContent, PairingUpdate, PairingWork,- SendOutcome, SessionScope,+ ClaimedSend, Lease, OutgoingContent, PairingUpdate, PairingWork, SendOutcome, SessionScope,};use whatsapp_linked::domain::models::{AccountState, GroupInfo, PairingState};use whatsapp_linked::domain::session::SessionService;@@ -25,6 +24,8 @@ use super::ports::{SessionError, SessionEvent, Traced, UploadedMedia, WhatsAppSession,};+mod backfill;+mod lookups;#[cfg(test)]mod test;@@ -520,6 +521,7 @@ impl<Session: WhatsAppSession> Running<'_, Session> {AccountSignal::Pairing(pairing) => self.check_pairing(pairing).await,AccountSignal::Send => self.dispatch_sends().await,AccountSignal::Groups => self.requested_refresh().await,+ AccountSignal::Lookup => self.answer_lookups().await,AccountSignal::Changed => self.account_changed().await,AccountSignal::Resync => self.resync().await,}@@ -537,6 +539,7 @@ impl<Session: WhatsAppSession> Running<'_, Session> {self.replay().await?;if self.is_connected() {self.dispatch_sends().await?;+ self.answer_lookups().await?;Box::pin(self.backfill(false)).await?;}Ok(())@@ -588,6 +591,7 @@ impl<Session: WhatsAppSession> Running<'_, Session> {self.refresh_groups().await?;self.replay().await?;self.dispatch_sends().await?;+ self.answer_lookups().await?;// The phone may have been the reason pages went unanswered.Box::pin(self.backfill(true)).await}@@ -729,128 +733,6 @@ impl<Session: WhatsAppSession> Running<'_, Session> {}}- /// Imports earlier messages of the owner's newly added groups from the- /// phone, a page at a time: asks for the next page of every group that- /// has none outstanding, marks unanswered requests as waiting for the- /// phone, and asks again after [`AccountConfig::backfill_retry`] (at once- /// with `retry_now`, after reconnecting).- async fn backfill(&mut self, retry_now: bool) -> Result<(), AccountExit> {- if !self.is_connected() {- return Ok(());- }- let Some(work) = survive(- self.sessions.backfill_work(self.scope).await,- "backfill_work",- )?- else {- return Ok(());- };- let now = chrono::Utc::now();- let elapsed = |at: Option<chrono::DateTime<chrono::Utc>>| {- at.and_then(|at| (now - at).to_std().ok())- .unwrap_or(Duration::MAX)- };- for group in work {- match group.state {- BackfillState::Running if group.requested_at.is_some() => {- if elapsed(group.requested_at) >= self.config.backfill_timeout {- tracing::info!(- account_id = %self.scope.account_id,- chat_id = %group.chat_id,- "The phone did not answer a history request; waiting for it"- );- survive(- self.sessions- .backfill_unanswered(self.scope, group.chat_id)- .await,- "backfill_unanswered",- )?;- }- }- BackfillState::WaitingForPhone- if !retry_now && elapsed(group.requested_at) < self.config.backfill_retry => {}- _ => Box::pin(self.request_page(&group)).await?,- }- }- Ok(())- }-- /// Asks the phone for the page before the group's cursor (first: before- /// the chat's newest message, which is asked for itself when it came- /// before the group was added and so was not kept).- async fn request_page(&mut self, group: &BackfillWork) -> Result<(), AccountExit> {- let Some(before) = group.cursor.as_ref().or(group.anchor.as_ref()) else {- // No message known in this chat yet: the first one starts it.- if group.state != BackfillState::WaitingForMessage {- survive(- self.sessions- .backfill_waiting_for_message(self.scope, group.chat_id)- .await,- "backfill_waiting_for_message",- )?;- }- return Ok(());- };- let span = tracing::info_span!(- "whatsapp.backfill.request",- account_id = %self.scope.account_id,- chat_id = %group.chat_id,- imported = group.imported,- first = group.cursor.is_none(),- outcome = tracing::field::Empty,- );- async {- let first = group.cursor.is_none();- if first- && before.at <= group.adopted_at + chrono::Duration::seconds(10)- && let Err(error) = self.session.request_message(&group.group_jid, before).await- {- tracing::warn!(error = %error, "Asking the phone for a chat's newest message failed");- }- match self- .session- .request_history(&group.group_jid, before, BACKFILL_PAGE)- .await- {- Ok(()) => {- tracing::Span::current().record("outcome", "requested");- survive(- self.sessions- .backfill_requested(self.scope, group.chat_id)- .await,- "backfill_requested",- )?;- }- Err(SessionError::Fenced) => return Err(AccountExit::Fenced),- Err(error) => {- tracing::Span::current().record("outcome", "send_failed");- tracing::warn!(error = %error, "Asking the phone for earlier messages failed");- }- }- Ok(())- }- .instrument(span)- .await- }-- /// The phone answered with a page: record it, then ask for the next one.- async fn history_page(&mut self, page: &HistoryPage) -> Result<(), AccountExit> {- // The page's messages were queued first; ingest them before counting.- self.replay().await?;- let states = survive(- self.sessions.backfill_page(self.scope, page).await,- "backfill_page",- )?- .unwrap_or_default();- if states- .iter()- .any(|(_, state)| *state == BackfillState::Running)- {- Box::pin(self.backfill(false)).await?;- }- Ok(())- }-/// A page asked for fresh groups: refresh unless that happened recently.async fn requested_refresh(&mut self) -> Result<(), AccountExit> {if selfdiff --git a/services/whatsapp_session_service/src/domain/account/backfill.rs b/services/whatsapp_session_service/src/domain/account/backfill.rsnew file mode 100644index 0000000000..627981a657--- /dev/null+++ b/services/whatsapp_session_service/src/domain/account/backfill.rs@@ -0,0 +1,134 @@+//! Importing earlier messages of the owner's added chats from the phone, a+//! page at a time.++use std::time::Duration;++use external_chat::domain::models::BackfillState;+use tracing::Instrument;+use whatsapp_linked::domain::events::{BackfillWork, HistoryPage};++use super::{AccountExit, BACKFILL_PAGE, Running, SessionError, WhatsAppSession, survive};++impl<Session: WhatsAppSession> Running<'_, Session> {+ /// Imports earlier messages of the owner's newly added groups from the+ /// phone, a page at a time: asks for the next page of every group that+ /// has none outstanding, marks unanswered requests as waiting for the+ /// phone, and asks again after [`AccountConfig::backfill_retry`] (at once+ /// with `retry_now`, after reconnecting).+ pub(super) async fn backfill(&mut self, retry_now: bool) -> Result<(), AccountExit> {+ if !self.is_connected() {+ return Ok(());+ }+ let Some(work) = survive(+ self.sessions.backfill_work(self.scope).await,+ "backfill_work",+ )?+ else {+ return Ok(());+ };+ let now = chrono::Utc::now();+ let elapsed = |at: Option<chrono::DateTime<chrono::Utc>>| {+ at.and_then(|at| (now - at).to_std().ok())+ .unwrap_or(Duration::MAX)+ };+ for group in work {+ match group.state {+ BackfillState::Running if group.requested_at.is_some() => {+ if elapsed(group.requested_at) >= self.config.backfill_timeout {+ tracing::info!(+ account_id = %self.scope.account_id,+ chat_id = %group.chat_id,+ "The phone did not answer a history request; waiting for it"+ );+ survive(+ self.sessions+ .backfill_unanswered(self.scope, group.chat_id)+ .await,+ "backfill_unanswered",+ )?;+ }+ }+ BackfillState::WaitingForPhone+ if !retry_now && elapsed(group.requested_at) < self.config.backfill_retry => {}+ _ => Box::pin(self.request_page(&group)).await?,+ }+ }+ Ok(())+ }++ /// Asks the phone for the page before the group's cursor (first: before+ /// the chat's newest message, which is asked for itself when it came+ /// before the group was added and so was not kept).+ pub(super) async fn request_page(&mut self, group: &BackfillWork) -> Result<(), AccountExit> {+ let Some(before) = group.cursor.as_ref().or(group.anchor.as_ref()) else {+ // No message known in this chat yet: the first one starts it.+ if group.state != BackfillState::WaitingForMessage {+ survive(+ self.sessions+ .backfill_waiting_for_message(self.scope, group.chat_id)+ .await,+ "backfill_waiting_for_message",+ )?;+ }+ return Ok(());+ };+ let span = tracing::info_span!(+ "whatsapp.backfill.request",+ account_id = %self.scope.account_id,+ chat_id = %group.chat_id,+ imported = group.imported,+ first = group.cursor.is_none(),+ outcome = tracing::field::Empty,+ );+ async {+ let first = group.cursor.is_none();+ if first+ && before.at <= group.adopted_at + chrono::Duration::seconds(10)+ && let Err(error) = self.session.request_message(&group.group_jid, before).await+ {+ tracing::warn!(error = %error, "Asking the phone for a chat's newest message failed");+ }+ match self+ .session+ .request_history(&group.group_jid, before, BACKFILL_PAGE)+ .await+ {+ Ok(()) => {+ tracing::Span::current().record("outcome", "requested");+ survive(+ self.sessions+ .backfill_requested(self.scope, group.chat_id)+ .await,+ "backfill_requested",+ )?;+ }+ Err(SessionError::Fenced) => return Err(AccountExit::Fenced),+ Err(error) => {+ tracing::Span::current().record("outcome", "send_failed");+ tracing::warn!(error = %error, "Asking the phone for earlier messages failed");+ }+ }+ Ok(())+ }+ .instrument(span)+ .await+ }++ /// The phone answered with a page: record it, then ask for the next one.+ pub(super) async fn history_page(&mut self, page: &HistoryPage) -> Result<(), AccountExit> {+ // The page's messages were queued first; ingest them before counting.+ self.replay().await?;+ let states = survive(+ self.sessions.backfill_page(self.scope, page).await,+ "backfill_page",+ )?+ .unwrap_or_default();+ if states+ .iter()+ .any(|(_, state)| *state == BackfillState::Running)+ {+ Box::pin(self.backfill(false)).await?;+ }+ Ok(())+ }+}diff --git a/services/whatsapp_session_service/src/domain/account/lookups.rs b/services/whatsapp_session_service/src/domain/account/lookups.rsnew file mode 100644index 0000000000..cc4a421b4c--- /dev/null+++ b/services/whatsapp_session_service/src/domain/account/lookups.rs@@ -0,0 +1,61 @@+//! Answering the owner's phone-number lookups, to start direct chats with+//! people not in the chat list.++use tracing::Instrument;+use whatsapp_linked::domain::events::LookupAnswer;++use super::{AccountExit, Running, SessionError, WhatsAppSession, survive};++impl<Session: WhatsAppSession> Running<'_, Session> {+ /// Answers the owner's pending phone-number lookups, one WhatsApp query+ /// each. Lookups wait while the connection is down and fail on their own+ /// once they expire.+ pub(super) async fn answer_lookups(&mut self) -> Result<(), AccountExit> {+ if !self.is_connected() {+ return Ok(());+ }+ let Some(lookups) = survive(+ self.sessions.pending_lookups(self.scope).await,+ "pending_lookups",+ )?+ else {+ return Ok(());+ };+ for lookup in lookups {+ let span = tracing::info_span!(+ "whatsapp.lookup",+ account_id = %self.scope.account_id,+ lookup_id = %lookup.id,+ outcome = tracing::field::Empty,+ );+ async {+ let answer = match self.session.look_up(&lookup.phone_number).await {+ Ok(answer) => answer,+ Err(SessionError::Fenced) => return Err(AccountExit::Fenced),+ Err(error) => {+ tracing::warn!(error = %error, "Looking up a WhatsApp number failed");+ LookupAnswer::Failed+ }+ };+ tracing::Span::current().record(+ "outcome",+ match &answer {+ LookupAnswer::Found { .. } => "found",+ LookupAnswer::NotOnWhatsApp => "not_on_whatsapp",+ LookupAnswer::Failed => "failed",+ },+ );+ survive(+ self.sessions+ .complete_lookup(self.scope, lookup.id, &answer)+ .await,+ "complete_lookup",+ )?;+ Ok(())+ }+ .instrument(span)+ .await?;+ }+ Ok(())+ }+}diff --git a/services/whatsapp_session_service/src/domain/account/test.rs b/services/whatsapp_session_service/src/domain/account/test.rsindex 67245f9f9b..3ee0421dcd 100644--- a/services/whatsapp_session_service/src/domain/account/test.rs+++ b/services/whatsapp_session_service/src/domain/account/test.rs@@ -11,9 +11,10 @@ use tokio::sync::mpsc;use tokio_util::sync::CancellationToken;use uuid::Uuid;use whatsapp_linked::domain::events::{- ClaimedSend, InboundEvent, InboundKind, MediaImport, Message, MessageAnchor, MessageKind,- OutboundMedia, SessionScope,+ ClaimedSend, InboundEvent, InboundKind, LookupAnswer, MediaImport, Message, MessageAnchor,+ MessageKind, OutboundMedia, SessionScope,};+use whatsapp_linked::domain::jid::PhoneNumber;use whatsapp_linked::domain::models::{GroupInfo, Identity, Participant};use whatsapp_linked::domain::session::SessionService;use whatsapp_linked::outbound::pg::PgWhatsAppRepository;@@ -28,6 +29,8 @@ use crate::domain::ports::{const IDENTITY: &str = "[email protected]";const GROUP: &str = "[email protected]";+/// The one number the fake WhatsApp has an account for.+const REGISTERED: &str = "+5550002";/// Calls the runner made, in order.#[derive(Debug, Clone, PartialEq, Eq)]@@ -46,6 +49,8 @@ enum Call {RequestHistory(String, String, u32),/// Chat, message id.RequestMessage(String, String),+ /// Phone number.+ LookUp(String),}#[derive(Clone)]@@ -214,6 +219,22 @@ impl WhatsAppSession for FakeSession {Ok(self.whatsapp.group.lock().unwrap().clone())}+ /// [`REGISTERED`] is the customer; every other number is unregistered.+ async fn look_up(&self, phone: &PhoneNumber) -> Result<LookupAnswer, SessionError> {+ self.whatsapp+ .calls+ .send(Call::LookUp(phone.as_str().to_owned()))+ .unwrap();+ Ok(if phone.as_str() == REGISTERED {+ LookupAnswer::Found {+ jid: phone.jid(),+ name: Some("Customer".to_owned()),+ }+ } else {+ LookupAnswer::NotOnWhatsApp+ })+ }+async fn logout(&self) {self.whatsapp.calls.send(Call::Logout).unwrap();}@@ -929,3 +950,5 @@ async fn a_kms_outage_leaves_a_connected_account_and_its_device_alone(pool: PgPo);assert_eq!(account_state(&pool, account).await, "connected");}++mod lookups;diff --git a/services/whatsapp_session_service/src/domain/account/test/lookups.rs b/services/whatsapp_session_service/src/domain/account/test/lookups.rsnew file mode 100644index 0000000000..aaaeceb36d--- /dev/null+++ b/services/whatsapp_session_service/src/domain/account/test/lookups.rs@@ -0,0 +1,108 @@+//! Phone-number lookups answered by the account's session.++use super::*;++const UNREGISTERED: &str = "+5550003";++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn lookups_are_answered_on_their_signal_and_list_found_numbers(pool: PgPool) {+ let (account, _, mut calls, started) = connected(&pool, Duration::from_secs(3600)).await;+ let found = Uuid::now_v7();+ let unregistered = Uuid::now_v7();+ for (id, phone) in [(found, REGISTERED), (unregistered, UNREGISTERED)] {+ sqlx::query!(+ "INSERT INTO whatsapp_lookup (id, account_id, phone_number, state) VALUES ($1, $2, $3, 'pending')",+ id,+ account,+ phone+ )+ .execute(&pool)+ .await+ .unwrap();+ }+ started+ .signals+ .send(AccountSignal::Lookup.into())+ .await+ .unwrap();+ assert_eq!(+ calls.recv().await,+ Some(Call::LookUp(REGISTERED.to_owned()))+ );+ assert_eq!(+ calls.recv().await,+ Some(Call::LookUp(UNREGISTERED.to_owned()))+ );+ started.release.cancel();+ assert_eq!(started.running.await.unwrap(), AccountExit::Released);++ let registered_jid = PhoneNumber::parse(REGISTERED).unwrap().jid();+ let answered = sqlx::query!(+ "SELECT id, state, chat_jid FROM whatsapp_lookup WHERE account_id = $1 ORDER BY phone_number",+ account+ )+ .fetch_all(&pool)+ .await+ .unwrap()+ .into_iter()+ .map(|row| (row.id, row.state, row.chat_jid))+ .collect::<Vec<_>>();+ assert_eq!(+ answered,+ [+ (found, "found".to_owned(), Some(registered_jid.clone())),+ (unregistered, "not_on_whatsapp".to_owned(), None),+ ]+ );+ let listed = sqlx::query!(+ "SELECT chat_jid, kind, name, last_activity_at FROM whatsapp_chat WHERE account_id = $1",+ account+ )+ .fetch_all(&pool)+ .await+ .unwrap()+ .into_iter()+ .map(|row| (row.chat_jid, row.kind, row.name, row.last_activity_at))+ .collect::<Vec<_>>();+ assert_eq!(+ listed,+ [(+ registered_jid,+ "direct".to_owned(),+ Some("Customer".to_owned()),+ None+ )]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+/// A lookup started while no replica ran the account (its signal went+/// nowhere) is answered once the account connects.+async fn lookups_pending_before_connecting_are_answered_once_connected(pool: PgPool) {+ let (account, _pairing) = insert_pairing_account(&pool).await;+ make_connected(&pool, account, false).await;+ sqlx::query!(+ "INSERT INTO whatsapp_lookup (id, account_id, phone_number, state) VALUES ($1, $2, $3, 'pending')",+ Uuid::now_v7(),+ account,+ UNREGISTERED+ )+ .execute(&pool)+ .await+ .unwrap();+ let (runner, whatsapp, mut calls) = runner(&pool);+ *whatsapp.identity.lock().unwrap() = Some(IDENTITY.to_owned());+ let started = start(&runner, account);+ assert_eq!(calls.recv().await, Some(Call::Open(1, false)));+ assert_eq!(calls.recv().await, Some(Call::Connect));+ event_sender(&whatsapp)+ .send(SessionEvent::Connected)+ .unwrap();+ assert_eq!(calls.recv().await, Some(Call::JoinedGroups));+ assert_eq!(+ calls.recv().await,+ Some(Call::LookUp(UNREGISTERED.to_owned()))+ );+ started.release.cancel();+ assert_eq!(started.running.await.unwrap(), AccountExit::Released);+}diff --git a/services/whatsapp_session_service/src/domain/ports.rs b/services/whatsapp_session_service/src/domain/ports.rsindex c49fb8722d..2184b784a7 100644--- a/services/whatsapp_session_service/src/domain/ports.rs+++ b/services/whatsapp_session_service/src/domain/ports.rs@@ -10,9 +10,10 @@ use tokio::sync::mpsc;use tokio_util::sync::CancellationToken;use uuid::Uuid;use whatsapp_linked::domain::events::{- ChatUpdate, ClaimedSend, HistoryPage, InboundEvent, MediaImport, MessageAnchor, OutboundMedia,- SessionScope,+ ChatUpdate, ClaimedSend, HistoryPage, InboundEvent, LookupAnswer, MediaImport, MessageAnchor,+ OutboundMedia, SessionScope,};+use whatsapp_linked::domain::jid::PhoneNumber;use whatsapp_linked::domain::models::GroupInfo;/// Errors from taking, holding or announcing account locks.@@ -80,6 +81,8 @@ pub enum AccountSignal {Send,/// `whatsapp_roster_requested`: refresh the group list.Groups,+ /// `whatsapp_lookup_requested`: answer pending phone-number lookups.+ Lookup,/// `whatsapp_account_changed`: consent or adopted groups changed.Changed,/// Notifications may have been missed; re-read everything.@@ -338,6 +341,13 @@ pub trait WhatsAppSession: Send + Sync + 'static {message: &MessageAnchor,) -> impl Future<Output = Result<(), SessionError>> + Send;+ /// Asks WhatsApp whether a phone number has an account (one usync+ /// query; it records the number's LID pairing in the LID store).+ fn look_up(+ &self,+ phone: &PhoneNumber,+ ) -> impl Future<Output = Result<LookupAnswer, SessionError>> + Send;+/// Unlinks the device at WhatsApp.fn logout(&self) -> impl Future<Output = ()> + Send;diff --git a/services/whatsapp_session_service/src/domain/supervisor.rs b/services/whatsapp_session_service/src/domain/supervisor.rsindex 38ff114c34..dabc46a219 100644--- a/services/whatsapp_session_service/src/domain/supervisor.rs+++ b/services/whatsapp_session_service/src/domain/supervisor.rs@@ -30,6 +30,8 @@ pub enum Signal {SendRequested(Uuid),/// `whatsapp_roster_requested`.GroupsRequested(Uuid),+ /// `whatsapp_lookup_requested`.+ LookupRequested(Uuid),/// `whatsapp_account_changed`.AccountChanged(Uuid),/// The listener reconnected, so notifications may have been missed.@@ -182,6 +184,10 @@ whereself.forward(account, AccountSignal::Groups, span);Ok(())}+ Signal::LookupRequested(account) => {+ self.forward(account, AccountSignal::Lookup, span);+ Ok(())+ }Signal::AccountChanged(account) if self.accounts.contains_key(&account) => {self.forward(account, AccountSignal::Changed, span);Ok(())diff --git a/services/whatsapp_session_service/src/outbound/signals.rs b/services/whatsapp_session_service/src/outbound/signals.rsindex 48c034b1a4..c845c071b8 100644--- a/services/whatsapp_session_service/src/outbound/signals.rs+++ b/services/whatsapp_session_service/src/outbound/signals.rs@@ -16,17 +16,19 @@ use tokio_util::sync::CancellationToken;use external_chat::signals::trace_context;use whatsapp_linked::signals::{- ACCOUNT_CHANGED, ACCOUNT_RELEASED, GROUPS_REQUESTED, PAIRING_REQUESTED, SEND_REQUESTED,+ ACCOUNT_CHANGED, ACCOUNT_RELEASED, GROUPS_REQUESTED, LOOKUP_REQUESTED, PAIRING_REQUESTED,+ SEND_REQUESTED,};use crate::domain::ports::Traced;use crate::domain::supervisor::Signal;-const CHANNELS: [&str; 5] = [+const CHANNELS: [&str; 6] = [ACCOUNT_RELEASED,PAIRING_REQUESTED,SEND_REQUESTED,GROUPS_REQUESTED,+ LOOKUP_REQUESTED,ACCOUNT_CHANGED,];@@ -112,6 +114,7 @@ pub fn parse(channel: &str, payload: &str) -> Option<(Signal, Option<String>)> {PAIRING_REQUESTED => Some(Signal::PairingRequested(id)),SEND_REQUESTED => Some(Signal::SendRequested(id)),GROUPS_REQUESTED => Some(Signal::GroupsRequested(id)),+ LOOKUP_REQUESTED => Some(Signal::LookupRequested(id)),ACCOUNT_CHANGED => Some(Signal::AccountChanged(id)),_ => None,}?;diff --git a/services/whatsapp_session_service/src/outbound/whatsapp.rs b/services/whatsapp_session_service/src/outbound/whatsapp.rsindex bf3b599b29..ac5cc22e17 100644--- a/services/whatsapp_session_service/src/outbound/whatsapp.rs+++ b/services/whatsapp_session_service/src/outbound/whatsapp.rs@@ -13,9 +13,10 @@ use tokio_util::sync::CancellationToken;use tracing::Instrument;use uuid::Uuid;use whatsapp_linked::domain::events::{- ChatUpdate, ClaimedSend, InboundEvent, MediaImport, MessageAnchor, OutboundMedia,+ ChatUpdate, ClaimedSend, InboundEvent, LookupAnswer, MediaImport, MessageAnchor, OutboundMedia,OutgoingContent, SessionScope, Target,};+use whatsapp_linked::domain::jid::PhoneNumber;use whatsapp_linked::domain::models::{GroupInfo, Identity, Participant};use whatsapp_store_pg::kms::WhatsAppKms;use whatsapp_store_pg::{PgWhatsAppStore, WhatsAppStoreError};@@ -25,7 +26,7 @@ use whatsmeow::proto::wa_history_sync::Conversation;use whatsmeow::proto::wa_history_sync::history_sync::HistorySyncType;use whatsmeow::send::{SendRequestExtra, build_edit};use whatsmeow::signal::CurveSignatures;-use whatsmeow::store::Device;+use whatsmeow::store::{ContactStore, Device};use whatsmeow::types::{Jid, MessageInfo, MessageSource, WebAuthnResponse};use whatsmeow::{Client, ClientConfig, ClientError, Dialer, Event, EventHandler, QrChannelItem, Signal,@@ -238,6 +239,32 @@ impl Forwarder {let _ = self.events.send(SessionEvent::Chats(chats));}+ /// The address book's saved contacts join the chat list, so the owner+ /// can start a chat with someone never written to. Read on connect and+ /// after each app-state sync (contacts sync through app state); rows+ /// that did not change signal nothing.+ async fn saved_contacts(&self) {+ let span = tracing::info_span!(+ "whatsapp.contacts.sync",+ account_id = %self.account,+ contacts = tracing::field::Empty,+ );+ async {+ match self.store.get_all_contacts().await {+ Ok(contacts) => {+ let chats = events::contact_chats(&contacts);+ tracing::Span::current().record("contacts", chats.len());+ self.chats(chats).await;+ }+ Err(error) => {+ tracing::warn!(error = %error, "Reading the WhatsApp address book failed");+ }+ }+ }+ .instrument(span)+ .await;+ }+/// A history-sync bundle: the chat list (initial, recent, full and/// push-name syncs), or an answer to an on-demand request for a chat's/// earlier messages.@@ -409,6 +436,9 @@ impl EventHandler for Forwarder {Event::Message(message) => {Box::pin(self.chats(events::message_chat(message).into_iter().collect())).await;}+ Event::Connected(_) | Event::AppStateSyncComplete(_) => {+ Box::pin(self.saved_contacts()).await;+ }event => {Box::pin(self.chats(events::chat_setting(event).into_iter().collect())).await;}@@ -951,6 +981,15 @@ impl WhatsAppSession for WhatsmeowSession {.map_err(internal)}+ async fn look_up(&self, phone: &PhoneNumber) -> Result<LookupAnswer, SessionError> {+ let answers = self+ .client+ .is_on_whatsapp(&[phone.as_str()])+ .await+ .map_err(internal)?;+ Ok(events::lookup_answer(self.store.as_ref(), self.store.as_ref(), phone, &answers).await)+ }+async fn logout(&self) {if let Err(error) = self.client.logout().await {tracing::warn!(error = %error, "Logging the WhatsApp device out failed");diff --git a/services/whatsapp_session_service/src/outbound/whatsapp/events.rs b/services/whatsapp_session_service/src/outbound/whatsapp/events.rsindex 69f21a34b7..e2c586860c 100644--- a/services/whatsapp_session_service/src/outbound/whatsapp/events.rs+++ b/services/whatsapp_session_service/src/outbound/whatsapp/events.rs@@ -2,6 +2,8 @@//! Only group traffic becomes [`InboundEvent`]s; the account runner then drops//! everything outside adopted groups.+use std::collections::HashMap;+use chrono::{DateTime, Utc};use external_chat::domain::rich::SystemLine;use external_chat::domain::{@@ -11,9 +13,10 @@ use external_chat::domain::{use serde::{Deserialize, Serialize};use uuid::Uuid;use whatsapp_linked::domain::events::{- ChatUpdate, HistoryPage, InboundEvent, InboundKind, Media, Message, MessageAnchor, MessageKind,- Receipt, ReceiptState, Target,+ ChatUpdate, HistoryPage, InboundEvent, InboundKind, LookupAnswer, Media, Message,+ MessageAnchor, MessageKind, Receipt, ReceiptState, Target,};+use whatsapp_linked::domain::jid::PhoneNumber;use whatsapp_linked::domain::models::Identity;use whatsmeow::Event;use whatsmeow::download::{DownloadableMessage, MediaType};@@ -25,7 +28,10 @@ use whatsmeow::proto::wa_history_sync::{Conversation, HistorySync, Pushname};use whatsmeow::proto::wa_web::WebMessageInfo;use whatsmeow::store::{ContactStore, LidStore, StoreError};use whatsmeow::types::events::GroupInfo;-use whatsmeow::types::{DEFAULT_USER_SERVER, GROUP_SERVER, HIDDEN_USER_SERVER, Jid, MessageSource};+use whatsmeow::types::{+ ContactInfo, DEFAULT_USER_SERVER, GROUP_SERVER, HIDDEN_USER_SERVER, IsOnWhatsAppResponse, Jid,+ MessageSource,+};use crate::domain::ports::SessionEvent;@@ -1228,6 +1234,8 @@ pub fn chat_setting(event: &Event) -> Option<ChatUpdate> {}).filter(|chat| chat.kind == ExternalChatKind::Direct)}+ // A saved contact is someone to start a chat with, so it is listed+ // even before anyone wrote.Event::Contact(contact) => {let action = contact.action.as_ref()?;let name = action@@ -1235,13 +1243,71 @@ pub fn chat_setting(event: &Event) -> Option<ChatUpdate> {.as_deref().or(action.first_name.as_deref()).filter(|name| !name.trim().is_empty())?;- setting_chat(&contact.jid, |chat| chat.name = Some(name.to_owned()))- .filter(|chat| chat.kind == ExternalChatKind::Direct)+ setting_chat(&contact.jid, |chat| {+ chat.name = Some(name.to_owned());+ chat.create = true;+ })+ .filter(|chat| chat.kind == ExternalChatKind::Direct)}_ => None,}}+/// The address book's saved contacts as direct chats with no activity, so+/// the chat list offers people never written to. People only seen with a+/// WhatsApp or business name (in groups, say) are not saved contacts.+pub fn contact_chats(contacts: &HashMap<Jid, ContactInfo>) -> Vec<ChatUpdate> {+ contacts+ .iter()+ .filter_map(|(jid, contact)| {+ let name = [&contact.full_name, &contact.first_name]+ .into_iter()+ .find(|name| !name.trim().is_empty())?;+ setting_chat(jid, |chat| {+ chat.name = Some(name.clone());+ chat.create = true;+ })+ .filter(|chat| chat.kind == ExternalChatKind::Direct)+ })+ .collect()+}++/// WhatsApp's answer to `IsOnWhatsApp` for one number: registered numbers+/// are found as their phone-number chat, named like any chat (address book,+/// else the verified business or WhatsApp name).+pub async fn lookup_answer(+ lids: &dyn LidStore,+ contacts: &dyn ContactStore,+ phone: &PhoneNumber,+ answers: &[IsOnWhatsAppResponse],+) -> LookupAnswer {+ let Some(answer) = answers.iter().find(|answer| answer.is_in) else {+ return LookupAnswer::NotOnWhatsApp;+ };+ let business = answer+ .verified_name+ .as_ref()+ .and_then(|verified| verified.details.as_ref())+ .and_then(|details| details.verified_name.clone())+ .filter(|name| !name.trim().is_empty());+ let mut chats = [ChatUpdate {+ jid: phone.jid(),+ kind: ExternalChatKind::Direct,+ name: business,+ last_activity_at: None,+ archived: None,+ pinned: None,+ anchor: None,+ create: true,+ }];+ complete_chats(lids, contacts, &mut chats).await;+ let [chat] = chats;+ LookupAnswer::Found {+ jid: chat.jid,+ name: chat.name,+ }+}+/// Direct chats by phone number when the LID store knows it, and named after/// the address book (else the WhatsApp name) when nothing better was given.pub async fn complete_chats(diff --git a/services/whatsapp_session_service/src/outbound/whatsapp/events/test.rs b/services/whatsapp_session_service/src/outbound/whatsapp/events/test.rsindex 0df708c36d..1fd1ff5b01 100644--- a/services/whatsapp_session_service/src/outbound/whatsapp/events/test.rs+++ b/services/whatsapp_session_service/src/outbound/whatsapp/events/test.rs@@ -1301,3 +1301,5 @@ async fn a_lid_store_failure_is_reported_instead_of_completing_nothing() {.is_err());}++mod contacts;diff --git a/services/whatsapp_session_service/src/outbound/whatsapp/events/test/contacts.rs b/services/whatsapp_session_service/src/outbound/whatsapp/events/test/contacts.rsnew file mode 100644index 0000000000..6654d6d49e--- /dev/null+++ b/services/whatsapp_session_service/src/outbound/whatsapp/events/test/contacts.rs@@ -0,0 +1,164 @@+//! Saved contacts and phone-number lookups as chat-list rows.++use std::collections::HashMap;++use external_chat::domain::models::ExternalChatKind;+use whatsapp_linked::domain::events::{ChatUpdate, LookupAnswer};+use whatsapp_linked::domain::jid::PhoneNumber;+use whatsmeow::Event;+use whatsmeow::proto::wa_sync_action::ContactAction;+use whatsmeow::proto::wa_vname_cert::verified_name_certificate::Details;+use whatsmeow::store::{ContactStore, MemoryStore};+use whatsmeow::types::events::Contact;+use whatsmeow::types::{+ ContactInfo, DEFAULT_USER_SERVER, IsOnWhatsAppResponse, VerifiedName, new_jid,+};++use super::super::{chat_setting, contact_chats, lookup_answer};++fn listed(jid: &str, name: &str) -> ChatUpdate {+ ChatUpdate {+ jid: jid.to_owned(),+ kind: ExternalChatKind::Direct,+ name: Some(name.to_owned()),+ last_activity_at: None,+ archived: None,+ pinned: None,+ anchor: None,+ create: true,+ }+}++#[test]+fn saved_contacts_are_listed_and_people_only_seen_in_groups_are_not() {+ let [dana, eve, shop] =+ ["5550001", "5550002", "5550003"].map(|user| new_jid(user, DEFAULT_USER_SERVER));+ let contacts = HashMap::from([+ (+ dana.clone(),+ ContactInfo {+ full_name: "Dana Smith".to_owned(),+ first_name: "Dana".to_owned(),+ push_name: "dana".to_owned(),+ ..ContactInfo::default()+ },+ ),+ (+ eve.clone(),+ ContactInfo {+ first_name: "Eve".to_owned(),+ ..ContactInfo::default()+ },+ ),+ (+ "987654321@lid".parse().unwrap(),+ ContactInfo {+ full_name: "Frank".to_owned(),+ ..ContactInfo::default()+ },+ ),+ (+ shop,+ ContactInfo {+ push_name: "Seen in a group".to_owned(),+ business_name: "Some shop".to_owned(),+ ..ContactInfo::default()+ },+ ),+ ]);++ let mut chats = contact_chats(&contacts);+ chats.sort_by(|a, b| a.jid.cmp(&b.jid));++ assert_eq!(+ chats,+ [+ listed(&dana.to_string(), "Dana Smith"),+ listed(&eve.to_string(), "Eve"),+ listed("987654321@lid", "Frank"),+ ]+ );+}++#[test]+fn a_contact_saved_on_the_phone_is_listed_at_once() {+ let eve = new_jid("5550002", DEFAULT_USER_SERVER);+ let event = Event::Contact(Box::new(Contact {+ jid: eve.clone(),+ timestamp: chrono::Utc::now(),+ action: Some(ContactAction {+ full_name: Some("Eve Adams".to_owned()),+ ..ContactAction::default()+ }),+ from_full_sync: false,+ }));++ assert_eq!(+ chat_setting(&event),+ Some(listed(&eve.to_string(), "Eve Adams"))+ );+}++#[tokio::test]+async fn a_registered_number_is_its_phone_chat_named_like_any_chat() {+ let store = MemoryStore::default();+ let dana = new_jid("5550001", DEFAULT_USER_SERVER);+ let corner_shop = new_jid("5550004", DEFAULT_USER_SERVER);+ store+ .put_contact_name(&dana, "Dana Smith", "Dana")+ .await+ .unwrap();+ // WhatsApp answers by LID with the number alongside.+ let registered = |business: Option<&str>| IsOnWhatsAppResponse {+ query: "+5550001".to_owned(),+ jid: "987654321@lid".parse().unwrap(),+ is_in: true,+ phone_number: dana.clone(),+ verified_name: business.map(|name| VerifiedName {+ details: Some(Details {+ verified_name: Some(name.to_owned()),+ ..Details::default()+ }),+ ..VerifiedName::default()+ }),+ };+ let phone = |number: &str| PhoneNumber::parse(number).unwrap();++ assert_eq!(+ lookup_answer(+ &store,+ &store,+ &phone("+5550001"),+ &[registered(Some("Dana's Bakery"))]+ )+ .await,+ LookupAnswer::Found {+ jid: dana.to_string(),+ name: Some("Dana Smith".to_owned()),+ },+ "the address book wins over the business name"+ );+ let unsaved = IsOnWhatsAppResponse {+ phone_number: corner_shop.clone(),+ ..registered(Some("Corner Shop"))+ };+ assert_eq!(+ lookup_answer(&store, &store, &phone("+5550004"), &[unsaved]).await,+ LookupAnswer::Found {+ jid: corner_shop.to_string(),+ name: Some("Corner Shop".to_owned()),+ }+ );+ let not_registered = IsOnWhatsAppResponse {+ is_in: false,+ ..registered(None)+ };+ assert_eq!(+ lookup_answer(&store, &store, &phone("+5550005"), &[not_registered]).await,+ LookupAnswer::NotOnWhatsApp+ );+ assert_eq!(+ lookup_answer(&store, &store, &phone("+5550005"), &[]).await,+ LookupAnswer::NotOnWhatsApp+ );+}