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(sdk): return web urls from agent sessions and other linkable entities (#9321)
Wolf Mermelsteine0c6fd823b3f
diff --git a/.agents/skills/add-sdk-endpoint/SKILL.md b/.agents/skills/add-sdk-endpoint/SKILL.mdindex a1c4c75bc4..b7063b7fe9 100644--- a/.agents/skills/add-sdk-endpoint/SKILL.md+++ b/.agents/skills/add-sdk-endpoint/SKILL.md@@ -55,6 +55,11 @@ To skip: add the method name, alphabetically, to `<camelService>Excluded` in- cursor lists → `paginate()` → `AsyncGenerator`; search → `entitySearch(...)`- camelCase + `undefined` on the SDK side even when the wire is snake_case/nullable- TSDoc every public member. No `any`.+ - an entity with its own page in the app gets `webUrl()`, built from+ `this.client.webAppUrl` and the route the web app's copy-link action uses+ (`/app/agent/<id>`, not the entity type when they differ), plus a+ `toJSON()` override adding `url: this.webUrl()`. Agents hand these links+ to users; without one they guess the route.5. **New service?** Only when the endpoint's service isn't reachable from`MacroClient` yet — per *service*, not per entity; a new entity needs none of this.Wire the `Sdk` into `src/utils/client.ts`, a host into `src/config.ts`, and andiff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex ebdbdd03ab..a521b234b7 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -16452,7 +16452,7 @@ export interface CodeGuide {** For editable email/calendar drafts, persist them with execution.reviews.create({kind, title, drafts}), then return reviews: [await review.reference()]. This does not send emails or create calendar events. Creation immediately presents a completed PresentReview ACP tool call, even while main continues. "Presented to the user" means saved in the conversation, not approved or sent. The saved cards remain usable after this execution and chat continues. User decisions arrive as typed system events referring to the same review ID. Use GetReview to read final drafts and confirmed outcomes; notifications never authorize repeating an action. To show the user what the program made, changed or found, present a view with await execution.views.present(view). It is checked and drawn at once, while main continues; nothing is saved and nothing comes back. When to present a view, and its format, are in the PresentView schema at the end of this description. Use the direct EditDocument tool for AI document edits. Direct human-interactive tools, subagents and unsupported SDK operations remain available.*- * Do the whole job in as few executions as possible, ideally one: every execution costs a model turn. Put control flow in the program instead of checking in one execution and acting in the next, e.g. if macro.tasks.findSimilar finds no likely duplicate, create the task and return it, else return the matches without creating. Use nested SDK entities, e.g. macro.documents.search(query) is an async iterator and document.content() is a promise. Use for await...of, break, conditions and ordinary JavaScript freely. Batch useful independent work with Promise.all or Promise.allSettled; inspect partial failures and await every started operation. Use bounded concurrency for large inputs. Preserve user source scope on every search and retry: macro.documents.search searches documents; macro.email.search searches emails. Read names in batches: macro.initiatives.summaries() and macro.tasks.summaries(tasks) each take one request, while name() on every handle loads each entity separately. Create a task with its initiative, assignees and dueDate in one macro.tasks.create call. Return compact evidence with source IDs, URLs, explicit failures and coverage limits, enough to answer without a follow-up execution; do not return SDK objects, raw large batches, or claim a stopped iterator is exhaustive.+ * Do the whole job in as few executions as possible, ideally one: every execution costs a model turn. Put control flow in the program instead of checking in one execution and acting in the next, e.g. if macro.tasks.findSimilar finds no likely duplicate, create the task and return it, else return the matches without creating. Use nested SDK entities, e.g. macro.documents.search(query) is an async iterator and document.content() is a promise. Use for await...of, break, conditions and ordinary JavaScript freely. Batch useful independent work with Promise.all or Promise.allSettled; inspect partial failures and await every started operation. Use bounded concurrency for large inputs. Preserve user source scope on every search and retry: macro.documents.search searches documents; macro.email.search searches emails. Read names in batches: macro.initiatives.summaries() and macro.tasks.summaries(tasks) each take one request, while name() on every handle loads each entity separately. Create a task with its initiative, assignees and dueDate in one macro.tasks.create call. Return compact evidence with source IDs, URLs, explicit failures and coverage limits, enough to answer without a follow-up execution; for each item you create or point the user to, return its webUrl() as the URL rather than building one; do not return SDK objects, raw large batches, or claim a stopped iterator is exhaustive.** For a workspace overview, fetch small pages for the relevant categories concurrently in one execution with macro.workspace.page({includeTypes:[type], limit:3}). A single mixed page can be dominated by one category; each page is a sample, not a category total. Return selected metadata and hasMore per category, not whole items or snapshots. Exact workspace types include calendar_event, ai_chat and channel_thread. Tasks are documents: use includeTypes:["document"], df:{l:{dst:"task"}}. AST & and | combine exactly two expressions; do not wrap a single filter.*diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.jsonindex 3eee715048..59a0b14b3d 100644--- a/crates/agent_code_mode/src/domain/documentation.json+++ b/crates/agent_code_mode/src/domain/documentation.json@@ -3,7 +3,7 @@{"name": "agentSessions","description": "Create and inspect agent sessions, read any viewable session's history as folded messages (`session.foldedLog()`), saved code executions, and editable email or calendar review stacks.",- "index": "## agentSessions\nCreate and inspect agent sessions, read any viewable session's history as folded messages (`session.foldedLog()`), saved code executions, and editable email or calendar review stacks.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### AgentSession\nA managed or externally hosted coding-agent session.\nExtends `MacroEntity`.\nFields: access, archivedAt, archivedBy, codeExecutions, createdAt, harness, id, instructions, model, modifiedAt, name, repoUrl, reviews, sandboxSize, status, views, workspace\n- `AgentSession.archive`: archive(): Promise<void> — Archive this session, making it read-only until unarchived.\n- `AgentSession.autoArchive`: autoArchive(): Promise<SessionAutoArchive> — This session's auto-archive settings, and when a trigger archived it.\n- `AgentSession.changes`: changes(): Promise<AgentSessionChangesResponse> — Read the latest captured GitHub pull request changes and capture status.\n- `AgentSession.changesPatch`: changesPatch(): Promise<string> — Read the unified diff of the latest captured changeset.\n- `AgentSession.control`: control(action): Promise<ControlResponse> — Send a prompt or lifecycle operation to the live agent session.\n- `AgentSession.delete`: delete(): Promise<void> — Delete this session and any live resources it owns.\n- `AgentSession.foldedLog`: foldedLog(): Promise<FoldedAgentSessionLog> — Read this session's whole history as the conversation the app renders: each user prompt and agent reply, oldest first, with tool calls and their results, pla...\n- `AgentSession.linkPullRequest`: linkPullRequest(url): Promise<void> — Link the GitHub pull request at url to this session.\n- `AgentSession.log`: log(): Promise<AgentSessionLogResponse> — Read the complete raw protocol log for this session.\n- `AgentSession.prompt`: prompt(text, attachments?): Promise<ControlResponse> — Send a prompt to the session — sugar over [control](#control).\n- `AgentSession.pullRequests`: pullRequests(): Promise<SessionPullRequest[]> — The GitHub pull requests linked to this session: the one its agent opened and any a person linked, oldest first.\n- `AgentSession.queue`: queue(): Promise<QueuedAction[]> — The actions waiting to dispatch in this session, oldest first.\n- `AgentSession.refreshChanges`: refreshChanges(): Promise<AgentSessionChangesResponse> — Request a fresh capture and return the current state while it runs.\n- `AgentSession.rename`: rename(name): Promise<void> — Rename this session.\n- `AgentSession.setAutoArchive`: setAutoArchive(overrides): Promise<void> — Replace this session's auto-archive choices.\n- `AgentSession.setSandboxSize`: setSandboxSize(size): Promise<SandboxSize> — Resize this session's sandbox and remember the size as the owner's default.\n- `AgentSession.sharePermissions`: sharePermissions(): Promise<agent-harness.SharePermissionV2> — Sharing configuration.\n- `AgentSession.toolApprovalById`: toolApprovalById(id): ToolApproval — Construct an approval handle scoped to this session.\n- `AgentSession.unarchive`: unarchive(): Promise<void> — Restore an archived session so it can be edited and prompted again.\n- `AgentSession.unlinkPullRequest`: unlinkPullRequest(url): Promise<void> — Unlink a GitHub pull request a person linked to this session.\n- `AgentSession.updateSharePermissions`: updateSharePermissions(options): Promise<agent-harness.SharePermissionV2> — Replace sharing grants.\n- `AgentSession.autoArchivePreferences`: static autoArchivePreferences(client): Promise<AutoArchivePreferencesBody> — Which triggers archive the caller's sessions by default; each is off unless chosen.\n- `AgentSession.byId`: static byId(client, id): AgentSession — A handle to an agent session by id.\n- `AgentSession.chooseMode`: static chooseMode(client, prompt): Promise<AgentMode> — Whether prompt needs a chat agent or a coding agent, as the app's Auto mode decides before starting a session.\n- `AgentSession.codingPreferences`: static codingPreferences(client): Promise<CodingPreferencesBody> — What the caller's new coding sessions are told to do beyond their assignment.\n- `AgentSession.createManaged`: static createManaged(client, opts?): Promise<AgentSession> — Create a managed session as agent when one is named, otherwise the deployment's default coding persona.\n- `AgentSession.defaultSandboxSize`: static defaultSandboxSize(client): Promise<SandboxSize> — The caller's default sandbox size for new @coder sessions.\n- `AgentSession.forPullRequest`: static forPullRequest(client, url): Promise<AgentSession[]> — The sessions linked to the GitHub pull request at url that the caller can view, oldest link first.\n- `AgentSession.repositories`: static repositories(client): Promise<SelectableRepository[]> — The GitHub repositories the caller can hand a managed session: every repository under an installation of Macro's GitHub App they or their teams made, sorted ...\n- `AgentSession.repositoryBranches`: static repositoryBranches(client, repoUrl): Promise<string[]> — Branch names on one repository the caller can start a managed session from, in the order GitHub listed them.\n- `AgentSession.setAutoArchivePreferences`: static setAutoArchivePreferences(client, preferences): Promise<AutoArchivePreferencesBody> — Replace which triggers archive the caller's sessions by default.\n- `AgentSession.setCodingPreferences`: static setCodingPreferences(client, preferences): Promise<CodingPreferencesBody> — Replace the caller's coding preferences.\n- `AgentSession.setDefaultSandboxSize`: static setDefaultSandboxSize(client, size): Promise<SandboxSize> — Set the caller's default sandbox size for the next @coder mention.\n\n### CodeExecution\nA saved code execution belonging to one agent session.\nExtends `MacroEntity`.\nFields: calls, error, id, reviews, source, status, views\n- `CodeExecution.refresh`: refresh(): Promise<CodeExecution> — Reload the saved state, for example after a running execution completes.\n- `CodeExecution.result`: result(): Promise<unknown> — The program's returned JSON; preserves an explicit null result.\n- `CodeExecution.session`: session(): AgentSession — The session this execution belongs to.\n- `CodeExecution.byId`: static byId(client, session, id): CodeExecution — Construct a lazy execution handle within its owning session.\n\n### AgentConversation\nAn agent's conversation in one channel.\nFields: channel\n- `AgentConversation.agent`: agent(): Agent — The agent taking part.\n- `AgentConversation.sessions`: sessions(): { createdAt: string; isCurrent: boolean; session: AgentSession; }[] — Conversation sessions with their current flag.\n- `AgentConversation.startFresh`: startFresh(session): Promise<void> — Start a fresh conversation from one of its sessions.\n- `AgentConversation.toJSON`: toJSON(): { agentId: string; channelId: string; } — Serialize scoped identity.\n- `AgentConversation.turns`: turns(): ConversationTurn[] — Recorded conversation turns.\n\n### ConversationTurn\nOne agent conversation turn, identified by its source message.\nFields: conversation\n- `ConversationTurn.retry`: retry(actionId): Promise<void> — Retry with a caller persisted action nonce.\n- `ConversationTurn.session`: session(): AgentSession — Session that handled this turn.\n- `ConversationTurn.source`: source(): Message — Originating message.\n- `ConversationTurn.toJSON`: toJSON(): { channelId: string; sourceMessageId: string; } — Serialize scoped identity.\n\n### AgentSessionNamespace (`macro.agentSessions`)\nEntry point for coding-agent sessions.\n- `AgentSessionNamespace.autoArchivePreferences`: autoArchivePreferences(): Promise<AutoArchivePreferencesBody> — Which triggers archive the caller's sessions by default; each is off unless chosen.\n- `AgentSessionNamespace.byId`: byId(id): AgentSession — A handle to an agent session by id.\n- `AgentSessionNamespace.chooseMode`: chooseMode(prompt): Promise<AgentMode> — Whether prompt needs a chat agent ('chat') or a coding agent ('code'), as the app's Auto mode decides before starting a session.\n- `AgentSessionNamespace.codingPreferences`: codingPreferences(): Promise<CodingPreferencesBody> — What the caller's new coding sessions are told to do beyond their assignment.\n- `AgentSessionNamespace.createManaged`: createManaged(opts?): Promise<AgentSession> — Create a managed session as agent when one is named, otherwise the deployment's default coding persona.\n- `AgentSessionNamespace.defaultSandboxSize`: defaultSandboxSize(): Promise<SandboxSize> — The caller's default sandbox size for new @coder sessions.\n- `AgentSessionNamespace.forPullRequest`: forPullRequest(url): Promise<AgentSession[]> — The sessions linked to the GitHub pull request at url that the caller can view.\n- `AgentSessionNamespace.repositories`: repositories(): Promise<SelectableRepository[]> — The GitHub repositories the caller can hand a managed session, with the branch each one's sessions start on by default.\n- `AgentSessionNamespace.repositoryBranches`: repositoryBranches(repoUrl): Promise<string[]> — Branch names on one repository the caller can start a managed session from.\n- `AgentSessionNamespace.setAutoArchivePreferences`: setAutoArchivePreferences(preferences): Promise<AutoArchivePreferencesBody> — Replace which triggers archive the caller's sessions by default.\n- `AgentSessionNamespace.setCodingPreferences`: setCodingPreferences(preferences): Promise<CodingPreferencesBody> — Replace the caller's coding preferences.\n- `AgentSessionNamespace.setDefaultSandboxSize`: setDefaultSandboxSize(size): Promise<SandboxSize> — Set the caller's default sandbox size for the next @coder mention.\n\n### QueuedAction\nOne action waiting in an agent session's server-side queue: a prompt or a compact accepted while a turn was running, dispatching when that turn ends.\n- `QueuedAction.edit`: edit(prompt): Promise<QueuedAction> — Replace this queued prompt's text before it dispatches.\n- `QueuedAction.remove`: remove(): Promise<void> — Remove this action from the queue before it dispatches.\n- `QueuedAction.steer`: steer(): Promise<void> — Move this action to the front and interrupt the current turn to run it next.\n- `QueuedAction.from`: static from(client, sessionId, dto): QueuedAction — Wrap a queue entry already in hand (e.g.\n\n### ReviewItem\nAn item handle scopes edits and decisions to its persisted review.\n- `ReviewItem.dismiss`: dismiss(): Promise<void> — Promise<void>\n- `ReviewItem.edit`: edit(draft): Promise<void> — Replace this pending draft; kind must match the review's.\n- `ReviewItem.submit`: submit(): Promise<void> — Promise<void>\n\n### SessionReview\nA persistent review remains actionable after the code execution ends.\nExtends `MacroEntity`.\nFields: id, kind, title\n- `SessionReview.dismissAll`: dismissAll(): Promise<void> — Promise<void>\n- `SessionReview.items`: items(): Promise<ReviewItem[]> — Promise<ReviewItem[]>\n- `SessionReview.reference`: reference(): Promise<{ id: string; kind: \"calendar\" | \"email\" | \"import\"; }> — Compact reference for main()'s returned reviews array.\n- `SessionReview.refresh`: refresh(): Promise<SessionReview> — Promise<SessionReview>\n- `SessionReview.session`: session(): AgentSession — AgentSession\n- `SessionReview.submitAll`: submitAll(): Promise<void> — Submit the saved pending drafts.\n- `SessionReview.byId`: static byId(client, session, id): SessionReview — SessionReview\n- `SessionReview.create`: static create(client, execution, input): Promise<SessionReview> — Promise<SessionReview>\n- `SessionReview.createForSession`: static createForSession(client, session, input, execution?): Promise<SessionReview> — Present a review in a session without requiring a code execution.\n- `SessionReview.fromRecord`: static fromRecord(client, session, record): SessionReview — SessionReview\n- `SessionReview.list`: static list(client, execution): Promise<SessionReview[]> — Promise<SessionReview[]>\n\n### ToolApproval\nA permission request scoped to its originating agent session.\nFields: id, session\n- `ToolApproval.answer`: answer(answer): Promise<AnswerToolApprovalResponse> — Answer the approval using the generated discriminated answer contract.\n- `ToolApproval.toJSON`: toJSON(): { id: string; sessionId: string; } — Serialize scoped identity only.\n- `ToolApproval.byId`: static byId(client, session, id): ToolApproval — Construct a scoped approval handle.\n\nFunctions: `presentView`\n\nTypes: `AutoArchiveOverrides`, `CreateManagedSessionOptions`, `FoldedAgentSessionLog`, `SelectableRepository`, `SessionAutoArchive`, `SessionPullRequest`, `CodeResult`, `JsonValue`, `CreateReviewOptions`, `ReviewCalendarDraft`, `ReviewDraft`, `ReviewEmailDraft`, `SessionView`\n"+ "index": "## agentSessions\nCreate and inspect agent sessions, read any viewable session's history as folded messages (`session.foldedLog()`), saved code executions, and editable email or calendar review stacks.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### AgentSession\nA managed or externally hosted coding-agent session.\nExtends `MacroEntity`.\nFields: access, archivedAt, archivedBy, codeExecutions, createdAt, harness, id, instructions, model, modifiedAt, name, repoUrl, reviews, sandboxSize, status, views, workspace\n- `AgentSession.archive`: archive(): Promise<void> — Archive this session, making it read-only until unarchived.\n- `AgentSession.autoArchive`: autoArchive(): Promise<SessionAutoArchive> — This session's auto-archive settings, and when a trigger archived it.\n- `AgentSession.changes`: changes(): Promise<AgentSessionChangesResponse> — Read the latest captured GitHub pull request changes and capture status.\n- `AgentSession.changesPatch`: changesPatch(): Promise<string> — Read the unified diff of the latest captured changeset.\n- `AgentSession.control`: control(action): Promise<ControlResponse> — Send a prompt or lifecycle operation to the live agent session.\n- `AgentSession.delete`: delete(): Promise<void> — Delete this session and any live resources it owns.\n- `AgentSession.foldedLog`: foldedLog(): Promise<FoldedAgentSessionLog> — Read this session's whole history as the conversation the app renders: each user prompt and agent reply, oldest first, with tool calls and their results, pla...\n- `AgentSession.linkPullRequest`: linkPullRequest(url): Promise<void> — Link the GitHub pull request at url to this session.\n- `AgentSession.log`: log(): Promise<AgentSessionLogResponse> — Read the complete raw protocol log for this session.\n- `AgentSession.prompt`: prompt(text, attachments?): Promise<ControlResponse> — Send a prompt to the session — sugar over [control](#control).\n- `AgentSession.pullRequests`: pullRequests(): Promise<SessionPullRequest[]> — The GitHub pull requests linked to this session: the one its agent opened and any a person linked, oldest first.\n- `AgentSession.queue`: queue(): Promise<QueuedAction[]> — The actions waiting to dispatch in this session, oldest first.\n- `AgentSession.refreshChanges`: refreshChanges(): Promise<AgentSessionChangesResponse> — Request a fresh capture and return the current state while it runs.\n- `AgentSession.rename`: rename(name): Promise<void> — Rename this session.\n- `AgentSession.setAutoArchive`: setAutoArchive(overrides): Promise<void> — Replace this session's auto-archive choices.\n- `AgentSession.setSandboxSize`: setSandboxSize(size): Promise<SandboxSize> — Resize this session's sandbox and remember the size as the owner's default.\n- `AgentSession.sharePermissions`: sharePermissions(): Promise<agent-harness.SharePermissionV2> — Sharing configuration.\n- `AgentSession.toJSON`: toJSON(): { detail?: AgentSessionResponse; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n- `AgentSession.toolApprovalById`: toolApprovalById(id): ToolApproval — Construct an approval handle scoped to this session.\n- `AgentSession.unarchive`: unarchive(): Promise<void> — Restore an archived session so it can be edited and prompted again.\n- `AgentSession.unlinkPullRequest`: unlinkPullRequest(url): Promise<void> — Unlink a GitHub pull request a person linked to this session.\n- `AgentSession.updateSharePermissions`: updateSharePermissions(options): Promise<agent-harness.SharePermissionV2> — Replace sharing grants.\n- `AgentSession.webUrl`: webUrl(): string — The session's URL in the Macro web app; hand it to users as the link.\n- `AgentSession.autoArchivePreferences`: static autoArchivePreferences(client): Promise<AutoArchivePreferencesBody> — Which triggers archive the caller's sessions by default; each is off unless chosen.\n- `AgentSession.byId`: static byId(client, id): AgentSession — A handle to an agent session by id.\n- `AgentSession.chooseMode`: static chooseMode(client, prompt): Promise<AgentMode> — Whether prompt needs a chat agent or a coding agent, as the app's Auto mode decides before starting a session.\n- `AgentSession.codingPreferences`: static codingPreferences(client): Promise<CodingPreferencesBody> — What the caller's new coding sessions are told to do beyond their assignment.\n- `AgentSession.createManaged`: static createManaged(client, opts?): Promise<AgentSession> — Create a managed session as agent when one is named, otherwise the deployment's default coding persona.\n- `AgentSession.defaultSandboxSize`: static defaultSandboxSize(client): Promise<SandboxSize> — The caller's default sandbox size for new @coder sessions.\n- `AgentSession.forPullRequest`: static forPullRequest(client, url): Promise<AgentSession[]> — The sessions linked to the GitHub pull request at url that the caller can view, oldest link first.\n- `AgentSession.repositories`: static repositories(client): Promise<SelectableRepository[]> — The GitHub repositories the caller can hand a managed session: every repository under an installation of Macro's GitHub App they or their teams made, sorted ...\n- `AgentSession.repositoryBranches`: static repositoryBranches(client, repoUrl): Promise<string[]> — Branch names on one repository the caller can start a managed session from, in the order GitHub listed them.\n- `AgentSession.setAutoArchivePreferences`: static setAutoArchivePreferences(client, preferences): Promise<AutoArchivePreferencesBody> — Replace which triggers archive the caller's sessions by default.\n- `AgentSession.setCodingPreferences`: static setCodingPreferences(client, preferences): Promise<CodingPreferencesBody> — Replace the caller's coding preferences.\n- `AgentSession.setDefaultSandboxSize`: static setDefaultSandboxSize(client, size): Promise<SandboxSize> — Set the caller's default sandbox size for the next @coder mention.\n\n### CodeExecution\nA saved code execution belonging to one agent session.\nExtends `MacroEntity`.\nFields: calls, error, id, reviews, source, status, views\n- `CodeExecution.refresh`: refresh(): Promise<CodeExecution> — Reload the saved state, for example after a running execution completes.\n- `CodeExecution.result`: result(): Promise<unknown> — The program's returned JSON; preserves an explicit null result.\n- `CodeExecution.session`: session(): AgentSession — The session this execution belongs to.\n- `CodeExecution.byId`: static byId(client, session, id): CodeExecution — Construct a lazy execution handle within its owning session.\n\n### AgentConversation\nAn agent's conversation in one channel.\nFields: channel\n- `AgentConversation.agent`: agent(): Agent — The agent taking part.\n- `AgentConversation.sessions`: sessions(): { createdAt: string; isCurrent: boolean; session: AgentSession; }[] — Conversation sessions with their current flag.\n- `AgentConversation.startFresh`: startFresh(session): Promise<void> — Start a fresh conversation from one of its sessions.\n- `AgentConversation.toJSON`: toJSON(): { agentId: string; channelId: string; } — Serialize scoped identity.\n- `AgentConversation.turns`: turns(): ConversationTurn[] — Recorded conversation turns.\n\n### ConversationTurn\nOne agent conversation turn, identified by its source message.\nFields: conversation\n- `ConversationTurn.retry`: retry(actionId): Promise<void> — Retry with a caller persisted action nonce.\n- `ConversationTurn.session`: session(): AgentSession — Session that handled this turn.\n- `ConversationTurn.source`: source(): Message — Originating message.\n- `ConversationTurn.toJSON`: toJSON(): { channelId: string; sourceMessageId: string; } — Serialize scoped identity.\n\n### AgentSessionNamespace (`macro.agentSessions`)\nEntry point for coding-agent sessions.\n- `AgentSessionNamespace.autoArchivePreferences`: autoArchivePreferences(): Promise<AutoArchivePreferencesBody> — Which triggers archive the caller's sessions by default; each is off unless chosen.\n- `AgentSessionNamespace.byId`: byId(id): AgentSession — A handle to an agent session by id.\n- `AgentSessionNamespace.chooseMode`: chooseMode(prompt): Promise<AgentMode> — Whether prompt needs a chat agent ('chat') or a coding agent ('code'), as the app's Auto mode decides before starting a session.\n- `AgentSessionNamespace.codingPreferences`: codingPreferences(): Promise<CodingPreferencesBody> — What the caller's new coding sessions are told to do beyond their assignment.\n- `AgentSessionNamespace.createManaged`: createManaged(opts?): Promise<AgentSession> — Create a managed session as agent when one is named, otherwise the deployment's default coding persona.\n- `AgentSessionNamespace.defaultSandboxSize`: defaultSandboxSize(): Promise<SandboxSize> — The caller's default sandbox size for new @coder sessions.\n- `AgentSessionNamespace.forPullRequest`: forPullRequest(url): Promise<AgentSession[]> — The sessions linked to the GitHub pull request at url that the caller can view.\n- `AgentSessionNamespace.repositories`: repositories(): Promise<SelectableRepository[]> — The GitHub repositories the caller can hand a managed session, with the branch each one's sessions start on by default.\n- `AgentSessionNamespace.repositoryBranches`: repositoryBranches(repoUrl): Promise<string[]> — Branch names on one repository the caller can start a managed session from.\n- `AgentSessionNamespace.setAutoArchivePreferences`: setAutoArchivePreferences(preferences): Promise<AutoArchivePreferencesBody> — Replace which triggers archive the caller's sessions by default.\n- `AgentSessionNamespace.setCodingPreferences`: setCodingPreferences(preferences): Promise<CodingPreferencesBody> — Replace the caller's coding preferences.\n- `AgentSessionNamespace.setDefaultSandboxSize`: setDefaultSandboxSize(size): Promise<SandboxSize> — Set the caller's default sandbox size for the next @coder mention.\n\n### QueuedAction\nOne action waiting in an agent session's server-side queue: a prompt or a compact accepted while a turn was running, dispatching when that turn ends.\n- `QueuedAction.edit`: edit(prompt): Promise<QueuedAction> — Replace this queued prompt's text before it dispatches.\n- `QueuedAction.remove`: remove(): Promise<void> — Remove this action from the queue before it dispatches.\n- `QueuedAction.steer`: steer(): Promise<void> — Move this action to the front and interrupt the current turn to run it next.\n- `QueuedAction.from`: static from(client, sessionId, dto): QueuedAction — Wrap a queue entry already in hand (e.g.\n\n### ReviewItem\nAn item handle scopes edits and decisions to its persisted review.\n- `ReviewItem.dismiss`: dismiss(): Promise<void> — Promise<void>\n- `ReviewItem.edit`: edit(draft): Promise<void> — Replace this pending draft; kind must match the review's.\n- `ReviewItem.submit`: submit(): Promise<void> — Promise<void>\n\n### SessionReview\nA persistent review remains actionable after the code execution ends.\nExtends `MacroEntity`.\nFields: id, kind, title\n- `SessionReview.dismissAll`: dismissAll(): Promise<void> — Promise<void>\n- `SessionReview.items`: items(): Promise<ReviewItem[]> — Promise<ReviewItem[]>\n- `SessionReview.reference`: reference(): Promise<{ id: string; kind: \"calendar\" | \"email\" | \"import\"; }> — Compact reference for main()'s returned reviews array.\n- `SessionReview.refresh`: refresh(): Promise<SessionReview> — Promise<SessionReview>\n- `SessionReview.session`: session(): AgentSession — AgentSession\n- `SessionReview.submitAll`: submitAll(): Promise<void> — Submit the saved pending drafts.\n- `SessionReview.byId`: static byId(client, session, id): SessionReview — SessionReview\n- `SessionReview.create`: static create(client, execution, input): Promise<SessionReview> — Promise<SessionReview>\n- `SessionReview.createForSession`: static createForSession(client, session, input, execution?): Promise<SessionReview> — Present a review in a session without requiring a code execution.\n- `SessionReview.fromRecord`: static fromRecord(client, session, record): SessionReview — SessionReview\n- `SessionReview.list`: static list(client, execution): Promise<SessionReview[]> — Promise<SessionReview[]>\n\n### ToolApproval\nA permission request scoped to its originating agent session.\nFields: id, session\n- `ToolApproval.answer`: answer(answer): Promise<AnswerToolApprovalResponse> — Answer the approval using the generated discriminated answer contract.\n- `ToolApproval.toJSON`: toJSON(): { id: string; sessionId: string; } — Serialize scoped identity only.\n- `ToolApproval.byId`: static byId(client, session, id): ToolApproval — Construct a scoped approval handle.\n\nFunctions: `presentView`\n\nTypes: `AutoArchiveOverrides`, `CreateManagedSessionOptions`, `FoldedAgentSessionLog`, `SelectableRepository`, `SessionAutoArchive`, `SessionPullRequest`, `CodeResult`, `JsonValue`, `CreateReviewOptions`, `ReviewCalendarDraft`, `ReviewDraft`, `ReviewEmailDraft`, `SessionView`\n"},{"name": "agents",@@ -28,7 +28,7 @@{"name": "initiatives","description": "Group tasks and members into initiatives.",- "index": "## initiatives\nGroup tasks and members into initiatives.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### Initiative\nA group of tasks and members working toward an outcome.\nExtends `MacroEntity`.\nFields: access, accessLevel, id, members, name, owner, sharePermissions, tasks\n- `Initiative.delete`: delete(): Promise<void> — Delete this initiative.\n- `Initiative.update`: update(options): Promise<void> — Update the name, membership or sharing configuration.\n- `Initiative.byId`: static byId(client, id): Initiative — Construct a lazy initiative handle.\n- `Initiative.from`: static from(client, record): Initiative — Seed from an initiative detail response.\n\n### InitiativeNamespace (`macro.initiatives`)\nInitiatives in the caller's workspace; find one by name with one summaries() call, not name() on each listed handle (one request each).\n- `InitiativeNamespace.byId`: byId(id): Initiative — Construct a lazy initiative handle.\n- `InitiativeNamespace.create`: create(options): Promise<Initiative> — Create an initiative.\n- `InitiativeNamespace.list`: list(): Promise<Initiative[]> — List accessible initiatives as handles; use summaries() for their names.\n- `InitiativeNamespace.summaries`: summaries(): Promise<InitiativeSummary[]> — Every accessible initiative with its name, in one request.\n\nTypes: `InitiativeOptions`, `InitiativeSummary`\n"+ "index": "## initiatives\nGroup tasks and members into initiatives.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### Initiative\nA group of tasks and members working toward an outcome.\nExtends `MacroEntity`.\nFields: access, accessLevel, id, members, name, owner, sharePermissions, tasks\n- `Initiative.delete`: delete(): Promise<void> — Delete this initiative.\n- `Initiative.toJSON`: toJSON(): { detail?: InitiativeDetail; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n- `Initiative.update`: update(options): Promise<void> — Update the name, membership or sharing configuration.\n- `Initiative.webUrl`: webUrl(): string — The initiative's URL in the Macro web app; hand it to users as the link.\n- `Initiative.byId`: static byId(client, id): Initiative — Construct a lazy initiative handle.\n- `Initiative.from`: static from(client, record): Initiative — Seed from an initiative detail response.\n\n### InitiativeNamespace (`macro.initiatives`)\nInitiatives in the caller's workspace; find one by name with one summaries() call, not name() on each listed handle (one request each).\n- `InitiativeNamespace.byId`: byId(id): Initiative — Construct a lazy initiative handle.\n- `InitiativeNamespace.create`: create(options): Promise<Initiative> — Create an initiative.\n- `InitiativeNamespace.list`: list(): Promise<Initiative[]> — List accessible initiatives as handles; use summaries() for their names.\n- `InitiativeNamespace.summaries`: summaries(): Promise<InitiativeSummary[]> — Every accessible initiative with its name, in one request.\n\nTypes: `InitiativeOptions`, `InitiativeSummary`\n"},{"name": "meetings",@@ -38,7 +38,7 @@{"name": "routines","description": "Create scheduled and event-triggered agent routines and inspect executions.",- "index": "## routines\nCreate scheduled and event-triggered agent routines and inspect executions.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### RoutineNamespace (`macro.routines`)\nScheduled and event-triggered routines.\n- `RoutineNamespace.byId`: byId(id): Routine — Construct a lazy routine handle.\n- `RoutineNamespace.create`: create(options): Promise<Routine> — Create an agent routine.\n- `RoutineNamespace.list`: list(options?): Promise<Routine[]> — List routines, optionally including event triggers.\n\n### Routine\nA scheduled or event-triggered agent task.\nExtends `MacroEntity`.\nFields: enabled, id, name, nextRunAt, owner, revision, runVisibility, sourceTemplate, trigger\n- `Routine.activateTemplate`: activateTemplate(options): Promise<Routine> — Create the caller's own routine from this routine's shared template, with its references already filled in for them.\n- `Routine.delete`: delete(): Promise<void> — Delete the routine.\n- `Routine.execute`: execute(): Promise<AgentSession | Chat | undefined> — Start an execution immediately and return its transcript handle if available.\n- `Routine.history`: history(): Promise<RoutineExecution[]> — Completed executions, with their routine scoped identity.\n- `Routine.setEnabled`: setEnabled(enabled): Promise<void> — Enable or disable triggering.\n- `Routine.shareAsTemplate`: shareAsTemplate(options): Promise<RoutineTemplate> — Share this routine as a template, or update its shared snapshot.\n- `Routine.stopSharingTemplate`: stopSharingTemplate(): Promise<void> — Stop sharing this routine.\n- `Routine.template`: template(): Promise<RoutineTemplate | undefined> — This routine's shared template, or undefined when it isn't shared.\n- `Routine.update`: update(options): Promise<void> — Replace the routine's task and trigger configuration.\n- `Routine.byId`: static byId(client, id): Routine — Construct a lazy routine handle.\n- `Routine.from`: static from(client, record): Routine — Seed a handle from a server record.\n\n### RoutineExecution\nA completed routine execution, as recorded by the service.\nFields: record, routine\n- `RoutineExecution.toJSON`: toJSON(): { action_id: string; created_at: string; end_time: string; id?: string | null; is_success: boolean; resource_id?: string | null; result: {[key: string]: unknown; }; routine: string; start_time: string; } — Serialize without the authenticated client.\n\n### RoutineTemplate\nA routine shared as a template, which people activate as their own routine.\nFields: author, record, routine\n- `RoutineTemplate.activate`: activate(options): Promise<Routine> — Create the caller's own routine from this template, with its references already filled in for them.\n- `RoutineTemplate.toJSON`: toJSON(): scheduled-action.RoutineTemplate — Serialize without the authenticated client.\n\nFunctions: `routineBody`\n\nTypes: `RoutineOptions`, `RoutineEventFilter`, `RoutineTriggerOptions`, `SingleRoutineTrigger`\n"+ "index": "## routines\nCreate scheduled and event-triggered agent routines and inspect executions.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### RoutineNamespace (`macro.routines`)\nScheduled and event-triggered routines.\n- `RoutineNamespace.byId`: byId(id): Routine — Construct a lazy routine handle.\n- `RoutineNamespace.create`: create(options): Promise<Routine> — Create an agent routine.\n- `RoutineNamespace.list`: list(options?): Promise<Routine[]> — List routines, optionally including event triggers.\n\n### Routine\nA scheduled or event-triggered agent task.\nExtends `MacroEntity`.\nFields: enabled, id, name, nextRunAt, owner, revision, runVisibility, sourceTemplate, trigger\n- `Routine.activateTemplate`: activateTemplate(options): Promise<Routine> — Create the caller's own routine from this routine's shared template, with its references already filled in for them.\n- `Routine.delete`: delete(): Promise<void> — Delete the routine.\n- `Routine.execute`: execute(): Promise<AgentSession | Chat | undefined> — Start an execution immediately and return its transcript handle if available.\n- `Routine.history`: history(): Promise<RoutineExecution[]> — Completed executions, with their routine scoped identity.\n- `Routine.setEnabled`: setEnabled(enabled): Promise<void> — Enable or disable triggering.\n- `Routine.shareAsTemplate`: shareAsTemplate(options): Promise<RoutineTemplate> — Share this routine as a template, or update its shared snapshot.\n- `Routine.stopSharingTemplate`: stopSharingTemplate(): Promise<void> — Stop sharing this routine.\n- `Routine.template`: template(): Promise<RoutineTemplate | undefined> — This routine's shared template, or undefined when it isn't shared.\n- `Routine.toJSON`: toJSON(): { detail?: ScheduledActionResponse; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n- `Routine.update`: update(options): Promise<void> — Replace the routine's task and trigger configuration.\n- `Routine.webUrl`: webUrl(): string — The routine's URL in the Macro web app; hand it to users as the link.\n- `Routine.byId`: static byId(client, id): Routine — Construct a lazy routine handle.\n- `Routine.from`: static from(client, record): Routine — Seed a handle from a server record.\n\n### RoutineExecution\nA completed routine execution, as recorded by the service.\nFields: record, routine\n- `RoutineExecution.toJSON`: toJSON(): { action_id: string; created_at: string; end_time: string; id?: string | null; is_success: boolean; resource_id?: string | null; result: {[key: string]: unknown; }; routine: string; start_time: string; } — Serialize without the authenticated client.\n\n### RoutineTemplate\nA routine shared as a template, which people activate as their own routine.\nFields: author, record, routine\n- `RoutineTemplate.activate`: activate(options): Promise<Routine> — Create the caller's own routine from this template, with its references already filled in for them.\n- `RoutineTemplate.toJSON`: toJSON(): scheduled-action.RoutineTemplate — Serialize without the authenticated client.\n\nFunctions: `routineBody`\n\nTypes: `RoutineOptions`, `RoutineEventFilter`, `RoutineTriggerOptions`, `SingleRoutineTrigger`\n"},{"name": "unfurls",@@ -63,12 +63,12 @@{"name": "calls","description": "Read and edit call records, transcripts and meeting links.",- "index": "## calls\nRead and edit call records, transcripts and meeting links.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### CallRecord\nA Macro call record (an archived or still active call).\nExtends `FavoritableEntity`.\nFields: access, channel, channelName, creator, durationMs, endedAt, entityType, guests, id, isActive, name, participants, recordingPreviewUrl, recordingStartedAt, recordingUrl, roomName, shareWithTeam, startedAt, status, summary, teamShareAccessLevel, transcript, search\n- `CallRecord.delete`: delete(): Promise<void> — Delete the call record.\n- `CallRecord.editTranscript`: editTranscript(assignments): Promise<void> — Update custom speaker assignments in the transcript.\n- `CallRecord.meeting`: meeting(): Promise<Meeting> — Get or create a shareable meeting for this call.\n- `CallRecord.message`: message(id): CallMessage — A message in this call's persistent chat.\n- `CallRecord.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `CallRecord.rename`: rename(name): Promise<void> — Rename the call or clear the custom name.\n- `CallRecord.setTeamShare`: setTeamShare(shared): Promise<void> — Share the call with the creator's team (view access), or unshare it.\n- `CallRecord.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: CallMessage; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `CallRecord.toggleTeamShare`: toggleTeamShare(): Promise<boolean> — Toggle the server's share-with-team setting and return its new value.\n- `CallRecord.byId`: static byId(client, id): CallRecord — A handle to a call record by id.\n\n### CallMessage\nA message in a call's single persistent chat thread.\nExtends `MacroEntity`.\nFields: callId, content, createdAt, id, updatedAt\n- `CallMessage.author`: author(): Promise<User> — The user who sent this message.\n- `CallMessage.call`: call(): CallRecord — The call whose chat contains this message.\n- `CallMessage.delete`: delete(): Promise<void> — Delete this message, preserving the rest of the call's chat.\n- `CallMessage.edit`: edit(body): Promise<CallMessage> — Replace this message's body.\n- `CallMessage.reply`: reply(body): Promise<CallMessage> — Reply in the call's canonical thread, including when this is a reply.\n- `CallMessage.byId`: static byId(client, callId, id): CallMessage — A handle to a message by id.\n- `CallMessage.from`: static from(client, callId, record): CallMessage — Build a message from its record without another fetch.\n\n### CallRecordNamespace (`macro.calls`)\n- `CallRecordNamespace.byId`: byId(id): CallRecord — CallRecord\n- `CallRecordNamespace.search`: search(query, opts?): AsyncGenerator<CallRecord> — AsyncGenerator<CallRecord>\n"+ "index": "## calls\nRead and edit call records, transcripts and meeting links.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### CallRecord\nA Macro call record (an archived or still active call).\nExtends `FavoritableEntity`.\nFields: access, channel, channelName, creator, durationMs, endedAt, entityType, guests, id, isActive, name, participants, recordingPreviewUrl, recordingStartedAt, recordingUrl, roomName, shareWithTeam, startedAt, status, summary, teamShareAccessLevel, transcript, search\n- `CallRecord.delete`: delete(): Promise<void> — Delete the call record.\n- `CallRecord.editTranscript`: editTranscript(assignments): Promise<void> — Update custom speaker assignments in the transcript.\n- `CallRecord.meeting`: meeting(): Promise<Meeting> — Get or create a shareable meeting for this call.\n- `CallRecord.message`: message(id): CallMessage — A message in this call's persistent chat.\n- `CallRecord.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `CallRecord.rename`: rename(name): Promise<void> — Rename the call or clear the custom name.\n- `CallRecord.setTeamShare`: setTeamShare(shared): Promise<void> — Share the call with the creator's team (view access), or unshare it.\n- `CallRecord.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: CallMessage; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `CallRecord.toggleTeamShare`: toggleTeamShare(): Promise<boolean> — Toggle the server's share-with-team setting and return its new value.\n- `CallRecord.toJSON`: toJSON(): { detail?: storage.CallRecord; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n- `CallRecord.webUrl`: webUrl(): string — The call's URL in the Macro web app; hand it to users as the link.\n- `CallRecord.byId`: static byId(client, id): CallRecord — A handle to a call record by id.\n\n### CallMessage\nA message in a call's single persistent chat thread.\nExtends `MacroEntity`.\nFields: callId, content, createdAt, id, updatedAt\n- `CallMessage.author`: author(): Promise<User> — The user who sent this message.\n- `CallMessage.call`: call(): CallRecord — The call whose chat contains this message.\n- `CallMessage.delete`: delete(): Promise<void> — Delete this message, preserving the rest of the call's chat.\n- `CallMessage.edit`: edit(body): Promise<CallMessage> — Replace this message's body.\n- `CallMessage.reply`: reply(body): Promise<CallMessage> — Reply in the call's canonical thread, including when this is a reply.\n- `CallMessage.byId`: static byId(client, callId, id): CallMessage — A handle to a message by id.\n- `CallMessage.from`: static from(client, callId, record): CallMessage — Build a message from its record without another fetch.\n\n### CallRecordNamespace (`macro.calls`)\n- `CallRecordNamespace.byId`: byId(id): CallRecord — CallRecord\n- `CallRecordNamespace.search`: search(query, opts?): AsyncGenerator<CallRecord> — AsyncGenerator<CallRecord>\n"},{"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(): AsyncGenerator<Channel> — Every channel the authenticated user is a member of, auto-paginated.\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 (case-insensitive substring match over every channel the user is a member of) 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"+ "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.toJSON`: toJSON(): { detail?: ApiChannelDetail; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\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(): AsyncGenerator<Channel> — Every channel the authenticated user is a member of, auto-paginated.\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 (case-insensitive substring match over every channel the user is a member of) 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",@@ -78,17 +78,17 @@{"name": "databases","description": "Read and edit database schemas, rows, and cells.",- "index": "## databases\nRead and edit database schemas, rows, and cells.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### DatabaseColumn\nOne column of a DatabaseTable: the placement of a property definition on the table.\nFields: id, table\n- `DatabaseColumn.addOptions`: addOptions(labels): Promise<DatabaseColumn> — Add select options to the column.\n- `DatabaseColumn.casts`: casts(): Promise<ColumnCast[]> — What changing this column to each type would do to its values: safe, checked (with how many would not convert, and a few of them), or never (with why).\n- `DatabaseColumn.changeType`: changeType(options): Promise<OpResultOf<\"column\", \"type_changed\">> — Change this column's type.\n- `DatabaseColumn.config`: config(): Promise<ColumnConfig | undefined> — Column-kind configuration (a link), or undefined for a plain value column.\n- `DatabaseColumn.convertIntoNewColumn`: convertIntoNewColumn(options): Promise<DatabaseColumn> — Add a column of another type right after this one, filled with the values that convert, leaving this one as it is.\n- `DatabaseColumn.dataType`: dataType(): Promise<storage.DataType> — The value type the column holds.\n- `DatabaseColumn.definition`: definition(): Promise<PropertyDefinitionWithOptions> — The bound property definition together with its select options — the source of the column's name, type, and allowed values.\n- `DatabaseColumn.delete`: delete(): Promise<void> — Delete this placement and its cells at the table version last read.\n- `DatabaseColumn.detail`: detail(): Promise<ColumnDetail> — The column's record as the API returns it: the placement and the bound property definition.\n- `DatabaseColumn.inferType`: inferType(options): Promise<DatabaseColumn> — Settle the type of an empty column created with inferType enabled.\n- `DatabaseColumn.isMultiSelect`: isMultiSelect(): Promise<boolean> — Whether the column holds multiple values.\n- `DatabaseColumn.name`: name(): Promise<string> — The placement's display name, falling back to its property definition.\n- `DatabaseColumn.position`: position(): Promise<string> — The column's fractional index within the table's column order.\n- `DatabaseColumn.rename`: rename(name): Promise<DatabaseColumn> — Rename this placement, only if its last-read name is still current, without changing its shared property definition.\n- `DatabaseColumn.toJSON`: toJSON(): { id: string; tableId: string; } — { id: string; tableId: string; }\n- `DatabaseColumn.byId`: static byId(table, id): DatabaseColumn — A handle to a column by id, within a table.\n\n### Database\nA Macro database: a named collection of tables, owned and shared as one entity.\nExtends `MacroEntity`.\nFields: access, createdAt, grant, id, name, owner, tables, trashedAt\n- `Database.addColumn`: addColumn(table, options): Promise<DatabaseColumn> — Add a column to one of the database's tables, under an id minted here, either creating a property definition for it or binding an existing one.\n- `Database.addColumnOptions`: addColumnOptions(column, labels): Promise<OpResultOf<\"column\", \"options_added\">> — Add select options to one of the database's columns, each under an id minted here.\n- `Database.applyOps`: applyOps(ops, options?): Promise<OpResult[]> — Apply ops to the database in one transaction: create, rename, reorder, or delete tables and columns; change a column's type; add, edit, or delete select opti...\n- `Database.changeColumnType`: changeColumnType(column, options): Promise<OpResultOf<\"column\", \"type_changed\">> — Change a column's type at the table version last read.\n- `Database.columnCasts`: columnCasts(column): Promise<ColumnCast[]> — What changing a column to each type would do to its values.\n- `Database.columnConversion`: columnConversion(column, to): Promise<ColumnConversion> — What a column's values become under another type: the values that convert, the option labels a new select or tag column of that type needs, and how many valu...\n- `Database.convertColumnIntoNewColumn`: convertColumnIntoNewColumn(column, options): Promise<DatabaseColumn> — Add a column of another type right after this one, filled with the values that convert, in one batch at the table version the conversion was read at.\n- `Database.createTable`: createTable(options): Promise<DatabaseTable> — Create a table in the database, under an id minted here.\n- `Database.createWebhook`: createWebhook(table): Promise<{ token: string; webhook: DatabaseWebhook; }> — Create a webhook that inserts rows into table, writing with the caller's access.\n- `Database.deleteColumn`: deleteColumn(column): Promise<number> — Remove a column and its cells at the table version last read.\n- `Database.deleteTable`: deleteTable(table): Promise<void> — Delete one of the database's tables with its columns, rows, and views.\n- `Database.deleteWebhook`: deleteWebhook(webhook): Promise<void> — Delete one of the database's webhooks; its URL stops working.\n- `Database.duplicate`: duplicate(options?): Promise<Database> — Copy the database into a new one the caller owns, with its tables, columns, views and rows.\n- `Database.importTable`: importTable(request): Promise<DatabaseTable> — Import text rows atomically.\n- `Database.inferColumnType`: inferColumnType(column, options): Promise<InferColumnTypeOutcome> — Adopt a first-value type only while the owned column is empty and inferable.\n- `Database.query`: query(sql, options?): Promise<DatabaseQueryResult> — Run one SQL statement with this database as the default name scope.\n- `Database.renameColumn`: renameColumn(column, name): Promise<number> — Rename this column placement, only if its last-read name is still current, without changing its shared property definition.\n- `Database.renameTable`: renameTable(table, name): Promise<number> — Rename a table only if its last-read name is still current.\n- `Database.reorderColumns`: reorderColumns(table, columns): Promise<number> — Persist a complete column order at the table version last read.\n- `Database.reorderTables`: reorderTables(tables): Promise<DatabaseTable[]> — Persist a new tab order.\n- `Database.rowHistory`: rowHistory(row): Promise<RowHistoryEntry[]> — A row's history: every committed change that touched it, newest first.\n- `Database.schema`: schema(): Promise<DatabaseDetail> — The full schema: the database record, the caller's access, and every table with its columns and views.\n- `Database.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Read direct recipients.\n- `Database.table`: table(name): Promise<DatabaseTable | undefined> — The table with the given display name, or undefined if there is none.\n- `Database.updateSharePermissions`: updateSharePermissions(request): Promise<storage.SharePermissionV2> — Add, replace, or remove recipient grants without transferring ownership.\n- `Database.viewPositions`: viewPositions(view): Promise<CardPosition[]> — Where a board view's cards sit: each placed card's lane and key.\n- `Database.webhooks`: webhooks(): Promise<DatabaseWebhook[]> — The database's webhooks, oldest first.\n- `Database.byId`: static byId(client, id): Database — A handle to a database by id.\n- `Database.create`: static create(client, options): Promise<Database> — Create a database owned by the caller.\n- `Database.list`: static list(client): Promise<Database[]> — The databases the caller can see, each with the caller's access level.\n\n### MacroOpRefusedError\nA batch of ops was refused (HTTP 400): nothing in it was written.\nExtends `MacroApiError`.\nFields: column, data, op, row, status, taken\n\n### DatabaseNamespace (`macro.databases`)\nMacro databases: named collections of tables, owned and shared as one entity.\n- `DatabaseNamespace.byId`: byId(id): Database — A handle to a database by id.\n- `DatabaseNamespace.create`: create(options): Promise<Database> — Create a database owned by the caller.\n- `DatabaseNamespace.list`: list(): Promise<Database[]> — The databases the caller can see.\n- `DatabaseNamespace.query`: query(sql, options?): Promise<DatabaseQueryResult> — Run one SQL statement over the caller's visible databases.\n\n### DatabaseRow\nOne row of a DatabaseTable.\nFields: id, table\n- `DatabaseRow.history`: history(): Promise<RowHistoryEntry[]> — Every committed change that touched the row, newest first: who made it, when, how, and the values of the columns it touched before and after.\n- `DatabaseRow.toJSON`: toJSON(): { id: string; tableId: string; } — { id: string; tableId: string; }\n- `DatabaseRow.byId`: static byId(table, id): DatabaseRow — A handle to a row by id, within a table.\n\n### DatabaseTable\nOne table (tab) of a Database.\nFields: database, id\n- `DatabaseTable.addColumn`: addColumn(options): Promise<DatabaseColumn> — Add a column to this table.\n- `DatabaseTable.columns`: columns(): Promise<DatabaseColumn[]> — The table's columns, in display order.\n- `DatabaseTable.createWebhook`: createWebhook(): Promise<{ token: string; webhook: DatabaseWebhook; }> — Create a webhook that inserts rows here.\n- `DatabaseTable.delete`: delete(): Promise<void> — Delete this table.\n- `DatabaseTable.detail`: detail(): Promise<TableDetail> — The table's record as the API returns it: the table, its columns, and its views.\n- `DatabaseTable.name`: name(): Promise<string> — The table's display name.\n- `DatabaseTable.position`: position(): Promise<string> — The table's fractional index within the database's tab order.\n- `DatabaseTable.rename`: rename(name): Promise<DatabaseTable> — Rename only if the last-read display name is still current.\n- `DatabaseTable.reorderColumns`: reorderColumns(columns): Promise<DatabaseTable> — Persist a new column order.\n- `DatabaseTable.row`: row(id): DatabaseRow — A handle to one of the table's rows, by the id an insert answered.\n- `DatabaseTable.toJSON`: toJSON(): { databaseId: string; id: string; } — { databaseId: string; id: string; }\n- `DatabaseTable.version`: version(): Promise<number> — The table's current version, bumped by every committed change to its schema or rows.\n- `DatabaseTable.views`: views(): Promise<DatabaseView[]> — The table's views, in their order.\n- `DatabaseTable.byId`: static byId(database, id): DatabaseTable — A handle to a table by id, within a database.\n\n### DatabaseView\nOne view of a DatabaseTable: which of its rows to show, in what order, drawn as a table or a board.\nFields: id, table\n- `DatabaseView.detail`: detail(): Promise<storage.DatabaseView> — The view's record as the API returns it.\n- `DatabaseView.layout`: layout(): Promise<ViewLayout> — How the view draws its rows: a table, or a board grouped by a column.\n- `DatabaseView.name`: name(): Promise<string> — The view's name, unique among its table's views ignoring case.\n- `DatabaseView.position`: position(): Promise<string> — The view's fractional index within its table's views.\n- `DatabaseView.positions`: positions(): Promise<CardPosition[]> — Where a board's cards sit: each placed card's lane and its key there.\n- `DatabaseView.query`: query(): Promise<ViewQuery> — Which rows the view shows, and in what order.\n- `DatabaseView.toJSON`: toJSON(): { id: string; tableId: string; } — { id: string; tableId: string; }\n- `DatabaseView.byId`: static byId(table, id): DatabaseView — A handle to a view by id, within a table.\n\n### DatabaseWebhook\nA webhook of a DatabaseTable: a secret URL that anyone holding it can POST JSON to, each object becoming a row, written with the access of the user who creat...\nFields: createdBy, id, table\n- `DatabaseWebhook.delete`: delete(): Promise<void> — Delete the webhook; its URL stops working.\n- `DatabaseWebhook.toJSON`: toJSON(): { id: string; tableId: string; tokenPrefix: string; } — { id: string; tableId: string; tokenPrefix: string; }\n- `DatabaseWebhook.fromRecord`: static fromRecord(table, createdBy, record): DatabaseWebhook — A handle from the record the API answered.\n\nTypes: `AddColumnOptions`, `ApplyOpsOptions`, `ChangeColumnTypeOptions`, `ColumnType`, `ConvertIntoNewColumnOptions`, `InferColumnTypeOptions`, `OpResultOf`, `DatabaseQueryOptions`, `DatabaseQueryResult`, `QueryResultSet`, `QueryTableVersion`, `QueryColumn`, `QueryStatement`\n"+ "index": "## databases\nRead and edit database schemas, rows, and cells.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### DatabaseColumn\nOne column of a DatabaseTable: the placement of a property definition on the table.\nFields: id, table\n- `DatabaseColumn.addOptions`: addOptions(labels): Promise<DatabaseColumn> — Add select options to the column.\n- `DatabaseColumn.casts`: casts(): Promise<ColumnCast[]> — What changing this column to each type would do to its values: safe, checked (with how many would not convert, and a few of them), or never (with why).\n- `DatabaseColumn.changeType`: changeType(options): Promise<OpResultOf<\"column\", \"type_changed\">> — Change this column's type.\n- `DatabaseColumn.config`: config(): Promise<ColumnConfig | undefined> — Column-kind configuration (a link), or undefined for a plain value column.\n- `DatabaseColumn.convertIntoNewColumn`: convertIntoNewColumn(options): Promise<DatabaseColumn> — Add a column of another type right after this one, filled with the values that convert, leaving this one as it is.\n- `DatabaseColumn.dataType`: dataType(): Promise<storage.DataType> — The value type the column holds.\n- `DatabaseColumn.definition`: definition(): Promise<PropertyDefinitionWithOptions> — The bound property definition together with its select options — the source of the column's name, type, and allowed values.\n- `DatabaseColumn.delete`: delete(): Promise<void> — Delete this placement and its cells at the table version last read.\n- `DatabaseColumn.detail`: detail(): Promise<ColumnDetail> — The column's record as the API returns it: the placement and the bound property definition.\n- `DatabaseColumn.inferType`: inferType(options): Promise<DatabaseColumn> — Settle the type of an empty column created with inferType enabled.\n- `DatabaseColumn.isMultiSelect`: isMultiSelect(): Promise<boolean> — Whether the column holds multiple values.\n- `DatabaseColumn.name`: name(): Promise<string> — The placement's display name, falling back to its property definition.\n- `DatabaseColumn.position`: position(): Promise<string> — The column's fractional index within the table's column order.\n- `DatabaseColumn.rename`: rename(name): Promise<DatabaseColumn> — Rename this placement, only if its last-read name is still current, without changing its shared property definition.\n- `DatabaseColumn.toJSON`: toJSON(): { id: string; tableId: string; } — { id: string; tableId: string; }\n- `DatabaseColumn.byId`: static byId(table, id): DatabaseColumn — A handle to a column by id, within a table.\n\n### Database\nA Macro database: a named collection of tables, owned and shared as one entity.\nExtends `MacroEntity`.\nFields: access, createdAt, grant, id, name, owner, tables, trashedAt\n- `Database.addColumn`: addColumn(table, options): Promise<DatabaseColumn> — Add a column to one of the database's tables, under an id minted here, either creating a property definition for it or binding an existing one.\n- `Database.addColumnOptions`: addColumnOptions(column, labels): Promise<OpResultOf<\"column\", \"options_added\">> — Add select options to one of the database's columns, each under an id minted here.\n- `Database.applyOps`: applyOps(ops, options?): Promise<OpResult[]> — Apply ops to the database in one transaction: create, rename, reorder, or delete tables and columns; change a column's type; add, edit, or delete select opti...\n- `Database.changeColumnType`: changeColumnType(column, options): Promise<OpResultOf<\"column\", \"type_changed\">> — Change a column's type at the table version last read.\n- `Database.columnCasts`: columnCasts(column): Promise<ColumnCast[]> — What changing a column to each type would do to its values.\n- `Database.columnConversion`: columnConversion(column, to): Promise<ColumnConversion> — What a column's values become under another type: the values that convert, the option labels a new select or tag column of that type needs, and how many valu...\n- `Database.convertColumnIntoNewColumn`: convertColumnIntoNewColumn(column, options): Promise<DatabaseColumn> — Add a column of another type right after this one, filled with the values that convert, in one batch at the table version the conversion was read at.\n- `Database.createTable`: createTable(options): Promise<DatabaseTable> — Create a table in the database, under an id minted here.\n- `Database.createWebhook`: createWebhook(table): Promise<{ token: string; webhook: DatabaseWebhook; }> — Create a webhook that inserts rows into table, writing with the caller's access.\n- `Database.deleteColumn`: deleteColumn(column): Promise<number> — Remove a column and its cells at the table version last read.\n- `Database.deleteTable`: deleteTable(table): Promise<void> — Delete one of the database's tables with its columns, rows, and views.\n- `Database.deleteWebhook`: deleteWebhook(webhook): Promise<void> — Delete one of the database's webhooks; its URL stops working.\n- `Database.duplicate`: duplicate(options?): Promise<Database> — Copy the database into a new one the caller owns, with its tables, columns, views and rows.\n- `Database.importTable`: importTable(request): Promise<DatabaseTable> — Import text rows atomically.\n- `Database.inferColumnType`: inferColumnType(column, options): Promise<InferColumnTypeOutcome> — Adopt a first-value type only while the owned column is empty and inferable.\n- `Database.query`: query(sql, options?): Promise<DatabaseQueryResult> — Run one SQL statement with this database as the default name scope.\n- `Database.renameColumn`: renameColumn(column, name): Promise<number> — Rename this column placement, only if its last-read name is still current, without changing its shared property definition.\n- `Database.renameTable`: renameTable(table, name): Promise<number> — Rename a table only if its last-read name is still current.\n- `Database.reorderColumns`: reorderColumns(table, columns): Promise<number> — Persist a complete column order at the table version last read.\n- `Database.reorderTables`: reorderTables(tables): Promise<DatabaseTable[]> — Persist a new tab order.\n- `Database.rowHistory`: rowHistory(row): Promise<RowHistoryEntry[]> — A row's history: every committed change that touched it, newest first.\n- `Database.schema`: schema(): Promise<DatabaseDetail> — The full schema: the database record, the caller's access, and every table with its columns and views.\n- `Database.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Read direct recipients.\n- `Database.table`: table(name): Promise<DatabaseTable | undefined> — The table with the given display name, or undefined if there is none.\n- `Database.toJSON`: toJSON(): { detail?: DatabaseDetail; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n- `Database.updateSharePermissions`: updateSharePermissions(request): Promise<storage.SharePermissionV2> — Add, replace, or remove recipient grants without transferring ownership.\n- `Database.viewPositions`: viewPositions(view): Promise<CardPosition[]> — Where a board view's cards sit: each placed card's lane and key.\n- `Database.webhooks`: webhooks(): Promise<DatabaseWebhook[]> — The database's webhooks, oldest first.\n- `Database.webUrl`: webUrl(): string — The database's URL in the Macro web app; hand it to users as the link.\n- `Database.byId`: static byId(client, id): Database — A handle to a database by id.\n- `Database.create`: static create(client, options): Promise<Database> — Create a database owned by the caller.\n- `Database.list`: static list(client): Promise<Database[]> — The databases the caller can see, each with the caller's access level.\n\n### MacroOpRefusedError\nA batch of ops was refused (HTTP 400): nothing in it was written.\nExtends `MacroApiError`.\nFields: column, data, op, row, status, taken\n\n### DatabaseNamespace (`macro.databases`)\nMacro databases: named collections of tables, owned and shared as one entity.\n- `DatabaseNamespace.byId`: byId(id): Database — A handle to a database by id.\n- `DatabaseNamespace.create`: create(options): Promise<Database> — Create a database owned by the caller.\n- `DatabaseNamespace.list`: list(): Promise<Database[]> — The databases the caller can see.\n- `DatabaseNamespace.query`: query(sql, options?): Promise<DatabaseQueryResult> — Run one SQL statement over the caller's visible databases.\n\n### DatabaseRow\nOne row of a DatabaseTable.\nFields: id, table\n- `DatabaseRow.history`: history(): Promise<RowHistoryEntry[]> — Every committed change that touched the row, newest first: who made it, when, how, and the values of the columns it touched before and after.\n- `DatabaseRow.toJSON`: toJSON(): { id: string; tableId: string; } — { id: string; tableId: string; }\n- `DatabaseRow.byId`: static byId(table, id): DatabaseRow — A handle to a row by id, within a table.\n\n### DatabaseTable\nOne table (tab) of a Database.\nFields: database, id\n- `DatabaseTable.addColumn`: addColumn(options): Promise<DatabaseColumn> — Add a column to this table.\n- `DatabaseTable.columns`: columns(): Promise<DatabaseColumn[]> — The table's columns, in display order.\n- `DatabaseTable.createWebhook`: createWebhook(): Promise<{ token: string; webhook: DatabaseWebhook; }> — Create a webhook that inserts rows here.\n- `DatabaseTable.delete`: delete(): Promise<void> — Delete this table.\n- `DatabaseTable.detail`: detail(): Promise<TableDetail> — The table's record as the API returns it: the table, its columns, and its views.\n- `DatabaseTable.name`: name(): Promise<string> — The table's display name.\n- `DatabaseTable.position`: position(): Promise<string> — The table's fractional index within the database's tab order.\n- `DatabaseTable.rename`: rename(name): Promise<DatabaseTable> — Rename only if the last-read display name is still current.\n- `DatabaseTable.reorderColumns`: reorderColumns(columns): Promise<DatabaseTable> — Persist a new column order.\n- `DatabaseTable.row`: row(id): DatabaseRow — A handle to one of the table's rows, by the id an insert answered.\n- `DatabaseTable.toJSON`: toJSON(): { databaseId: string; id: string; } — { databaseId: string; id: string; }\n- `DatabaseTable.version`: version(): Promise<number> — The table's current version, bumped by every committed change to its schema or rows.\n- `DatabaseTable.views`: views(): Promise<DatabaseView[]> — The table's views, in their order.\n- `DatabaseTable.byId`: static byId(database, id): DatabaseTable — A handle to a table by id, within a database.\n\n### DatabaseView\nOne view of a DatabaseTable: which of its rows to show, in what order, drawn as a table or a board.\nFields: id, table\n- `DatabaseView.detail`: detail(): Promise<storage.DatabaseView> — The view's record as the API returns it.\n- `DatabaseView.layout`: layout(): Promise<ViewLayout> — How the view draws its rows: a table, or a board grouped by a column.\n- `DatabaseView.name`: name(): Promise<string> — The view's name, unique among its table's views ignoring case.\n- `DatabaseView.position`: position(): Promise<string> — The view's fractional index within its table's views.\n- `DatabaseView.positions`: positions(): Promise<CardPosition[]> — Where a board's cards sit: each placed card's lane and its key there.\n- `DatabaseView.query`: query(): Promise<ViewQuery> — Which rows the view shows, and in what order.\n- `DatabaseView.toJSON`: toJSON(): { id: string; tableId: string; } — { id: string; tableId: string; }\n- `DatabaseView.byId`: static byId(table, id): DatabaseView — A handle to a view by id, within a table.\n\n### DatabaseWebhook\nA webhook of a DatabaseTable: a secret URL that anyone holding it can POST JSON to, each object becoming a row, written with the access of the user who creat...\nFields: createdBy, id, table\n- `DatabaseWebhook.delete`: delete(): Promise<void> — Delete the webhook; its URL stops working.\n- `DatabaseWebhook.toJSON`: toJSON(): { id: string; tableId: string; tokenPrefix: string; } — { id: string; tableId: string; tokenPrefix: string; }\n- `DatabaseWebhook.fromRecord`: static fromRecord(table, createdBy, record): DatabaseWebhook — A handle from the record the API answered.\n\nTypes: `AddColumnOptions`, `ApplyOpsOptions`, `ChangeColumnTypeOptions`, `ColumnType`, `ConvertIntoNewColumnOptions`, `InferColumnTypeOptions`, `OpResultOf`, `DatabaseQueryOptions`, `DatabaseQueryResult`, `QueryResultSet`, `QueryTableVersion`, `QueryColumn`, `QueryStatement`\n"},{"name": "documents","description": "Search, read, create, and manage documents and tasks.",- "index": "## documents\nSearch, read, create, and manage documents and tasks.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### DocumentAnchor\nA PDF annotation scoped to its document.\nExtends `MacroEntity`.\nFields: document, id, kind, page\n- `DocumentAnchor.delete`: delete(): Promise<void> — Delete a standalone highlight annotation.\n- `DocumentAnchor.edit`: edit(options): Promise<void> — Edit a placeable comment's position and display settings.\n- `DocumentAnchor.toJSON`: toJSON(): { detail?: PdfAnchor; documentId: string; id: string; } — Serialize identity with its owning resource.\n- `DocumentAnchor.byId`: static byId(client, document, id): DocumentAnchor — Construct a document scoped annotation handle.\n- `DocumentAnchor.from`: static from(client, document, record): DocumentAnchor — Seed an annotation from a document annotation listing.\n\n### Comment\nA comment on a document: a document-parent message, addressed by its document and message UUID.\nExtends `MacroEntity`.\nFields: createdAt, documentId, id, text, updatedAt\n- `Comment.author`: author(): Promise<User> — The user who wrote this comment.\n- `Comment.delete`: delete(): Promise<void> — Delete this comment.\n- `Comment.document`: document(): Document — The document this comment is on.\n- `Comment.edit`: edit(body): Promise<Comment> — Replace the comment's text.\n- `Comment.reply`: reply(body): Promise<Comment> — Reply in this comment's thread.\n- `Comment.threadId`: threadId(): Promise<string> — The id of the thread this comment belongs to: its root, or itself for a root.\n- `Comment.byId`: static byId(client, documentId, id): Comment — A handle to a comment by id.\n- `Comment.from`: static from(client, documentId, record): Comment — Build a comment from a message record (pre-seeded, no fetch).\n\n### Document\nA Macro document.\nExtends `PropertiedEntity`.\nFields: access, branchedFrom, createdAt, deletedAt, entityType, fileType, id, name, owner, project, updatedAt, search\n- `Document.anchors`: anchors(): Promise<DocumentAnchor[]> — PDF annotations in this document.\n- `Document.branchName`: branchName(): Promise<string> — The git branch name derived for the document (task documents).\n- `Document.comment`: comment(body, opts?): Promise<Comment> — Add a comment.\n- `Document.comments`: comments(): Promise<CommentThread[]> — The document's live comment threads, each with its comments, newest thread first.\n- `Document.content`: content(): Promise<string> — Current Markdown for native documents, extracted text for PDF/Word, or raw file content for other formats.\n- `Document.copy`: copy(opts): Promise<Document> — Copy the document under a new name, optionally from a specific version.\n- `Document.createHighlight`: createHighlight(options): Promise<DocumentAnchor> — Create a standalone PDF highlight.\n- `Document.delete`: delete(opts?): Promise<void> — Delete the document.\n- `Document.githubPullRequests`: githubPullRequests(): Promise<storage.GithubPullRequest[]> — GitHub pull requests associated with the document.\n- `Document.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `Document.move`: move(project): Promise<void> — Move the document into a project (or out of one, with null).\n- `Document.permissionsToken`: permissionsToken(): Promise<string> — Mint a scoped permissions token.\n- `Document.prepareSave`: prepareSave(parts): Promise<PreSaveDocumentResponseData> — Prepare multipart content saving and return the service's upload instructions.\n- `Document.rename`: rename(name): Promise<void> — Rename the document.\n- `Document.restore`: restore(): Promise<void> — Restore a soft-deleted document.\n- `Document.save`: save(options): Promise<SaveDocumentResponseData> — Commit uploaded content.\n- `Document.setTeamShare`: setTeamShare(shared): Promise<void> — Share the document with the owner's team, or unshare it.\n- `Document.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Sharing configuration.\n- `Document.shortId`: shortId(): Promise<string> — The document's short id (used in compact links and branch names).\n- `Document.simpleSave`: simpleSave(): Promise<SaveDocumentResponseData> — Commit a simple document save.\n- `Document.teamShare`: teamShare(): Promise<DocumentTeamShareResponse> — Whether the document is shared with the owner's team, and which team.\n- `Document.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: Comment; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `Document.toMention`: toMention(): MentionPart — MentionPart\n- `Document.version`: version(version): DocumentVersion — A handle to an immutable version.\n- `Document.webUrl`: webUrl(): string — The document's URL in the Macro web app.\n- `Document.byId`: static byId(client, id): Document — A handle to a document by id.\n- `Document.create`: static create(client, opts): Promise<Document> — Create a markdown document.\n- `Document.createSkill`: static createSkill(client, opts): Promise<Document> — Create a skill: a markdown document containing instructions that AI reads and follows when the skill is referenced in an AI input.\n- `Document.createSnippet`: static createSnippet(client, opts): Promise<Document> — Create a snippet: a reusable markdown document that can be inserted into any markdown area.\n- `Document.recent`: static recent(client, opts?): AsyncGenerator<Document> — The user's recent documents, most recent first, auto-paginated.\n- `Document.recentlyDeleted`: static recentlyDeleted(client): Promise<Document[]> — The user's recently soft-deleted documents.\n\n### DocumentNamespace (`macro.documents`)\n- `DocumentNamespace.byId`: byId(id): Document — A handle to a document by id.\n- `DocumentNamespace.byTeamSlug`: byTeamSlug(slug): Promise<Document> — Resolve a team task reference such as ENG-42.\n- `DocumentNamespace.create`: create(opts): Promise<Document> — Create a markdown document.\n- `DocumentNamespace.createCanvas`: createCanvas(opts): Promise<Document> — Create a native Canvas with shared content ready for reading and editing.\n- `DocumentNamespace.createSkill`: createSkill(opts): Promise<Document> — Create a skill: markdown instructions that AI reads and follows.\n- `DocumentNamespace.createSnippet`: createSnippet(opts): Promise<Document> — Create a snippet: a reusable markdown document.\n- `DocumentNamespace.createUpload`: createUpload(options): Promise<{ content: DocumentContent; contentType: string; document: Document; uploadUrl: string | undefined; }> — Reserve a binary document and return upload instructions.\n- `DocumentNamespace.recent`: recent(opts?): AsyncGenerator<Document> — The user's recent documents, most recent first, auto-paginated.\n- `DocumentNamespace.recentlyDeleted`: recentlyDeleted(): Promise<Document[]> — The user's recently soft-deleted documents.\n- `DocumentNamespace.search`: search(query, opts?): AsyncGenerator<Document> — Search documents by name and content, most relevant first, auto-paginated.\n- `DocumentNamespace.systemSkills`: systemSkills(): Promise<SystemSkill[]> — The built-in system skills: static AI instructions with no document behind them.\n- `DocumentNamespace.validatePermissionsToken`: validatePermissionsToken(token): Promise<{ accessLevel: storage.AccessLevel; document: Document; expiresAt: number; issuer: string; user: User | undefined; }> — Validate a permissions token, returning its document and optional user handles.\n\n### SystemSkill\nA built-in system skill: static, code-defined AI instructions that surface to AI like skill documents but have no document behind them.\nFields: id, name\n- `SystemSkill.list`: static list(client): Promise<SystemSkill[]> — The built-in system skills, in display order.\n\n### DocumentVersion\nAn immutable document version, scoped to its document.\nFields: document, id\n- `DocumentVersion.read`: read(): Promise<GetDocumentResponseData> — Version metadata and the caller's access.\n- `DocumentVersion.toJSON`: toJSON(): { documentId: string; id: number; } — Serialize only scoped identity.\n- `DocumentVersion.byId`: static byId(client, document, id): DocumentVersion — Construct a version handle.\n\nTypes: `CommentThread`\n"+ "index": "## documents\nSearch, read, create, and manage documents and tasks.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### DocumentAnchor\nA PDF annotation scoped to its document.\nExtends `MacroEntity`.\nFields: document, id, kind, page\n- `DocumentAnchor.delete`: delete(): Promise<void> — Delete a standalone highlight annotation.\n- `DocumentAnchor.edit`: edit(options): Promise<void> — Edit a placeable comment's position and display settings.\n- `DocumentAnchor.toJSON`: toJSON(): { detail?: PdfAnchor; documentId: string; id: string; } — Serialize identity with its owning resource.\n- `DocumentAnchor.byId`: static byId(client, document, id): DocumentAnchor — Construct a document scoped annotation handle.\n- `DocumentAnchor.from`: static from(client, document, record): DocumentAnchor — Seed an annotation from a document annotation listing.\n\n### Comment\nA comment on a document: a document-parent message, addressed by its document and message UUID.\nExtends `MacroEntity`.\nFields: createdAt, documentId, id, text, updatedAt\n- `Comment.author`: author(): Promise<User> — The user who wrote this comment.\n- `Comment.delete`: delete(): Promise<void> — Delete this comment.\n- `Comment.document`: document(): Document — The document this comment is on.\n- `Comment.edit`: edit(body): Promise<Comment> — Replace the comment's text.\n- `Comment.reply`: reply(body): Promise<Comment> — Reply in this comment's thread.\n- `Comment.threadId`: threadId(): Promise<string> — The id of the thread this comment belongs to: its root, or itself for a root.\n- `Comment.byId`: static byId(client, documentId, id): Comment — A handle to a comment by id.\n- `Comment.from`: static from(client, documentId, record): Comment — Build a comment from a message record (pre-seeded, no fetch).\n\n### Document\nA Macro document.\nExtends `PropertiedEntity`.\nFields: access, branchedFrom, createdAt, deletedAt, entityType, fileType, id, name, owner, project, updatedAt, search\n- `Document.anchors`: anchors(): Promise<DocumentAnchor[]> — PDF annotations in this document.\n- `Document.branchName`: branchName(): Promise<string> — The git branch name derived for the document (task documents).\n- `Document.comment`: comment(body, opts?): Promise<Comment> — Add a comment.\n- `Document.comments`: comments(): Promise<CommentThread[]> — The document's live comment threads, each with its comments, newest thread first.\n- `Document.content`: content(): Promise<string> — Current Markdown for native documents, extracted text for PDF/Word, or raw file content for other formats.\n- `Document.copy`: copy(opts): Promise<Document> — Copy the document under a new name, optionally from a specific version.\n- `Document.createHighlight`: createHighlight(options): Promise<DocumentAnchor> — Create a standalone PDF highlight.\n- `Document.delete`: delete(opts?): Promise<void> — Delete the document.\n- `Document.githubPullRequests`: githubPullRequests(): Promise<storage.GithubPullRequest[]> — GitHub pull requests associated with the document.\n- `Document.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `Document.move`: move(project): Promise<void> — Move the document into a project (or out of one, with null).\n- `Document.permissionsToken`: permissionsToken(): Promise<string> — Mint a scoped permissions token.\n- `Document.prepareSave`: prepareSave(parts): Promise<PreSaveDocumentResponseData> — Prepare multipart content saving and return the service's upload instructions.\n- `Document.rename`: rename(name): Promise<void> — Rename the document.\n- `Document.restore`: restore(): Promise<void> — Restore a soft-deleted document.\n- `Document.save`: save(options): Promise<SaveDocumentResponseData> — Commit uploaded content.\n- `Document.setTeamShare`: setTeamShare(shared): Promise<void> — Share the document with the owner's team, or unshare it.\n- `Document.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Sharing configuration.\n- `Document.shortId`: shortId(): Promise<string> — The document's short id (used in compact links and branch names).\n- `Document.simpleSave`: simpleSave(): Promise<SaveDocumentResponseData> — Commit a simple document save.\n- `Document.teamShare`: teamShare(): Promise<DocumentTeamShareResponse> — Whether the document is shared with the owner's team, and which team.\n- `Document.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: Comment; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `Document.toJSON`: toJSON(): { detail?: DocumentMetadataWithContent; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n- `Document.toMention`: toMention(): MentionPart — MentionPart\n- `Document.version`: version(version): DocumentVersion — A handle to an immutable version.\n- `Document.webUrl`: webUrl(): string — The document's URL in the Macro web app.\n- `Document.byId`: static byId(client, id): Document — A handle to a document by id.\n- `Document.create`: static create(client, opts): Promise<Document> — Create a markdown document.\n- `Document.createSkill`: static createSkill(client, opts): Promise<Document> — Create a skill: a markdown document containing instructions that AI reads and follows when the skill is referenced in an AI input.\n- `Document.createSnippet`: static createSnippet(client, opts): Promise<Document> — Create a snippet: a reusable markdown document that can be inserted into any markdown area.\n- `Document.recent`: static recent(client, opts?): AsyncGenerator<Document> — The user's recent documents, most recent first, auto-paginated.\n- `Document.recentlyDeleted`: static recentlyDeleted(client): Promise<Document[]> — The user's recently soft-deleted documents.\n\n### DocumentNamespace (`macro.documents`)\n- `DocumentNamespace.byId`: byId(id): Document — A handle to a document by id.\n- `DocumentNamespace.byTeamSlug`: byTeamSlug(slug): Promise<Document> — Resolve a team task reference such as ENG-42.\n- `DocumentNamespace.create`: create(opts): Promise<Document> — Create a markdown document.\n- `DocumentNamespace.createCanvas`: createCanvas(opts): Promise<Document> — Create a native Canvas with shared content ready for reading and editing.\n- `DocumentNamespace.createSkill`: createSkill(opts): Promise<Document> — Create a skill: markdown instructions that AI reads and follows.\n- `DocumentNamespace.createSnippet`: createSnippet(opts): Promise<Document> — Create a snippet: a reusable markdown document.\n- `DocumentNamespace.createUpload`: createUpload(options): Promise<{ content: DocumentContent; contentType: string; document: Document; uploadUrl: string | undefined; }> — Reserve a binary document and return upload instructions.\n- `DocumentNamespace.recent`: recent(opts?): AsyncGenerator<Document> — The user's recent documents, most recent first, auto-paginated.\n- `DocumentNamespace.recentlyDeleted`: recentlyDeleted(): Promise<Document[]> — The user's recently soft-deleted documents.\n- `DocumentNamespace.search`: search(query, opts?): AsyncGenerator<Document> — Search documents by name and content, most relevant first, auto-paginated.\n- `DocumentNamespace.systemSkills`: systemSkills(): Promise<SystemSkill[]> — The built-in system skills: static AI instructions with no document behind them.\n- `DocumentNamespace.validatePermissionsToken`: validatePermissionsToken(token): Promise<{ accessLevel: storage.AccessLevel; document: Document; expiresAt: number; issuer: string; user: User | undefined; }> — Validate a permissions token, returning its document and optional user handles.\n\n### SystemSkill\nA built-in system skill: static, code-defined AI instructions that surface to AI like skill documents but have no document behind them.\nFields: id, name\n- `SystemSkill.list`: static list(client): Promise<SystemSkill[]> — The built-in system skills, in display order.\n\n### DocumentVersion\nAn immutable document version, scoped to its document.\nFields: document, id\n- `DocumentVersion.read`: read(): Promise<GetDocumentResponseData> — Version metadata and the caller's access.\n- `DocumentVersion.toJSON`: toJSON(): { documentId: string; id: number; } — Serialize only scoped identity.\n- `DocumentVersion.byId`: static byId(client, document, id): DocumentVersion — Construct a version handle.\n\nTypes: `CommentThread`\n"},{"name": "email","description": "Search, read, draft, and send email.",- "index": "## email\nSearch, read, draft, and send email.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### EmailAttachment\nA file attached to an email message.\nExtends `MacroEntity`.\nFields: contentId, dataUrl, filename, id, mimeType, sfsId, size\n- `EmailAttachment.toDocument`: toDocument(): Promise<Document> — The Macro document holding this attachment's content.\n- `EmailAttachment.byId`: static byId(client, id): EmailAttachment — A handle to an attachment by id.\n- `EmailAttachment.from`: static from(client, data): EmailAttachment — Build an attachment from an already-fetched record (pre-seeded, no fetch).\n\n### DraftAttachment\nAn uploaded or forwarded attachment belonging to a draft.\nFields: draft, draftGeneration, forwarded, id\n- `DraftAttachment.complete`: complete(): Promise<void> — Complete verification after uploading the file.\n- `DraftAttachment.remove`: remove(): Promise<void> — Remove this attachment from its draft.\n- `DraftAttachment.toJSON`: toJSON(): { draftGeneration: number; draftId: string; forwarded: boolean; id: string; } — Serialize identity without credentials.\n- `DraftAttachment.byId`: static byId(_client, draft, id, forwarded?, draftGeneration?): DraftAttachment — Construct a draft scoped attachment handle.\n\n### EmailDraft\nA draft email.\nExtends `EmailMessage`.\nFields: bcc, body, cc, draftGeneration, from, id, labels, link, sentAt, subject, to\n- `EmailDraft.addAttachment`: addAttachment(options): Promise<{ attachment: DraftAttachment; contentType: string; uploadUrl: string; }> — Reserve an attachment upload.\n- `EmailDraft.delete`: delete(): Promise<void> — Delete the draft.\n- `EmailDraft.forwardAttachment`: forwardAttachment(attachment): Promise<DraftAttachment> — Forward an existing attachment into this draft.\n- `EmailDraft.removeAttachment`: removeAttachment(attachment): Promise<void> — Remove a draft attachment.\n- `EmailDraft.schedule`: schedule(sendTime, options?): Promise<void> — Schedule this draft for sending.\n- `EmailDraft.unschedule`: unschedule(): Promise<void> — Remove a scheduled send.\n- `EmailDraft.update`: update(options): Promise<void> — Replace draft content without changing its identity or sending it.\n- `EmailDraft.verifyAttachment`: verifyAttachment(attachment): Promise<void> — Complete verification of an uploaded attachment.\n- `EmailDraft.byId`: static byId(client, id): EmailDraft — Construct a lazy draft handle.\n\n### EmailFilter\nAn importance filter matched by sender address or domain.\nExtends `MacroEntity`.\nFields: emailAddress, emailDomain, id, isImportant\n- `EmailFilter.delete`: delete(): Promise<void> — Delete this filter.\n- `EmailFilter.setImportant`: setImportant(isImportant): Promise<void> — Change the importance for the same sender selector.\n- `EmailFilter.byId`: static byId(client, id, inbox?): EmailFilter — Construct a lazy filter handle.\n- `EmailFilter.from`: static from(client, record, inbox?): EmailFilter — Seed from a server record.\n\n### Label\nAn email label.\nExtends `MacroEntity`.\nFields: createdAt, id, labelListVisibility, linkId, messageListVisibility, name, type\n- `Label.delete`: delete(): Promise<void> — Delete this label.\n- `Label.byId`: static byId(client, id): Label — A handle to a label by id.\n- `Label.create`: static create(client, name): Promise<Label> — Create a user label.\n- `Label.list`: static list(client): Promise<Label[]> — All labels across the user's inboxes.\n\n### Link\nAn email link: a connected inbox (e.g.\nExtends `MacroEntity`.\nFields: emailAddress, id, isPrimary, isSyncActive, needsReauth, photoUrl, provider, syncStatus\n- `Link.settingsOperations`: settingsOperations(): Promise<MailboxSettingsOperation[]> — Read category and sender-policy changes for this inbox.\n- `Link.byId`: static byId(client, id): Link — A handle to an email link by id.\n- `Link.list`: static list(client): Promise<Link[]> — The caller's connected email links.\n\n### EmailMessage\nA message in an email thread.\nExtends `MacroEntity`.\nFields: bcc, body, cc, from, id, labels, link, sentAt, subject, to\n- `EmailMessage.addLabel`: addLabel(label): Promise<void> — Add a label to this message.\n- `EmailMessage.completeDraftAttachment`: completeDraftAttachment(attachmentId, draftGeneration?): Promise<void> — Verify an uploaded attachment using the draft generation captured when its upload began.\n- `EmailMessage.downloadEml`: downloadEml(): Promise<Blob> — The message's original source, exactly as Gmail or Outlook holds it, as message/rfc822 bytes for an .eml file.\n- `EmailMessage.operationStatus`: operationStatus(): Promise<MessageOperationResponse> — Read the draft's durable send, upload, or conflict status without retrying it.\n- `EmailMessage.removeLabel`: removeLabel(label): Promise<void> — Remove a label from this message.\n- `EmailMessage.resolveOperation`: resolveOperation(request): Promise<void> — Resolve the displayed operation revision after the user chooses an action.\n- `EmailMessage.thread`: thread(): Promise<EmailThread> — The thread this message belongs to.\n- `EmailMessage.transferDraft`: transferDraft(request): Promise<TransferDraftResponse> — Move a draft to another inbox using a caller-persisted operation UUID.\n- `EmailMessage.byId`: static byId(client, id): EmailMessage — A handle to a message by id.\n- `EmailMessage.from`: static from(client, data): EmailMessage — Build a message from an already-fetched record (pre-seeded, no fetch).\n- `EmailMessage.send`: static send(client, opts): Promise<EmailMessage | undefined> — Send a new email message.\n\n### EmailNamespace (`macro.email`)\n- `EmailNamespace.archive`: archive(threads, archived?): Promise<EmailThread[]> — Archive many threads (or unarchive with false).\n- `EmailNamespace.attachment`: attachment(id): EmailAttachment — A handle to an email attachment by id.\n- `EmailNamespace.blockedSenders`: blockedSenders(): Promise<string[]> — The email addresses currently blocked.\n- `EmailNamespace.blockSender`: blockSender(email): Promise<void> — Block an email sender.\n- `EmailNamespace.byId`: byId(id): EmailThread — A handle to an email thread by id.\n- `EmailNamespace.connectionProviders`: connectionProviders(): Promise<EmailConnectionProviders> — Providers the server currently permits this caller to connect.\n- `EmailNamespace.contacts`: contacts(): Promise<{[key: string]: ContactInfoWithInteraction[]; }> — Address book contacts grouped by the service's interaction buckets.\n- `EmailNamespace.createDraft`: createDraft(options, inbox?): Promise<EmailDraft> — Create a draft without sending it; the inbox defaults to the caller's primary.\n- `EmailNamespace.createLabel`: createLabel(name): Promise<Label> — Create a user label.\n- `EmailNamespace.deleteLabel`: deleteLabel(label): Promise<void> — Delete a label.\n- `EmailNamespace.draftById`: draftById(id): EmailDraft — Construct a lazy draft handle.\n- `EmailNamespace.filters`: filters(inbox?): Promise<EmailFilter[]> — Importance filters.\n- `EmailNamespace.inbox`: inbox(opts?): AsyncGenerator<EmailThread> — The threads in the inbox, most recent first, auto-paginated.\n- `EmailNamespace.label`: label(id): Label — A handle to a label by id.\n- `EmailNamespace.labels`: labels(): Promise<Label[]> — All labels across the user's inboxes.\n- `EmailNamespace.link`: link(id): Link — A handle to a connected inbox (email link) by id.\n- `EmailNamespace.links`: links(): Promise<Link[]> — The caller's connected inboxes (email links).\n- `EmailNamespace.message`: message(id): EmailMessage — A handle to an email message by id.\n- `EmailNamespace.recoverDraftTransfer`: recoverDraftTransfer(operationId): Promise<TransferRecoveryResponse> — Recover a draft move using its original operation UUID; never starts a new move.\n- `EmailNamespace.reminders`: reminders(options?): AsyncGenerator<{ followup: EmailFollowup; thread: EmailThread; }, any, any> — Follow-up reminders with thread handles, automatically paginated.\n- `EmailNamespace.scheduled`: scheduled(options?): AsyncGenerator<EmailDraft> — Scheduled drafts, fetched lazily in bounded pages.\n- `EmailNamespace.search`: search(query, opts?): AsyncGenerator<EmailThread> — Search email threads by subject and content.\n- `EmailNamespace.send`: send(opts): Promise<EmailMessage | undefined> — Send a new email message.\n- `EmailNamespace.unblockSender`: unblockSender(email): Promise<void> — Unblock a previously blocked sender.\n- `EmailNamespace.upsertFilter`: upsertFilter(options, inbox?): Promise<EmailFilter> — Create or replace a filter matching an address or domain.\n\n### EmailThread\nAn email thread.\nExtends `PropertiedEntity`.\nFields: access, accessLevel, createdAt, entityType, id, inboxVisible, isRead, latestInboundAt, latestNonSpamAt, latestOutboundAt, link, project, providerId, updatedAt, search\n- `EmailThread.addEventToCalendar`: addEventToCalendar(message, invitation, options?): Promise<CalendarEvent> — Add a shared event one of this thread's messages carries (a published .ics, such as one sent with Forward by email) to one of the requester's Google calendar...\n- `EmailThread.addLabel`: addLabel(label): Promise<void> — Add a label to every message in the thread.\n- `EmailThread.archive`: archive(archived?): Promise<void> — Archive the thread (or unarchive with false).\n- `EmailThread.attachments`: attachments(): Promise<EmailAttachment[]> — The attachments across this thread's first 100 messages, pre-seeded from the thread detail.\n- `EmailThread.calendarInvitations`: calendarInvitations(): Promise<{[key: string]: InvitationResolution; }> — Calendar invitations resolved from this thread's messages.\n- `EmailThread.followup`: followup(): Promise<EmailFollowupResponse> — Read follow-up state for this thread.\n- `EmailThread.markSeen`: markSeen(): Promise<void> — Mark the thread as seen.\n- `EmailThread.messages`: messages(opts?): Promise<EmailMessage[]> — The messages in this thread, pre-seeded from the list endpoint.\n- `EmailThread.moveToProject`: moveToProject(project): Promise<void> — Attach the thread to a project, or clear the project with null.\n- `EmailThread.operations`: operations(): Promise<MailboxOperation[]> — Read pending or failed mailbox changes without initiating a retry.\n- `EmailThread.participants`: participants(): Promise<ApiContactInfo[]> — Everyone on the thread (senders and recipients), deduped by email.\n- `EmailThread.readReceipts`: readReceipts(): Promise<EmailReadReceipt[]> — Opens recorded for messages sent from the caller's own or delegated inboxes with read receipts on, newest message first.\n- `EmailThread.removeLabel`: removeLabel(label): Promise<void> — Remove a label from every message in the thread.\n- `EmailThread.reply`: reply(opts): Promise<EmailMessage | undefined> — Send a reply within this thread.\n- `EmailThread.setFollowup`: setFollowup(command): Promise<EmailFollowup> — Set or remove a follow-up using a persisted operation id and revision.\n- `EmailThread.subject`: subject(): Promise<string | undefined> — The thread's subject, from its first message with one.\n- `EmailThread.update`: update(options): Promise<void> — Change project membership or share permissions for this thread.\n- `EmailThread.updateState`: updateState(request): Promise<void> — Update provider-neutral read, trash, spam, or star state.\n- `EmailThread.archiveMany`: static archiveMany(client, threads, archived?): Promise<EmailThread[]> — Archive many threads (or unarchive with false), sending one request per 100 threads.\n- `EmailThread.byId`: static byId(client, id): EmailThread — A handle to a thread by id.\n\nFunctions: `draftBody`\n\nTypes: `EmailAttachmentData`, `DraftOptions`, `EmailFilterOptions`, `SendEmailOptions`, `EmailMessageData`, `InboxOptions`, `EmailReadReceipt`, `ReplyEmailOptions`\n"+ "index": "## email\nSearch, read, draft, and send email.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### EmailAttachment\nA file attached to an email message.\nExtends `MacroEntity`.\nFields: contentId, dataUrl, filename, id, mimeType, sfsId, size\n- `EmailAttachment.toDocument`: toDocument(): Promise<Document> — The Macro document holding this attachment's content.\n- `EmailAttachment.byId`: static byId(client, id): EmailAttachment — A handle to an attachment by id.\n- `EmailAttachment.from`: static from(client, data): EmailAttachment — Build an attachment from an already-fetched record (pre-seeded, no fetch).\n\n### DraftAttachment\nAn uploaded or forwarded attachment belonging to a draft.\nFields: draft, draftGeneration, forwarded, id\n- `DraftAttachment.complete`: complete(): Promise<void> — Complete verification after uploading the file.\n- `DraftAttachment.remove`: remove(): Promise<void> — Remove this attachment from its draft.\n- `DraftAttachment.toJSON`: toJSON(): { draftGeneration: number; draftId: string; forwarded: boolean; id: string; } — Serialize identity without credentials.\n- `DraftAttachment.byId`: static byId(_client, draft, id, forwarded?, draftGeneration?): DraftAttachment — Construct a draft scoped attachment handle.\n\n### EmailDraft\nA draft email.\nExtends `EmailMessage`.\nFields: bcc, body, cc, draftGeneration, from, id, labels, link, sentAt, subject, to\n- `EmailDraft.addAttachment`: addAttachment(options): Promise<{ attachment: DraftAttachment; contentType: string; uploadUrl: string; }> — Reserve an attachment upload.\n- `EmailDraft.delete`: delete(): Promise<void> — Delete the draft.\n- `EmailDraft.forwardAttachment`: forwardAttachment(attachment): Promise<DraftAttachment> — Forward an existing attachment into this draft.\n- `EmailDraft.removeAttachment`: removeAttachment(attachment): Promise<void> — Remove a draft attachment.\n- `EmailDraft.schedule`: schedule(sendTime, options?): Promise<void> — Schedule this draft for sending.\n- `EmailDraft.unschedule`: unschedule(): Promise<void> — Remove a scheduled send.\n- `EmailDraft.update`: update(options): Promise<void> — Replace draft content without changing its identity or sending it.\n- `EmailDraft.verifyAttachment`: verifyAttachment(attachment): Promise<void> — Complete verification of an uploaded attachment.\n- `EmailDraft.byId`: static byId(client, id): EmailDraft — Construct a lazy draft handle.\n\n### EmailFilter\nAn importance filter matched by sender address or domain.\nExtends `MacroEntity`.\nFields: emailAddress, emailDomain, id, isImportant\n- `EmailFilter.delete`: delete(): Promise<void> — Delete this filter.\n- `EmailFilter.setImportant`: setImportant(isImportant): Promise<void> — Change the importance for the same sender selector.\n- `EmailFilter.byId`: static byId(client, id, inbox?): EmailFilter — Construct a lazy filter handle.\n- `EmailFilter.from`: static from(client, record, inbox?): EmailFilter — Seed from a server record.\n\n### Label\nAn email label.\nExtends `MacroEntity`.\nFields: createdAt, id, labelListVisibility, linkId, messageListVisibility, name, type\n- `Label.delete`: delete(): Promise<void> — Delete this label.\n- `Label.byId`: static byId(client, id): Label — A handle to a label by id.\n- `Label.create`: static create(client, name): Promise<Label> — Create a user label.\n- `Label.list`: static list(client): Promise<Label[]> — All labels across the user's inboxes.\n\n### Link\nAn email link: a connected inbox (e.g.\nExtends `MacroEntity`.\nFields: emailAddress, id, isPrimary, isSyncActive, needsReauth, photoUrl, provider, syncStatus\n- `Link.settingsOperations`: settingsOperations(): Promise<MailboxSettingsOperation[]> — Read category and sender-policy changes for this inbox.\n- `Link.byId`: static byId(client, id): Link — A handle to an email link by id.\n- `Link.list`: static list(client): Promise<Link[]> — The caller's connected email links.\n\n### EmailMessage\nA message in an email thread.\nExtends `MacroEntity`.\nFields: bcc, body, cc, from, id, labels, link, sentAt, subject, to\n- `EmailMessage.addLabel`: addLabel(label): Promise<void> — Add a label to this message.\n- `EmailMessage.completeDraftAttachment`: completeDraftAttachment(attachmentId, draftGeneration?): Promise<void> — Verify an uploaded attachment using the draft generation captured when its upload began.\n- `EmailMessage.downloadEml`: downloadEml(): Promise<Blob> — The message's original source, exactly as Gmail or Outlook holds it, as message/rfc822 bytes for an .eml file.\n- `EmailMessage.operationStatus`: operationStatus(): Promise<MessageOperationResponse> — Read the draft's durable send, upload, or conflict status without retrying it.\n- `EmailMessage.removeLabel`: removeLabel(label): Promise<void> — Remove a label from this message.\n- `EmailMessage.resolveOperation`: resolveOperation(request): Promise<void> — Resolve the displayed operation revision after the user chooses an action.\n- `EmailMessage.thread`: thread(): Promise<EmailThread> — The thread this message belongs to.\n- `EmailMessage.transferDraft`: transferDraft(request): Promise<TransferDraftResponse> — Move a draft to another inbox using a caller-persisted operation UUID.\n- `EmailMessage.byId`: static byId(client, id): EmailMessage — A handle to a message by id.\n- `EmailMessage.from`: static from(client, data): EmailMessage — Build a message from an already-fetched record (pre-seeded, no fetch).\n- `EmailMessage.send`: static send(client, opts): Promise<EmailMessage | undefined> — Send a new email message.\n\n### EmailNamespace (`macro.email`)\n- `EmailNamespace.archive`: archive(threads, archived?): Promise<EmailThread[]> — Archive many threads (or unarchive with false).\n- `EmailNamespace.attachment`: attachment(id): EmailAttachment — A handle to an email attachment by id.\n- `EmailNamespace.blockedSenders`: blockedSenders(): Promise<string[]> — The email addresses currently blocked.\n- `EmailNamespace.blockSender`: blockSender(email): Promise<void> — Block an email sender.\n- `EmailNamespace.byId`: byId(id): EmailThread — A handle to an email thread by id.\n- `EmailNamespace.connectionProviders`: connectionProviders(): Promise<EmailConnectionProviders> — Providers the server currently permits this caller to connect.\n- `EmailNamespace.contacts`: contacts(): Promise<{[key: string]: ContactInfoWithInteraction[]; }> — Address book contacts grouped by the service's interaction buckets.\n- `EmailNamespace.createDraft`: createDraft(options, inbox?): Promise<EmailDraft> — Create a draft without sending it; the inbox defaults to the caller's primary.\n- `EmailNamespace.createLabel`: createLabel(name): Promise<Label> — Create a user label.\n- `EmailNamespace.deleteLabel`: deleteLabel(label): Promise<void> — Delete a label.\n- `EmailNamespace.draftById`: draftById(id): EmailDraft — Construct a lazy draft handle.\n- `EmailNamespace.filters`: filters(inbox?): Promise<EmailFilter[]> — Importance filters.\n- `EmailNamespace.inbox`: inbox(opts?): AsyncGenerator<EmailThread> — The threads in the inbox, most recent first, auto-paginated.\n- `EmailNamespace.label`: label(id): Label — A handle to a label by id.\n- `EmailNamespace.labels`: labels(): Promise<Label[]> — All labels across the user's inboxes.\n- `EmailNamespace.link`: link(id): Link — A handle to a connected inbox (email link) by id.\n- `EmailNamespace.links`: links(): Promise<Link[]> — The caller's connected inboxes (email links).\n- `EmailNamespace.message`: message(id): EmailMessage — A handle to an email message by id.\n- `EmailNamespace.recoverDraftTransfer`: recoverDraftTransfer(operationId): Promise<TransferRecoveryResponse> — Recover a draft move using its original operation UUID; never starts a new move.\n- `EmailNamespace.reminders`: reminders(options?): AsyncGenerator<{ followup: EmailFollowup; thread: EmailThread; }, any, any> — Follow-up reminders with thread handles, automatically paginated.\n- `EmailNamespace.scheduled`: scheduled(options?): AsyncGenerator<EmailDraft> — Scheduled drafts, fetched lazily in bounded pages.\n- `EmailNamespace.search`: search(query, opts?): AsyncGenerator<EmailThread> — Search email threads by subject and content.\n- `EmailNamespace.send`: send(opts): Promise<EmailMessage | undefined> — Send a new email message.\n- `EmailNamespace.unblockSender`: unblockSender(email): Promise<void> — Unblock a previously blocked sender.\n- `EmailNamespace.upsertFilter`: upsertFilter(options, inbox?): Promise<EmailFilter> — Create or replace a filter matching an address or domain.\n\n### EmailThread\nAn email thread.\nExtends `PropertiedEntity`.\nFields: access, accessLevel, createdAt, entityType, id, inboxVisible, isRead, latestInboundAt, latestNonSpamAt, latestOutboundAt, link, project, providerId, updatedAt, search\n- `EmailThread.addEventToCalendar`: addEventToCalendar(message, invitation, options?): Promise<CalendarEvent> — Add a shared event one of this thread's messages carries (a published .ics, such as one sent with Forward by email) to one of the requester's Google calendar...\n- `EmailThread.addLabel`: addLabel(label): Promise<void> — Add a label to every message in the thread.\n- `EmailThread.archive`: archive(archived?): Promise<void> — Archive the thread (or unarchive with false).\n- `EmailThread.attachments`: attachments(): Promise<EmailAttachment[]> — The attachments across this thread's first 100 messages, pre-seeded from the thread detail.\n- `EmailThread.calendarInvitations`: calendarInvitations(): Promise<{[key: string]: InvitationResolution; }> — Calendar invitations resolved from this thread's messages.\n- `EmailThread.followup`: followup(): Promise<EmailFollowupResponse> — Read follow-up state for this thread.\n- `EmailThread.markSeen`: markSeen(): Promise<void> — Mark the thread as seen.\n- `EmailThread.messages`: messages(opts?): Promise<EmailMessage[]> — The messages in this thread, pre-seeded from the list endpoint.\n- `EmailThread.moveToProject`: moveToProject(project): Promise<void> — Attach the thread to a project, or clear the project with null.\n- `EmailThread.operations`: operations(): Promise<MailboxOperation[]> — Read pending or failed mailbox changes without initiating a retry.\n- `EmailThread.participants`: participants(): Promise<ApiContactInfo[]> — Everyone on the thread (senders and recipients), deduped by email.\n- `EmailThread.readReceipts`: readReceipts(): Promise<EmailReadReceipt[]> — Opens recorded for messages sent from the caller's own or delegated inboxes with read receipts on, newest message first.\n- `EmailThread.removeLabel`: removeLabel(label): Promise<void> — Remove a label from every message in the thread.\n- `EmailThread.reply`: reply(opts): Promise<EmailMessage | undefined> — Send a reply within this thread.\n- `EmailThread.setFollowup`: setFollowup(command): Promise<EmailFollowup> — Set or remove a follow-up using a persisted operation id and revision.\n- `EmailThread.subject`: subject(): Promise<string | undefined> — The thread's subject, from its first message with one.\n- `EmailThread.toJSON`: toJSON(): { detail?: ApiThread; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n- `EmailThread.update`: update(options): Promise<void> — Change project membership or share permissions for this thread.\n- `EmailThread.updateState`: updateState(request): Promise<void> — Update provider-neutral read, trash, spam, or star state.\n- `EmailThread.webUrl`: webUrl(): string — The thread's URL in the Macro web app; hand it to users as the link.\n- `EmailThread.archiveMany`: static archiveMany(client, threads, archived?): Promise<EmailThread[]> — Archive many threads (or unarchive with false), sending one request per 100 threads.\n- `EmailThread.byId`: static byId(client, id): EmailThread — A handle to a thread by id.\n\nFunctions: `draftBody`\n\nTypes: `EmailAttachmentData`, `DraftOptions`, `EmailFilterOptions`, `SendEmailOptions`, `EmailMessageData`, `InboxOptions`, `EmailReadReceipt`, `ReplyEmailOptions`\n"},{"name": "favorites",@@ -103,7 +103,7 @@{"name": "forms","description": "Build forms and read responses.",- "index": "## forms\nBuild forms and read responses.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### Form\nA form over a database table.\nExtends `MacroEntity`.\nFields: access, audience, closesAt, database, description, id, name, owner, status, table\n- `Form.editResponse`: editResponse(answers): Promise<FormSubmissionOutcome> — Replace the caller's answers while the form is open; gates are evaluated again.\n- `Form.myResponse`: myResponse(): Promise<MyFormResponse> — Read the caller's receipt and answers without reading anyone else's responses.\n- `Form.questions`: questions(): Promise<FormQuestion[]> — All questions in display order, skipping gates.\n- `Form.replaceLayout`: replaceLayout(sections): Promise<FormLayoutResult> — Save a replacement in the shared draft.\n- `Form.respondUrl`: respondUrl(): string — The respondent page, which public forms also expose without signing in.\n- `Form.responseSummary`: responseSummary(): Promise<FormResponseSummary> — Ledger counts and total table rows; requires edit access.\n- `Form.schema`: schema(): Promise<FormDetail> — The form's presentation and column facts; this never contains response rows.\n- `Form.sections`: sections(): Promise<FormSection[]> — Sections in display order.\n- `Form.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Read the form's sharing grants.\n- `Form.submit`: submit(answers): Promise<FormSubmissionOutcome> — Submit answers.\n- `Form.tally`: tally(): Promise<FormQuestionTally[]> — Choice and checkbox counts, available to viewers when tally visibility is enabled.\n- `Form.update`: update(updates): Promise<Form> — Update presentation or owner-controlled settings; null explicitly clears the closing time.\n- `Form.updateSharePermissions`: updateSharePermissions(request): Promise<storage.SharePermissionV2> — Update grants.\n- `Form.webUrl`: webUrl(): string — Open the form's builder in Macro.\n- `Form.byId`: static byId(client, id): Form — A form handle with details loaded on demand.\n- `Form.create`: static create(client, options): Promise<Form> — Create a form, optionally over a table of a database the caller owns.\n- `Form.list`: static list(client, database?): Promise<Form[]> — Forms shared with the caller, or live forms over a specified database.\n\n### FormReference\nA typed reference read from a form answer, without fetching the referenced entity.\nFields: entityType, id\n- `FormReference.byId`: static byId(entityType, id): FormReference — Construct a reference when its kind and identifier are known.\n\n### FormNamespace (`macro.forms`)\nForms collect answers into a database table without granting respondents table access.\n- `FormNamespace.byId`: byId(id): Form — A form handle.\n- `FormNamespace.create`: create(options): Promise<Form> — Create a form over an existing table, or create its own Responses database.\n- `FormNamespace.list`: list(database?): Promise<Form[]> — List forms shared with the caller, or forms over a database the caller can read.\n\n### FormOption\nA choice of one form question, resolved through that question's current options.\nFields: id, question\n- `FormOption.color`: color(): Promise<string | undefined> — The choice's color, when one is set.\n- `FormOption.detail`: detail(): Promise<QuestionOption> — The choice's label and color.\n- `FormOption.label`: label(): Promise<string> — The choice's label.\n- `FormOption.byId`: static byId(question, id): FormOption — A handle to a known choice of a question.\n\n### FormQuestion\nOne question, backed by a column.\nFields: form, id\n- `FormQuestion.column`: column(): Promise<DatabaseColumn> — The column behind the question.\n- `FormQuestion.detail`: detail(): Promise<FormQuestionDetail> — The question's current presentation and column facts.\n- `FormQuestion.options`: options(): Promise<FormOption[]> — Current choices, in display order.\n- `FormQuestion.title`: title(): Promise<string> — The question's current title (its column's name).\n- `FormQuestion.byId`: static byId(form, id): FormQuestion — A question handle within a form.\n\n### FormResponse\nA cached receipt for the caller's response; other respondents' receipts are private.\nFields: form, id\n- `FormResponse.answers`: answers(): Promise<FormAnswer[]> — Answers as submitted or last read.\n- `FormResponse.booking`: booking(): Promise<FormBookingStep | undefined> — The booking step unlocked by this saved response, if any.\n- `FormResponse.refresh`: refresh(): Promise<FormResponse> — Reload the caller's current receipt; requires a signed-in respondent.\n- `FormResponse.row`: row(): Promise<DatabaseRow | undefined> — The receipt's row, if any.\n- `FormResponse.status`: status(): Promise<ResponseStatus> — Whether this receipt was submitted or stopped by a gate.\n- `FormResponse.byId`: static byId(form, id, snapshot?): FormResponse — A response handle, optionally seeded with an already returned receipt.\n\n### FormSection\nAn ordered group of questions, or a gate between groups.\nFields: form, id\n- `FormSection.detail`: detail(): Promise<FormSectionDetail> — The section's current presentation.\n- `FormSection.questions`: questions(): Promise<FormQuestion[]> — Questions in display order; gates contain no questions.\n- `FormSection.title`: title(): Promise<string> — The section heading.\n- `FormSection.byId`: static byId(form, id): FormSection — A section handle within a form.\n\nTypes: `FormEntityHandle`, `FormAnswer`, `FormAnswerValue`, `FormBookingStep`, `FormBookingTarget`, `FormLayoutResult`, `FormQuestionPlacement`, `FormQuestionTally`, `FormResponseSummary`, `FormRuleTest`, `FormRules`, `FormSectionPlacement`, `FormSubmissionOutcome`, `MyFormResponse`, `SavedFormResponse`\n"+ "index": "## forms\nBuild forms and read responses.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### Form\nA form over a database table.\nExtends `MacroEntity`.\nFields: access, audience, closesAt, database, description, id, name, owner, status, table\n- `Form.editResponse`: editResponse(answers): Promise<FormSubmissionOutcome> — Replace the caller's answers while the form is open; gates are evaluated again.\n- `Form.myResponse`: myResponse(): Promise<MyFormResponse> — Read the caller's receipt and answers without reading anyone else's responses.\n- `Form.questions`: questions(): Promise<FormQuestion[]> — All questions in display order, skipping gates.\n- `Form.replaceLayout`: replaceLayout(sections): Promise<FormLayoutResult> — Save a replacement in the shared draft.\n- `Form.respondUrl`: respondUrl(): string — The respondent page, which public forms also expose without signing in.\n- `Form.responseSummary`: responseSummary(): Promise<FormResponseSummary> — Ledger counts and total table rows; requires edit access.\n- `Form.schema`: schema(): Promise<FormDetail> — The form's presentation and column facts; this never contains response rows.\n- `Form.sections`: sections(): Promise<FormSection[]> — Sections in display order.\n- `Form.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Read the form's sharing grants.\n- `Form.submit`: submit(answers): Promise<FormSubmissionOutcome> — Submit answers.\n- `Form.tally`: tally(): Promise<FormQuestionTally[]> — Choice and checkbox counts, available to viewers when tally visibility is enabled.\n- `Form.toJSON`: toJSON(): { detail?: FormDetail; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n- `Form.update`: update(updates): Promise<Form> — Update presentation or owner-controlled settings; null explicitly clears the closing time.\n- `Form.updateSharePermissions`: updateSharePermissions(request): Promise<storage.SharePermissionV2> — Update grants.\n- `Form.webUrl`: webUrl(): string — Open the form's builder in Macro.\n- `Form.byId`: static byId(client, id): Form — A form handle with details loaded on demand.\n- `Form.create`: static create(client, options): Promise<Form> — Create a form, optionally over a table of a database the caller owns.\n- `Form.list`: static list(client, database?): Promise<Form[]> — Forms shared with the caller, or live forms over a specified database.\n\n### FormReference\nA typed reference read from a form answer, without fetching the referenced entity.\nFields: entityType, id\n- `FormReference.byId`: static byId(entityType, id): FormReference — Construct a reference when its kind and identifier are known.\n\n### FormNamespace (`macro.forms`)\nForms collect answers into a database table without granting respondents table access.\n- `FormNamespace.byId`: byId(id): Form — A form handle.\n- `FormNamespace.create`: create(options): Promise<Form> — Create a form over an existing table, or create its own Responses database.\n- `FormNamespace.list`: list(database?): Promise<Form[]> — List forms shared with the caller, or forms over a database the caller can read.\n\n### FormOption\nA choice of one form question, resolved through that question's current options.\nFields: id, question\n- `FormOption.color`: color(): Promise<string | undefined> — The choice's color, when one is set.\n- `FormOption.detail`: detail(): Promise<QuestionOption> — The choice's label and color.\n- `FormOption.label`: label(): Promise<string> — The choice's label.\n- `FormOption.byId`: static byId(question, id): FormOption — A handle to a known choice of a question.\n\n### FormQuestion\nOne question, backed by a column.\nFields: form, id\n- `FormQuestion.column`: column(): Promise<DatabaseColumn> — The column behind the question.\n- `FormQuestion.detail`: detail(): Promise<FormQuestionDetail> — The question's current presentation and column facts.\n- `FormQuestion.options`: options(): Promise<FormOption[]> — Current choices, in display order.\n- `FormQuestion.title`: title(): Promise<string> — The question's current title (its column's name).\n- `FormQuestion.byId`: static byId(form, id): FormQuestion — A question handle within a form.\n\n### FormResponse\nA cached receipt for the caller's response; other respondents' receipts are private.\nFields: form, id\n- `FormResponse.answers`: answers(): Promise<FormAnswer[]> — Answers as submitted or last read.\n- `FormResponse.booking`: booking(): Promise<FormBookingStep | undefined> — The booking step unlocked by this saved response, if any.\n- `FormResponse.refresh`: refresh(): Promise<FormResponse> — Reload the caller's current receipt; requires a signed-in respondent.\n- `FormResponse.row`: row(): Promise<DatabaseRow | undefined> — The receipt's row, if any.\n- `FormResponse.status`: status(): Promise<ResponseStatus> — Whether this receipt was submitted or stopped by a gate.\n- `FormResponse.byId`: static byId(form, id, snapshot?): FormResponse — A response handle, optionally seeded with an already returned receipt.\n\n### FormSection\nAn ordered group of questions, or a gate between groups.\nFields: form, id\n- `FormSection.detail`: detail(): Promise<FormSectionDetail> — The section's current presentation.\n- `FormSection.questions`: questions(): Promise<FormQuestion[]> — Questions in display order; gates contain no questions.\n- `FormSection.title`: title(): Promise<string> — The section heading.\n- `FormSection.byId`: static byId(form, id): FormSection — A section handle within a form.\n\nTypes: `FormEntityHandle`, `FormAnswer`, `FormAnswerValue`, `FormBookingStep`, `FormBookingTarget`, `FormLayoutResult`, `FormQuestionPlacement`, `FormQuestionTally`, `FormResponseSummary`, `FormRuleTest`, `FormRules`, `FormSectionPlacement`, `FormSubmissionOutcome`, `MyFormResponse`, `SavedFormResponse`\n"},{"name": "notifications",@@ -118,7 +118,7 @@{"name": "projects","description": "Organize entities into projects.",- "index": "## projects\nOrganize entities into projects.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### ProjectNamespace (`macro.projects`)\n- `ProjectNamespace.byId`: byId(id): Project — Project\n- `ProjectNamespace.create`: create(opts): Promise<Project> — Promise<Project>\n- `ProjectNamespace.search`: search(query, opts?): AsyncGenerator<Project> — AsyncGenerator<Project>\n\n### Project\nA Macro project: a folder-like container for documents, chats, and subprojects.\nExtends `PropertiedEntity`.\nFields: access, createdAt, entityType, id, name, parent, search\n- `Project.accessLevel`: accessLevel(): Promise<\"view\" | \"comment\" | \"edit\" | \"owner\"> — Read the caller's effective access level.\n- `Project.delete`: delete(opts?): Promise<void> — Delete the project and its contents.\n- `Project.items`: items(): Promise<Item[]> — The items (documents, chats, subprojects) directly inside this project.\n- `Project.rename`: rename(name): Promise<void> — Rename the project.\n- `Project.restore`: restore(): Promise<void> — Restore a soft-deleted project.\n- `Project.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Read this project's sharing configuration.\n- `Project.byId`: static byId(client, id): Project — A handle to a project by id.\n- `Project.create`: static create(client, opts): Promise<Project> — Create a project, optionally nested inside a parent project.\n"+ "index": "## projects\nOrganize entities into projects.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### ProjectNamespace (`macro.projects`)\n- `ProjectNamespace.byId`: byId(id): Project — Project\n- `ProjectNamespace.create`: create(opts): Promise<Project> — Promise<Project>\n- `ProjectNamespace.search`: search(query, opts?): AsyncGenerator<Project> — AsyncGenerator<Project>\n\n### Project\nA Macro project: a folder-like container for documents, chats, and subprojects.\nExtends `PropertiedEntity`.\nFields: access, createdAt, entityType, id, name, parent, search\n- `Project.accessLevel`: accessLevel(): Promise<\"view\" | \"comment\" | \"edit\" | \"owner\"> — Read the caller's effective access level.\n- `Project.delete`: delete(opts?): Promise<void> — Delete the project and its contents.\n- `Project.items`: items(): Promise<Item[]> — The items (documents, chats, subprojects) directly inside this project.\n- `Project.rename`: rename(name): Promise<void> — Rename the project.\n- `Project.restore`: restore(): Promise<void> — Restore a soft-deleted project.\n- `Project.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Read this project's sharing configuration.\n- `Project.toJSON`: toJSON(): { detail?: storage.Project; id: string; url: string; } — Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n- `Project.webUrl`: webUrl(): string — The project's URL in the Macro web app; hand it to users as the link.\n- `Project.byId`: static byId(client, id): Project — A handle to a project by id.\n- `Project.create`: static create(client, opts): Promise<Project> — Create a project, optionally nested inside a parent project.\n"},{"name": "properties",@@ -861,11 +861,12 @@"AgentSession.setAutoArchive": "### setAutoArchive()\n\n> **setAutoArchive**(`overrides`): `Promise`\\<`void`\\>\n\nReplace this session's auto-archive choices. Owner only; a trigger left\n`undefined` follows the owner's default.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `overrides` | `AutoArchiveOverrides` |\n\n#### Returns\n\n`Promise`\\<`void`\\>","AgentSession.setSandboxSize": "### setSandboxSize()\n\n> **setSandboxSize**(`size`): `Promise`\\<`SandboxSize`\\>\n\nResize this session's sandbox and remember the size as the owner's default.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `size` | `SandboxSize` |\n\n#### Returns\n\n`Promise`\\<`SandboxSize`\\>","AgentSession.sharePermissions": "### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<`agent-harness.SharePermissionV2`\\>\n\nSharing configuration.\n\n#### Returns\n\n`Promise`\\<`agent-harness.SharePermissionV2`\\>",- "AgentSession.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `AgentSessionResponse`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `AgentSessionResponse`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `AgentSessionResponse` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",+ "AgentSession.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `AgentSessionResponse`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `AgentSessionResponse`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `AgentSessionResponse` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`MacroEntity.toJSON`","AgentSession.toolApprovalById": "### toolApprovalById()\n\n> **toolApprovalById**(`id`): `ToolApproval`\n\nConstruct an approval handle scoped to this session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`ToolApproval`","AgentSession.unarchive": "### unarchive()\n\n> **unarchive**(): `Promise`\\<`void`\\>\n\nRestore an archived session so it can be edited and prompted again.\n\n#### Returns\n\n`Promise`\\<`void`\\>","AgentSession.unlinkPullRequest": "### unlinkPullRequest()\n\n> **unlinkPullRequest**(`url`): `Promise`\\<`void`\\>\n\nUnlink a GitHub pull request a person linked to this session. The pull\nrequest the session's agent opened stays linked.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>","AgentSession.updateSharePermissions": "### updateSharePermissions()\n\n> **updateSharePermissions**(`options`): `Promise`\\<`agent-harness.SharePermissionV2`\\>\n\nReplace sharing grants.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `SharePermissionOptions` |\n\n#### Returns\n\n`Promise`\\<`agent-harness.SharePermissionV2`\\>",+ "AgentSession.webUrl": "### webUrl()\n\n> **webUrl**(): `string`\n\nThe session's URL in the Macro web app; hand it to users as the link.\n\n#### Returns\n\n`string`","AgentSession.autoArchivePreferences": "### autoArchivePreferences()\n\n> `static` **autoArchivePreferences**(`client`): `Promise`\\<`AutoArchivePreferencesBody`\\>\n\nWhich triggers archive the caller's sessions by default; each is off unless chosen.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<`AutoArchivePreferencesBody`\\>","AgentSession.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `AgentSession`\n\nA handle to an agent session by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`AgentSession`","AgentSession.chooseMode": "### chooseMode()\n\n> `static` **chooseMode**(`client`, `prompt`): `Promise`\\<`AgentMode`\\>\n\nWhether `prompt` needs a chat agent or a coding agent, as the app's Auto\nmode decides before starting a session. Rejects when Auto mode is not\nenabled for the caller, the classifier is unavailable or slow, or the\ncaller is out of AI quota.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `prompt` | `string` |\n\n#### Returns\n\n`Promise`\\<`AgentMode`\\>",@@ -1029,8 +1030,9 @@"CallRecord.setTeamShare": "### setTeamShare()\n\n> **setTeamShare**(`shared`): `Promise`\\<`void`\\>\n\nShare the call with the creator's team (view access), or unshare it.\nWhile the call is live this sets the pending toggle any participant with\nedit access may change; once archived only the call's creator may change\nit and the API answers 403 otherwise.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `shared` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>","CallRecord.timelinePage": "### timelinePage()\n\n> **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`: `CallMessage`; `type`: `\"message\"`; \\})[]; `nextCursor`: `MessageCursor` \\| `undefined`; `previousCursor`: `MessageCursor` \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | `TimelineOptions`\\<`CallMessage`\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: `User`; `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: `CallMessage`; `type`: `\"message\"`; \\})[]; `nextCursor`: `MessageCursor` \\| `undefined`; `previousCursor`: `MessageCursor` \\| `undefined`; \\}\\>","CallRecord.toggleTeamShare": "### toggleTeamShare()\n\n> **toggleTeamShare**(): `Promise`\\<`boolean`\\>\n\nToggle the server's share-with-team setting and return its new value.\n\n#### Returns\n\n`Promise`\\<`boolean`\\>",- "CallRecord.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `storage.CallRecord`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `storage.CallRecord`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `storage.CallRecord` |\n| `id` | `string` |\n\n#### Inherited from\n\n`FavoritableEntity.toJSON`",+ "CallRecord.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `storage.CallRecord`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `storage.CallRecord`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `storage.CallRecord` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`FavoritableEntity.toJSON`","CallRecord.unfavorite": "### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`CallRecord`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`CallRecord`\\>\n\n#### Inherited from\n\n`FavoritableEntity.unfavorite`",+ "CallRecord.webUrl": "### webUrl()\n\n> **webUrl**(): `string`\n\nThe call's URL in the Macro web app; hand it to users as the link.\n\n#### Returns\n\n`string`","CallRecord.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `CallRecord`\n\nA handle to a call record by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`CallRecord`","CallMessage": "# Class: CallMessage\n\nA message in a call's single persistent chat thread.\n\n## Extends\n\n- `MacroEntity`\\<`storage.Message`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-callid\"></a> `callId` | `readonly` | `string` | - | - |\n| <a id=\"property-content\"></a> `content` | `readonly` | () => `Promise`\\<`string`\\> | The message body (markdown). | - |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | When the message was created. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string`\\> | When the message was last updated. | - |","CallMessage.author": "### author()\n\n> **author**(): `Promise`\\<`User`\\>\n\nThe user who sent this message.\n\n#### Returns\n\n`Promise`\\<`User`\\>",@@ -1074,7 +1076,7 @@"Channel.setPicture": "### setPicture()\n\n> **setPicture**(`picture?`): `Promise`\\<`void`\\>\n\nSet an uploaded profile picture, or clear it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `picture?` | `ChannelPicture` |\n\n#### Returns\n\n`Promise`\\<`void`\\>","Channel.setProperty": "### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | `PropertyDefinition` |\n| `value?` | `properties.SetPropertyValue` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n`PropertiedEntity.setProperty`","Channel.timelinePage": "### timelinePage()\n\n> **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`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | `TimelineOptions`\\<`Message`\\> |\n\n#### Returns\n\n`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`; \\}\\>",- "Channel.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `ApiChannelDetail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `ApiChannelDetail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `ApiChannelDetail` |\n| `id` | `string` |\n\n#### Inherited from\n\n`PropertiedEntity.toJSON`",+ "Channel.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `ApiChannelDetail`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `ApiChannelDetail`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `ApiChannelDetail` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`PropertiedEntity.toJSON`","Channel.typing": "### typing()\n\n> **typing**(`action`, `opts?`): `Promise`\\<`void`\\>\n\nBroadcast a typing indicator, optionally scoped to a thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `action` | `\"start\"` \\| `\"stop\"` |\n| `opts?` | \\{ `thread?`: `Thread`; \\} |\n| `opts.thread?` | `Thread` |\n\n#### Returns\n\n`Promise`\\<`void`\\>","Channel.unfavorite": "### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Channel`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n#### Inherited from\n\n`PropertiedEntity.unfavorite`","Channel.updatePropertyOptions": "### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | `PropertyOptionDelta`[] |\n\n#### Returns\n\n`Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\n#### Inherited from\n\n`PropertiedEntity.updatePropertyOptions`",@@ -1279,10 +1281,11 @@"Database.schema": "### schema()\n\n> **schema**(): `Promise`\\<`DatabaseDetail`\\>\n\nThe full schema: the database record, the caller's access, and every\ntable with its columns and views. Cached until the next write.\n\n#### Returns\n\n`Promise`\\<`DatabaseDetail`\\>","Database.sharePermissions": "### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<`storage.SharePermissionV2`\\>\n\nRead direct recipients. Only the database owner can manage sharing.\n\n#### Returns\n\n`Promise`\\<`storage.SharePermissionV2`\\>","Database.table": "### table()\n\n> **table**(`name`): `Promise`\\<`DatabaseTable` \\| `undefined`\\>\n\nThe table with the given display name, or `undefined` if there is none.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`DatabaseTable` \\| `undefined`\\>",- "Database.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `DatabaseDetail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `DatabaseDetail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `DatabaseDetail` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",+ "Database.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `DatabaseDetail`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `DatabaseDetail`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `DatabaseDetail` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`MacroEntity.toJSON`","Database.updateSharePermissions": "### updateSharePermissions()\n\n> **updateSharePermissions**(`request`): `Promise`\\<`storage.SharePermissionV2`\\>\n\nAdd, replace, or remove recipient grants without transferring ownership.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `request` | `UpdateSharePermissionRequestV2` |\n\n#### Returns\n\n`Promise`\\<`storage.SharePermissionV2`\\>","Database.viewPositions": "### viewPositions()\n\n> **viewPositions**(`view`): `Promise`\\<`CardPosition`[]\\>\n\nWhere a board view's cards sit: each placed card's lane and key.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `view` | `DatabaseView` |\n\n#### Returns\n\n`Promise`\\<`CardPosition`[]\\>","Database.webhooks": "### webhooks()\n\n> **webhooks**(): `Promise`\\<`DatabaseWebhook`[]\\>\n\nThe database's webhooks, oldest first. Takes edit access.\n\n#### Returns\n\n`Promise`\\<`DatabaseWebhook`[]\\>",+ "Database.webUrl": "### webUrl()\n\n> **webUrl**(): `string`\n\nThe database's URL in the Macro web app; hand it to users as the link.\n\n#### Returns\n\n`string`","Database.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `Database`\n\nA handle to a database by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Database`","Database.create": "### create()\n\n> `static` **create**(`client`, `options`): `Promise`\\<`Database`\\>\n\nCreate a database owned by the caller.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `options` | \\{ `name`: `string`; \\} |\n| `options.name` | `string` |\n\n#### Returns\n\n`Promise`\\<`Database`\\>","Database.list": "### list()\n\n> `static` **list**(`client`): `Promise`\\<`Database`[]\\>\n\nThe databases the caller can see, each with the caller's access level.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<`Database`[]\\>",@@ -1382,7 +1385,7 @@"Document.simpleSave": "### simpleSave()\n\n> **simpleSave**(): `Promise`\\<`SaveDocumentResponseData`\\>\n\nCommit a simple document save.\n\n#### Returns\n\n`Promise`\\<`SaveDocumentResponseData`\\>","Document.teamShare": "### teamShare()\n\n> **teamShare**(): `Promise`\\<`DocumentTeamShareResponse`\\>\n\nWhether the document is shared with the owner's team, and which team.\n\n#### Returns\n\n`Promise`\\<`DocumentTeamShareResponse`\\>","Document.timelinePage": "### timelinePage()\n\n> **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`: `Comment`; `type`: `\"message\"`; \\})[]; `nextCursor`: `MessageCursor` \\| `undefined`; `previousCursor`: `MessageCursor` \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | `TimelineOptions`\\<`Comment`\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: `User`; `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: `Comment`; `type`: `\"message\"`; \\})[]; `nextCursor`: `MessageCursor` \\| `undefined`; `previousCursor`: `MessageCursor` \\| `undefined`; \\}\\>",- "Document.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `DocumentMetadataWithContent`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `DocumentMetadataWithContent`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `DocumentMetadataWithContent` |\n| `id` | `string` |\n\n#### Inherited from\n\n`PropertiedEntity.toJSON`",+ "Document.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `DocumentMetadataWithContent`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `DocumentMetadataWithContent`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `DocumentMetadataWithContent` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`PropertiedEntity.toJSON`","Document.toMention": "### toMention()\n\n> **toMention**(): `MentionPart`\n\n#### Returns\n\n`MentionPart`\n\n#### Implementation of\n\n`Mentionable.toMention`","Document.unfavorite": "### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Document`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Document`\\>\n\n#### Inherited from\n\n`PropertiedEntity.unfavorite`","Document.updatePropertyOptions": "### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | `PropertyOptionDelta`[] |\n\n#### Returns\n\n`Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\n#### Inherited from\n\n`PropertiedEntity.updatePropertyOptions`",@@ -1531,11 +1534,12 @@"EmailThread.setFollowup": "### setFollowup()\n\n> **setFollowup**(`command`): `Promise`\\<`EmailFollowup`\\>\n\nSet or remove a follow-up using a persisted operation id and revision.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `command` | `EmailFollowupCommand` |\n\n#### Returns\n\n`Promise`\\<`EmailFollowup`\\>","EmailThread.setProperty": "### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | `PropertyDefinition` |\n| `value?` | `properties.SetPropertyValue` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n`PropertiedEntity.setProperty`","EmailThread.subject": "### subject()\n\n> **subject**(): `Promise`\\<`string` \\| `undefined`\\>\n\nThe thread's subject, from its first message with one.\n\n#### Returns\n\n`Promise`\\<`string` \\| `undefined`\\>",- "EmailThread.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `ApiThread`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `ApiThread`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `ApiThread` |\n| `id` | `string` |\n\n#### Inherited from\n\n`PropertiedEntity.toJSON`",+ "EmailThread.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `ApiThread`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `ApiThread`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `ApiThread` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`PropertiedEntity.toJSON`","EmailThread.unfavorite": "### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`EmailThread`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`EmailThread`\\>\n\n#### Inherited from\n\n`PropertiedEntity.unfavorite`","EmailThread.update": "### update()\n\n> **update**(`options`): `Promise`\\<`void`\\>\n\nChange project membership or share permissions for this thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `project?`: `Project` \\| `null`; `sharePermission?`: `SharePermissionOptions`; \\} |\n| `options.project?` | `Project` \\| `null` |\n| `options.sharePermission?` | `SharePermissionOptions` |\n\n#### Returns\n\n`Promise`\\<`void`\\>","EmailThread.updatePropertyOptions": "### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | `PropertyOptionDelta`[] |\n\n#### Returns\n\n`Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\n#### Inherited from\n\n`PropertiedEntity.updatePropertyOptions`","EmailThread.updateState": "### updateState()\n\n> **updateState**(`request`): `Promise`\\<`void`\\>\n\nUpdate provider-neutral read, trash, spam, or star state.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `request` | `UpdateThreadStateRequest` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",+ "EmailThread.webUrl": "### webUrl()\n\n> **webUrl**(): `string`\n\nThe thread's URL in the Macro web app; hand it to users as the link.\n\n#### Returns\n\n`string`","EmailThread.archiveMany": "### archiveMany()\n\n> `static` **archiveMany**(`client`, `threads`, `archived?`): `Promise`\\<`EmailThread`[]\\>\n\nArchive many threads (or unarchive with `false`), sending one request per\n100 threads. Resolves to the threads whose state could not change.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | `undefined` |\n| `threads` | `EmailThread`[] | `undefined` |\n| `archived?` | `boolean` | `true` |\n\n#### Returns\n\n`Promise`\\<`EmailThread`[]\\>","EmailThread.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `EmailThread`\n\nA handle to a thread by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`EmailThread`","EmailReadReceipt": "# Interface: EmailReadReceipt\n\nOpen tracking for one of the caller's sent messages.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-firstopenedat\"></a> `firstOpenedAt?` | `string` | When the first counted fetch happened, if any. |\n| <a id=\"property-lastopenedat\"></a> `lastOpenedAt?` | `string` | When the latest counted fetch happened, if any. |\n| <a id=\"property-message\"></a> `message` | `EmailMessage` | The tracked message. |\n| <a id=\"property-opencount\"></a> `openCount` | `number` | Counted pixel fetches; repeats within a few seconds count once. |",@@ -1641,7 +1645,7 @@"Form.sharePermissions": "### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<`storage.SharePermissionV2`\\>\n\nRead the form's sharing grants. Requires ownership.\n\n#### Returns\n\n`Promise`\\<`storage.SharePermissionV2`\\>","Form.submit": "### submit()\n\n> **submit**(`answers`): `Promise`\\<`FormSubmissionOutcome`\\>\n\nSubmit answers. Signed-in respondents get at most one response; use editResponse afterwards.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `answers` | `FormAnswer`[] |\n\n#### Returns\n\n`Promise`\\<`FormSubmissionOutcome`\\>","Form.tally": "### tally()\n\n> **tally**(): `Promise`\\<`FormQuestionTally`[]\\>\n\nChoice and checkbox counts, available to viewers when tally visibility is enabled.\n\n#### Returns\n\n`Promise`\\<`FormQuestionTally`[]\\>",- "Form.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `FormDetail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `FormDetail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `FormDetail` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",+ "Form.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `FormDetail`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `FormDetail`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `FormDetail` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`MacroEntity.toJSON`","Form.update": "### update()\n\n> **update**(`updates`): `Promise`\\<`Form`\\>\n\nUpdate presentation or owner-controlled settings; null explicitly clears the closing time.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `updates` | `UpdateForm` |\n\n#### Returns\n\n`Promise`\\<`Form`\\>","Form.updateSharePermissions": "### updateSharePermissions()\n\n> **updateSharePermissions**(`request`): `Promise`\\<`storage.SharePermissionV2`\\>\n\nUpdate grants. Public responding is controlled by audience, not link sharing.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `request` | `UpdateSharePermissionRequestV2` |\n\n#### Returns\n\n`Promise`\\<`storage.SharePermissionV2`\\>","Form.webUrl": "### webUrl()\n\n> **webUrl**(): `string`\n\nOpen the form's builder in Macro.\n\n#### Returns\n\n`string`",@@ -1735,8 +1739,9 @@"GenerateImageOptions": "# Interface: GenerateImageOptions\n\nWhat image to generate.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-aspectratio\"></a> `aspectRatio?` | `GenerateImageAspectRatio` | Shape of the image: `square` (1:1, the default), `landscape` (4:3), `portrait` (3:4), `widescreen` (16:9, banners and slides) or `tall` (9:16, phone screens and stories). |\n| <a id=\"property-prompt\"></a> `prompt` | `string` | Description of the image: subject, style (photo, illustration, flat vector...), composition, colours, mood, and any text that must appear. |\n| <a id=\"property-referenceimages\"></a> `referenceImages?` | (`StaticImage` \\| `Document`)[] | Up to three images to edit or draw from, in the order the prompt refers to them (\"image 1\", \"image 2\"): image documents the caller can view, or static images such as an earlier generation or an attachment. |","Initiative": "# Class: Initiative\n\nA group of tasks and members working toward an outcome.\n\n## Extends\n\n- `MacroEntity`\\<`InitiativeDetail`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `readonly` | `EntityAccess` | Access requests and direct user grants. | - |\n| <a id=\"property-accesslevel\"></a> `accessLevel` | `readonly` | () => `Promise`\\<`storage.AccessLevel`\\> | Current user's access. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-members\"></a> `members` | `readonly` | () => `Promise`\\<`User`[]\\> | Assigned members. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Display name. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<`User`\\> | Owner. | - |\n| <a id=\"property-sharepermissions\"></a> `sharePermissions` | `readonly` | () => `Promise`\\<`storage.SharePermissionV2`\\> | Sharing configuration. | - |\n| <a id=\"property-tasks\"></a> `tasks` | `readonly` | () => `Promise`\\<`Task`[]\\> | Tasks in this initiative. For their names, pass them to `macro.tasks.summaries` (one request) instead of calling `name()` on each. | - |","Initiative.delete": "### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete this initiative.\n\n#### Returns\n\n`Promise`\\<`void`\\>",- "Initiative.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `InitiativeDetail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `InitiativeDetail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `InitiativeDetail` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",+ "Initiative.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `InitiativeDetail`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `InitiativeDetail`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `InitiativeDetail` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`MacroEntity.toJSON`","Initiative.update": "### update()\n\n> **update**(`options`): `Promise`\\<`void`\\>\n\nUpdate the name, membership or sharing configuration.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `members?`: `User`[]; `name?`: `string`; `sharePermission?`: `SharePermissionOptions`; \\} |\n| `options.members?` | `User`[] |\n| `options.name?` | `string` |\n| `options.sharePermission?` | `SharePermissionOptions` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",+ "Initiative.webUrl": "### webUrl()\n\n> **webUrl**(): `string`\n\nThe initiative's URL in the Macro web app; hand it to users as the link.\n\n#### Returns\n\n`string`","Initiative.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `Initiative`\n\nConstruct a lazy initiative handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Initiative`","Initiative.from": "### from()\n\n> `static` **from**(`client`, `record`): `Initiative`\n\nSeed from an initiative detail response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | `InitiativeDetail` |\n\n#### Returns\n\n`Initiative`","InitiativeOptions": "# Interface: InitiativeOptions\n\nInitiative creation settings.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-description\"></a> `description?` | `string` | Collaborative description. |\n| <a id=\"property-members\"></a> `members?` | `User`[] | Members assigned to this initiative. |\n| <a id=\"property-name\"></a> `name` | `string` | Initiative name. |\n| <a id=\"property-propertyvalues\"></a> `propertyValues?` | `InitialPropertyValue`[] | Initial properties. |\n| <a id=\"property-sharewithteam\"></a> `shareWithTeam?` | `boolean` | Whether the current team can access it. |",@@ -1818,9 +1823,10 @@"Project.restore": "### restore()\n\n> **restore**(): `Promise`\\<`void`\\>\n\nRestore a soft-deleted project.\n\n#### Returns\n\n`Promise`\\<`void`\\>","Project.setProperty": "### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | `PropertyDefinition` |\n| `value?` | `properties.SetPropertyValue` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n`PropertiedEntity.setProperty`","Project.sharePermissions": "### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<`storage.SharePermissionV2`\\>\n\nRead this project's sharing configuration.\n\n#### Returns\n\n`Promise`\\<`storage.SharePermissionV2`\\>",- "Project.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `storage.Project`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `storage.Project`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `storage.Project` |\n| `id` | `string` |\n\n#### Inherited from\n\n`PropertiedEntity.toJSON`",+ "Project.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `storage.Project`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `storage.Project`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `storage.Project` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`PropertiedEntity.toJSON`","Project.unfavorite": "### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Project`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Project`\\>\n\n#### Inherited from\n\n`PropertiedEntity.unfavorite`","Project.updatePropertyOptions": "### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | `PropertyOptionDelta`[] |\n\n#### Returns\n\n`Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\n#### Inherited from\n\n`PropertiedEntity.updatePropertyOptions`",+ "Project.webUrl": "### webUrl()\n\n> **webUrl**(): `string`\n\nThe project's URL in the Macro web app; hand it to users as the link.\n\n#### Returns\n\n`string`","Project.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `Project`\n\nA handle to a project by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Project`","Project.create": "### create()\n\n> `static` **create**(`client`, `opts`): `Promise`\\<`Project`\\>\n\nCreate a project, optionally nested inside a parent project.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts` | \\{ `name`: `string`; `parent?`: `Project`; \\} |\n| `opts.name` | `string` |\n| `opts.parent?` | `Project` |\n\n#### Returns\n\n`Promise`\\<`Project`\\>","PropertiesNamespace": "# Class: PropertiesNamespace\n\nProperty definitions and tag sets. Entity-level reads and writes live on\nthe entity handles (`PropertiedEntity.properties`, `setProperty`,\n`deleteProperty`).",@@ -1863,8 +1869,9 @@"Routine.shareAsTemplate": "### shareAsTemplate()\n\n> **shareAsTemplate**(`options`): `Promise`\\<`RoutineTemplate`\\>\n\nShare this routine as a template, or update its shared snapshot. People\nget the template, never the routine, its runs or its results.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `description`: `string`; `variables`: `TemplateVariable`[]; \\} | - |\n| `options.description` | `string` | What the routine does for someone. |\n| `options.variables` | `TemplateVariable`[] | How each user-specific reference fills in when someone activates it. |\n\n#### Returns\n\n`Promise`\\<`RoutineTemplate`\\>","Routine.stopSharingTemplate": "### stopSharingTemplate()\n\n> **stopSharingTemplate**(): `Promise`\\<`void`\\>\n\nStop sharing this routine. Routines already activated keep running.\n\n#### Returns\n\n`Promise`\\<`void`\\>","Routine.template": "### template()\n\n> **template**(): `Promise`\\<`RoutineTemplate` \\| `undefined`\\>\n\nThis routine's shared template, or `undefined` when it isn't shared.\n\n#### Returns\n\n`Promise`\\<`RoutineTemplate` \\| `undefined`\\>",- "Routine.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `ScheduledActionResponse`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `ScheduledActionResponse`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `ScheduledActionResponse` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",+ "Routine.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `ScheduledActionResponse`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `ScheduledActionResponse`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `ScheduledActionResponse` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Overrides\n\n`MacroEntity.toJSON`","Routine.update": "### update()\n\n> **update**(`options`): `Promise`\\<`void`\\>\n\nReplace the routine's task and trigger configuration.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `RoutineOptions` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",+ "Routine.webUrl": "### webUrl()\n\n> **webUrl**(): `string`\n\nThe routine's URL in the Macro web app; hand it to users as the link.\n\n#### Returns\n\n`string`","Routine.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `Routine`\n\nConstruct a lazy routine handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Routine`","Routine.from": "### from()\n\n> `static` **from**(`client`, `record`): `Routine`\n\nSeed a handle from a server record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | `ScheduledActionResponse` |\n\n#### Returns\n\n`Routine`","RoutineExecution": "# Class: RoutineExecution\n\nA completed routine execution, as recorded by the service.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-record\"></a> `record` | `readonly` | `ActionExecutionRecord` | Execution snapshot. |\n| <a id=\"property-routine\"></a> `routine` | `readonly` | `Routine` | Parent routine. |\n\n## Accessors\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string` \\| `undefined`\n\nExecution identity, when assigned.\n\n##### Returns\n\n`string` \\| `undefined`",@@ -1933,7 +1940,7 @@"Task.simpleSave": "### simpleSave()\n\n> **simpleSave**(): `Promise`\\<`SaveDocumentResponseData`\\>\n\nCommit a simple document save.\n\n#### Returns\n\n`Promise`\\<`SaveDocumentResponseData`\\>\n\n#### Inherited from\n\n`Document.simpleSave`","Task.teamShare": "### teamShare()\n\n> **teamShare**(): `Promise`\\<`DocumentTeamShareResponse`\\>\n\nWhether the document is shared with the owner's team, and which team.\n\n#### Returns\n\n`Promise`\\<`DocumentTeamShareResponse`\\>\n\n#### Inherited from\n\n`Document.teamShare`","Task.timelinePage": "### timelinePage()\n\n> **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`: `Comment`; `type`: `\"message\"`; \\})[]; `nextCursor`: `MessageCursor` \\| `undefined`; `previousCursor`: `MessageCursor` \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | `TimelineOptions`\\<`Comment`\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: `User`; `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: `Comment`; `type`: `\"message\"`; \\})[]; `nextCursor`: `MessageCursor` \\| `undefined`; `previousCursor`: `MessageCursor` \\| `undefined`; \\}\\>\n\n#### Inherited from\n\n`Document.timelinePage`",- "Task.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `DocumentMetadataWithContent`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `DocumentMetadataWithContent`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `DocumentMetadataWithContent` |\n| `id` | `string` |\n\n#### Inherited from\n\n`Document.toJSON`",+ "Task.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `DocumentMetadataWithContent`; `id`: `string`; `url`: `string`; \\}\n\nIdentity, loaded detail and `Document.webUrl`, so serialized handles carry their link.\n\n#### Returns\n\n\\{ `detail?`: `DocumentMetadataWithContent`; `id`: `string`; `url`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `DocumentMetadataWithContent` |\n| `id` | `string` |\n| `url` | `string` |\n\n#### Inherited from\n\n`Document.toJSON`","Task.toMention": "### toMention()\n\n> **toMention**(): `MentionPart`\n\n#### Returns\n\n`MentionPart`\n\n#### Inherited from\n\n`Document.toMention`","Task.unfavorite": "### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Task`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Task`\\>\n\n#### Inherited from\n\n`Document.unfavorite`","Task.updatePropertyOptions": "### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | `PropertyOptionDelta`[] |\n\n#### Returns\n\n`Promise`\\<`BulkUpdateEntityPropertyOptionsResponse`\\>\n\n#### Inherited from\n\n`Document.updatePropertyOptions`",diff --git a/crates/agent_code_mode/src/inbound/toolset/shared/program.md b/crates/agent_code_mode/src/inbound/toolset/shared/program.mdindex e7b750129b..98123e0509 100644--- a/crates/agent_code_mode/src/inbound/toolset/shared/program.md+++ b/crates/agent_code_mode/src/inbound/toolset/shared/program.md@@ -1,3 +1,3 @@-Do the whole job in as few executions as possible, ideally one: every execution costs a model turn. Put control flow in the program instead of checking in one execution and acting in the next, e.g. if macro.tasks.findSimilar finds no likely duplicate, create the task and return it, else return the matches without creating. Use nested SDK entities, e.g. macro.documents.search(query) is an async iterator and document.content() is a promise. Use for await...of, break, conditions and ordinary JavaScript freely. Batch useful independent work with Promise.all or Promise.allSettled; inspect partial failures and await every started operation. Use bounded concurrency for large inputs. Preserve user source scope on every search and retry: macro.documents.search searches documents; macro.email.search searches emails. Read names in batches: macro.initiatives.summaries() and macro.tasks.summaries(tasks) each take one request, while name() on every handle loads each entity separately. Create a task with its initiative, assignees and dueDate in one macro.tasks.create call. Return compact evidence with source IDs, URLs, explicit failures and coverage limits, enough to answer without a follow-up execution; do not return SDK objects, raw large batches, or claim a stopped iterator is exhaustive.+Do the whole job in as few executions as possible, ideally one: every execution costs a model turn. Put control flow in the program instead of checking in one execution and acting in the next, e.g. if macro.tasks.findSimilar finds no likely duplicate, create the task and return it, else return the matches without creating. Use nested SDK entities, e.g. macro.documents.search(query) is an async iterator and document.content() is a promise. Use for await...of, break, conditions and ordinary JavaScript freely. Batch useful independent work with Promise.all or Promise.allSettled; inspect partial failures and await every started operation. Use bounded concurrency for large inputs. Preserve user source scope on every search and retry: macro.documents.search searches documents; macro.email.search searches emails. Read names in batches: macro.initiatives.summaries() and macro.tasks.summaries(tasks) each take one request, while name() on every handle loads each entity separately. Create a task with its initiative, assignees and dueDate in one macro.tasks.create call. Return compact evidence with source IDs, URLs, explicit failures and coverage limits, enough to answer without a follow-up execution; for each item you create or point the user to, return its webUrl() as the URL rather than building one; do not return SDK objects, raw large batches, or claim a stopped iterator is exhaustive.For a workspace overview, fetch small pages for the relevant categories concurrently in one execution with macro.workspace.page({includeTypes:[type], limit:3}). A single mixed page can be dominated by one category; each page is a sample, not a category total. Return selected metadata and hasMore per category, not whole items or snapshots. Exact workspace types include calendar_event, ai_chat and channel_thread. Tasks are documents: use includeTypes:["document"], df:{l:{dst:"task"}}. AST & and | combine exactly two expressions; do not wrap a single filter.diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex 2f4cc7dd3a..046a9df1fc 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 dO($,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 W${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)}var X$=Symbol.for("@ts-pattern/matcher"),s1=Symbol.for("@ts-pattern/isVariadic");var d0=($)=>Boolean($&&typeof $=="object"),Lj=($)=>$&&!!$[X$],s=($,O,j)=>{if(Lj($)){let x=$[X$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(d0($)){if(!d0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Lj(X)&&X[s1]?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),Q=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,G)=>s(L,Z[G],j))&&S.every((L,G)=>s(L,X[G],j))&&(K.length===0||s(K[0],Q,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)||Lj(K=S)&&K[X$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Z$=($)=>{var O,j,x;return d0($)?Lj($)?(O=(j=(x=$[X$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?lO($,Z$):lO(Object.values($),Z$):[]},lO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function a7(...$){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 e($){return Object.assign($,{optional:()=>p0($),and:(O)=>l($,O),or:(O)=>t1($,O),select:(O)=>O===void 0?rO($):rO(O,$)})}function l0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[s1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>l0(p0($)),select:(O)=>l0(O===void 0?rO($):rO(O,$))})}function p0($){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Z$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Z$($),matcherType:"optional"})})}var i7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},n7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},s7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function l(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>lO($,Z$),matcherType:"and"})})}function t1(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return lO($,Z$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>lO($,Z$),matcherType:"or"})})}function u($){return{[X$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function rO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return e({[X$]:()=>({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?[]:Z$(j))})})}function e1($){return!0}function w$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var o1=e(u(e1)),t7=e(u(e1)),e7=o1,s$=($)=>Object.assign(e($),{startsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),n1=s$(u(i$)),f$=($)=>Object.assign(e($),{between:(O,j)=>f$(l($,((x,S)=>u((K)=>w$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<j))(O))),gt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>j))(O))),lte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<=j))(O))),gte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>=j))(O))),int:()=>f$(l($,u((O)=>w$(O)&&Number.isInteger(O)))),finite:()=>f$(l($,u((O)=>w$(O)&&Number.isFinite(O)))),positive:()=>f$(l($,u((O)=>w$(O)&&O>0))),negative:()=>f$(l($,u((O)=>w$(O)&&O<0)))}),o7=f$(u(w$)),t$=($)=>Object.assign(e($),{between:(O,j)=>t$(l($,((x,S)=>u((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(l($,u((O)=>n$(O)&&O>0))),negative:()=>t$(l($,u((O)=>n$(O)&&O<0)))}),$5=t$(u(n$)),O5=e(u(function($){return typeof $=="boolean"})),j5=e(u(function($){return typeof $=="symbol"})),x5=e(u(function($){return $==null})),S5=e(u(function($){return $!=null})),t={__proto__:null,matcher:X$,optional:p0,array:function(...$){return l0({[X$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Z$(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?[]:Z$($[0])})})},set:function(...$){return e({[X$]:()=>({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:i7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},map:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Q)=>{j[X]=(j[X]||[]).concat([Q])};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:n7(O,(X,Q)=>{let L=s(K,Q,x),G=s(Z,X,x);return L&&G}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},record:function(...$){return e({[X$]:()=>({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,Q)=>{x[X]=(x[X]||[]).concat([Q])},[K,Z]=$.length===1?[n1,$[0]]:$;return{matched:s7(O,(X,Q)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),G=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Q,S);return(J||G)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},intersection:l,union:t1,not:function($){return e({[X$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:rO,any:o1,unknown:t7,_:e7,string:n1,number:o7,bigint:$5,boolean:O5,symbol:j5,nullish:x5,nonNullable:S5,instanceOf:function($){return e(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return e(u(a7($)))}};class $2 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 r0={matched:!1,value:void 0};function k($){return new Nj($,r0)}class Nj{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=(Q,L)=>{S=!0,K[Q]=L},X=!j.some((Q)=>s(Q,this.input,Z))||x&&!Boolean(x(this.input))?r0:{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 Nj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Nj(this.input,j?{matched:!0,value:O(this.input,this.input)}:r0)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=Z5){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function Z5($){throw new $2($)}class w extends Error{constructor($){super($);this.name="MacroError"}}var O2=500;function X5($){let O=k($).with(t.string,(j)=>j).with({message:t.string},({message:j})=>j).with({error:t.string},({error:j})=>j).otherwise(()=>"").trim();return O.length>O2?`${O.slice(0,O2)}…`:O}class e$ extends w{status;data;constructor($,O){let j=X5(O);super(j?`Macro API error ${$}: ${j}`:`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class a0 extends e${constructor($){super(403,$);this.name="MacroForbiddenError"}}function K5($,O){return $===403?new a0(O):new e$($,O)}class E extends w{constructor($){super($);this.name="MacroNotFoundError"}}function Y($){if($.error!==void 0)throw K5($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>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 A{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 K$ 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 Q5={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function o$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>Q5[x]??x);return`<${$}>${j}</${$}>`}function Y5($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var G5={toMention:()=>({tag:o$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function J5($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(Y5(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:V5(x)}}function V5($){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 B$ extends A{static byId($,O){return new B$($,O)}static from($,O){return new B$($,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 A{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",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:i0($)}))}}function i0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Q,...L}=$;return{...L,channel_ids:O?.map((G)=>G.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Q}}async function Uj($,O,j,x=[]){let{channelId:S,thread:K}=B5(O);if(await L5($)){let{id:X}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((Q)=>({entity_type:W5,entity_id:Q.id,width:Q.width??null,height:Q.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new w("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 w("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 W5="static/image";function B5($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function L5($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${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 o.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)=>o.from(this.client,this.channelId,O))}async reply($,O){let j=await Uj(this.client,this,O$($),O?.images);return o.byId(this.client,this.channelId,j)}}class o 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 o($,O,j,x)}static from($,O,j){return new o($,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 M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(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 zj{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:d.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new n0(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 n0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return o.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return d.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 L$ extends A{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 L$($,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 b$($,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:M.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 N5=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Q=X?.searchOn??"name_content",L=X?.pageSize??N5;return c(async(G)=>{let{results:J,next_cursor:I}=Y(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Q,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...G?{cursor:G}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class GO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new GO(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 K${async recordActivity($){return new GO(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 L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return b$(this.client,{type:"channel",entity:this},(O)=>o.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new zj(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 Uj(this.client,O?.thread??this,O$($),O?.images);return o.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)=>o.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return o.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 M extends K${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 M($,O)}static fromName($,O){return new M($,O.id,O)}static async me($){let{user_id:O}=Y(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}async isAgent(){return(await this.detail.get()).is_agent===!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:o$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class $${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?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?IO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>IO.from(this.client,this,j))}}async request($){let{mine:O}=await this.state();return this.submit($,O?await O.revision():void 0)}async submit($,O){return IO.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:M.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 IO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new IO($,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",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function $O($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}function s0($){return $}class N$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.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 N$.fromRecord($,O,s0(S))}static async list($,O){return Y(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),s0(x)))}async fetch(){return s0(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((j)=>new t0(j,{edit:(x)=>this.decide({action:"edit",item:j.id,draft:x}),submit:()=>this.decide({action:"submit",items:[j.id]}),dismiss:()=>this.decide({action:"dismiss",items:[j.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 t0{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()}}async function Ij($,O,j,x){Y(await $.agentHarness.presentSessionView({path:{session_id:O.id},body:{view:j,executionId:x?.id??null}}))}class pO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new pO($,j,O)}async fetch(){return Y(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};views={present:($)=>Ij(this.client,this.parent,$,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 Hj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Hj($,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 aO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new aO($,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 d extends A{access=new $$(this.client,"agent_session",this);toolApprovalById($){return aO.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:$O($)}))}static byId($,O){return new d($,O)}static async createManaged($,O){let{session:j}=Y(await $.agentHarness.createAgentSession({body:{botId:O?.agent?.id,prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new d($,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");archivedBy=this.field("archivedBy");archivedAt=this.field("archivedAt");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)=>d.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?M.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 autoArchive(){let{overrides:$,defaults:O,autoArchivedAt:j}=Y(await this.client.agentHarness.getAgentSessionAutoArchive({path:{session_id:this.id}}));return{overrides:{onPullRequestMerged:$.onPullRequestMerged??void 0,onRuntimeClosed:$.onRuntimeClosed??void 0},defaults:O,autoArchivedAt:j??void 0}}async setAutoArchive($){Y(await this.client.agentHarness.putAgentSessionAutoArchive({path:{session_id:this.id},body:{onPullRequestMerged:$.onPullRequestMerged??null,onRuntimeClosed:$.onRuntimeClosed??null}}))}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:{archived:$}}))}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 autoArchivePreferences($){return Y(await $.agentHarness.getAgentAutoArchivePreferences())}static async setAutoArchivePreferences($,O){return Y(await $.agentHarness.putAgentAutoArchivePreferences({body:O}))}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)=>Hj.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:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};views={present:($)=>Ij(this.client,this,$)};codeExecutions={byId:($)=>pO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class e0{client;constructor($){this.client=$}byId($){return d.byId(this.client,$)}createManaged($){return d.createManaged(this.client,$)}chooseMode($){return d.chooseMode(this.client,$)}repositories(){return d.repositories(this.client)}repositoryBranches($){return d.repositoryBranches(this.client,$)}forPullRequest($){return d.forPullRequest(this.client,$)}defaultSandboxSize(){return d.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return d.setDefaultSandboxSize(this.client,$)}codingPreferences(){return d.codingPreferences(this.client)}autoArchivePreferences(){return d.autoArchivePreferences(this.client)}setAutoArchivePreferences($){return d.setAutoArchivePreferences(this.client,$)}setCodingPreferences($){return d.setCodingPreferences(this.client,$)}}class o0{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:i0($)})))}}class $x{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 OO extends A{static byId($,O){return new OO($,O)}static from($,O){return new OO($,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 Ox{client;constructor($){this.client=$}byId($){return OO.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>OO.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:OO.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class iO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new w("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 w("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 w("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class R$ extends A{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 m$ extends A{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 m$($,O)}static async list($){let{calendars:O}=Y(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class nO{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 S$ extends A{async fetch(){throw new w(`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 S$($,O)}static fromRecord($,O){return new S$($,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",($)=>$?m$.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:U5($)}));return S$.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 nO(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 S$.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 S$.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 S$.fromRecord(this.client,O)}}function U5($){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 jx{client;async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.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??=I5(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:S$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:j2(K.event,S),inbox:Z?.emailAddress,role:H5(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.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:S$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return S$.byId(this.client,$)}replacement($){return new nO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:z5($)}));return S$.fromRecord(this.client,O)}}function z5($){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 I5($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function j2($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function H5($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&j2($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends A{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 u$ extends A{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 u$($,O,j)}static from($,O,j){return new u$($,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 M.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 u$.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 L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return b$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new $$(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 u$.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",($)=>M.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 xx{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class Sx{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}}))}}var T5=100;class Zx{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new GO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new Sx($)}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(){for await(let $ of this.records())yield b.byId(this.client,$.id)}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let j=$.toLowerCase();for await(let x of this.records())if(x.name?.toLowerCase().includes(j))yield b.byId(this.client,x.id)}else yield*b.search(this.client,$,O)}records(){return c(async($)=>{let O=Y(await this.client.storage.getChannels({query:{limit:T5,...$?{cursor:$}:{}}}));return{items:O.items,nextCursor:O.next_cursor}})}}class n extends K${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 $$(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 sO{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 sO($,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 tO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new tO($,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 Q$ extends K${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=Q$.byId(this.client,S.chat_id);return sO.byId(this.client,K,S.stream_id,tO.byId(this.client,K,S.message_id))}access=new $$(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 Q$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Q$($,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 Q$(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 Q$($,O.chat_id)});toMention(){return{tag:o$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class Xx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class HO extends A{static byId($,O){return new HO($,O)}static from($,O){return new HO($,O.id,O)}async fetch(){let $=Y(await this.client.auth.getTeamInvites()).invites.find((O)=>O.id===this.id);if(!$)throw new E(`team invite ${this.id} not found`);return $}email=this.field("email");role=this.field("team_role");invitedBy=this.mappedField("invited_by",($)=>M.byId(this.client,$));createdAt=this.field("created_at");lastSentAt=this.field("last_sent_at");async revoke(){await this.mutate(($)=>$.auth.deleteTeamInviteHandler({path:{team_invite_id:this.id}}))}}class _$ extends A{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 _$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O?.team)throw new E("caller has no current team");return new _$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new _$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){return(await this.requireCurrent("members")).members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}async invite($,O){let j=[],x=new Set;for(let K of typeof $==="string"?[$]:$){let Z=K.trim(),X=Z.toLowerCase();if(Z&&!x.has(X))x.add(X),j.push(Z)}if(j.length===0)throw new w("invite needs at least one email address");let S=await this.client.auth.inviteToTeam({body:{invites:j.map((K)=>({email:K})),team_id:this.id,...O?.agent&&{is_agent:!0}}});if(S.response?.status===304)return!1;return Y(S),!0}async invites(){return Y(await this.client.auth.getTeamInvites({query:{team_id:this.id}})).invites.map(($)=>HO.from(this.client,$))}async requireCurrent($){let O=Y(await this.client.auth.getTeam());if(!O?.team||O.team.id!==this.id)throw new w(`${$} are only available for the current team (see Team.current)`);return O}}var R5=8;class A$ extends A{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 A$($,O,j)}static from($,O,j){return new A$($,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 M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return eO(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 Tj($,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 dO(S,R5,async(K)=>{let{state:Z,root:X,replies:Q}=Y(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Q].map((L)=>A$.from($,O,L))}})}async function eO($,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 A$.from($,O,S)}class P$ extends H${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_contact",entity:this},(O)=>A$.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 P$($,O)}static from($,O){return new P$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>$?k$.byId(this.client,$):void 0);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 Tj(this.client,this.commentParent)}async comment($,O){return eO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class k$ extends K${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_company",entity:this},(O)=>A$.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 k$($,O)}static from($,O){return new k$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>_$.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)=>P$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new k$($,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 P$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Tj(this.client,this.commentParent)}async comment($,O){return eO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class jO extends A{tableDetail=new W$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new jO($,O)}static from($,O){return new jO($,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",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>_$.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:$O($)}))}async table(){return Rj.from(this.client,this,await this.tableRecord())}async viewPositions($){if($.table.pipeline.id!==this.id)throw Error("View belongs to another pipeline");return Y(await this.client.storage.getCrmPipelineViewPositions({path:{id:this.id,view:$.id}}))}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)=>JO.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)=>JO.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 Rj extends A{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 Rj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>_j.from(this.client,this,$))}async views(){return(await this.pipeline.tableRecord()).views.map(($)=>Dj.byId(this,$.id))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return JO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let $=(await this.table.pipeline.tableRecord()).views.find((O)=>O.id===this.id);if(!$)throw new E(`view ${this.id} is not on table ${this.table.id}`);return $}positions(){return this.table.pipeline.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id,pipelineId:this.table.pipeline.id}}}class JO extends A{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 JO($,O,j)}static from($,O,j){return new JO($,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 _j extends A{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 _j($,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 Kx{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>jO.from(this.client,$))}async create($){return jO.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class Qx{client;pipelines;constructor($){this.client=$;this.pipelines=new Kx($)}companyById($){return k$.byId(this.client,$)}contactById($){return P$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?P$.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)=>P$.from(this.client,x))}async createCompany($){return k$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async createContact($){return P$.from(this.client,Y(await this.client.storage.createCrmTeamContact({body:$})))}async blockedDomains(){return Y(await this.client.storage.listCrmBlockedDomains()).map(($)=>$.domain)}async blockDomain($){Y(await this.client.storage.blockCrmDomain({path:{domain:$}}))}async unblockDomain($){Y(await this.client.storage.unblockCrmDomain({path:{domain:$}}))}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 k$.search(this.client,$)}}var Yx,D5=new Uint8Array(16);function Cj(){if(!Yx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Yx=crypto.getRandomValues.bind(crypto)}return Yx(D5)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function x2($,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 Gx={};function _5($,O,j){let x;if($)x=S2($.random??$.rng?.()??Cj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Cj();C5(Gx,S,K),x=S2(K,Gx.msecs,Gx.seq,O,j)}return O??x2(x)}function C5($,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 S2($,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 c$=_5;class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,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 E${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new E$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Mj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Mj($,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)=>F$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return E$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Mj.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 Aj($,O,j,x={}){let S=Y(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:G,version:J})=>[G.id,J]))}})),K=new Map;for(let G of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!G)continue;let J=K.get(G.id);if(J)J.add(G);else K.set(G.id,new Set([G]))}let Z=(G)=>{let J=K.get(G)?.values().next().value;if(J)return J;let I=O($,G);return K.set(G,new Set([I])),I},X=(G)=>{let J=S.tableDatabases[G];if(!J)throw Error(`SQL response is missing the owner of table ${G}`);return V$.byId(Z(J),G)},Q=new Set(Object.keys(S.newVersions).map((G)=>X(G).database.id));if(S.statement.kind==="schema")Q.add(S.statement.databaseId);for(let G of Q)for(let J of K.get(G)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(G)=>G).with({kind:"schema"},({databaseId:G,summary:J})=>({kind:"schema",database:Z(G),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:G,tableId:J,tableName:I})=>({kind:G,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:G,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(G);return{kind:"alterColumnType",table:V,tableName:J,column:F$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?M5(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((G)=>E$.byId(L.table,G)):[],newVersions:Object.entries(S.newVersions).map(([G,J])=>({table:X(G),version:J})),readVersions:Object.entries(S.readVersions).map(([G,J])=>({table:X(G),version:J})),truncatedTables:S.truncatedTables,statement:L}}function M5($,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)=>E$.byId(x,S)):[]}}class Pj{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 Pj($,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 Wx extends e${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 Fj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:t.not("relation")},(O)=>O).exhaustive()}var A5={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 P5($){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})=>A5[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Jx($){return $.map((O)=>({id:c$(),label:O}))}function Z2($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Vx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:t.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function d$($,O,j){let[x]=$;if($.length!==1||!Z2(x,O,j))throw new w(`expected one ${O}.${j} result, got ${$.map(Vx).join(", ")||"none"}`);return x}class Y$ extends A{access=new $$(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 w(`${$} does not belong to database ${this.id}`)}static byId($,O){return new Y$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new Y$($,j.id)}async duplicate($){let O=Y(await this.client.storage.duplicateDatabase({path:{id:this.id},body:{name:$?.name}}));return new Y$(this.client,O.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new Y$($,j.database.id))}query($,O){return Aj(this.client,Y$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.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}=d$(await this.applyOps([{kind:"table",table:c$(),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 Wx(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 w(`expected one reorder_tables result, got ${O.map(Vx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),d$(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 Pj.fromRecord(V$.byId(this,$.tableId),M.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 d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Fj(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:Fj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${P5(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Fj(O.to),options:Jx(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:Q})=>({row:X,cells:[{column:S,value:Q}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!Z2(Z,"column","created"))throw new w(`expected a column.created result, got ${Z?Vx(Z):"none"}`);return F$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=d$(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 w(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=d$(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 w(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new w(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=d$(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 w(`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:Fj(O.type),...O.options!==void 0?{options:Jx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=d$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return F$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Jx(O)}}]),"column","options_added")}}class Bx{client;constructor($){this.client=$}query($,O){return Aj(this.client,Y$.byId,$,O)}byId($){return Y$.byId(this.client,$)}create($){return Y$.create(this.client,$)}list(){return Y$.list(this.client)}}class VO extends A{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 l$ extends A{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 l$($,O,j)}static from($,O,j){return new l$($,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 f.byId(this.client,this.documentId)}async author(){return M.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 oO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>Y(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new oO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var F5=8;class f extends K${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 oO.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 L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return b$(this.client,{type:"document",entity:this},(O)=>l$.from(this.client,this.id,O),$)}access=new $$(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 f($,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 f($,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 f($,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 f($,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 f($,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 f($,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",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?f.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 e$(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 f(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 dO(j,F5,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)=>l$.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 l$.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 f($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:o$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Ej{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Ej(j.id,j.name))}}class Lx{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 f.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Y(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:f.byId(this.client,O.document_id),user:O.user_id?M.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:f.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return f.byId(this.client,$)}create($){return f.create(this.client,$)}async createCanvas($){let O=Y(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return f.byId(this.client,O.documentId)}createSnippet($){return f.createSnippet(this.client,$)}createSkill($){return f.createSkill(this.client,$)}systemSkills(){return Ej.list(this.client)}search($,O){return f.search(this.client,$,O)}recent($){return f.recent(this.client,$)}recentlyDeleted(){return f.recentlyDeleted(this.client)}}class WO extends A{async fetch(){let{attachment:$}=Y(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,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 f.byId(this.client,$)}}class z$ extends K${access=new $$(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 S$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=Y(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:U$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}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?$O($.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)=>U$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.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?U$.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((Q)=>Q.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Q of K)if(Q.detail.clear(),X.has(Q.id))x.push(Q)}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 U$ extends A{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new U$($,O)}static from($,O){return new U$($,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?U$.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 BO extends U${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 BO($,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:{...Nx($),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:$j.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 $j.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 $j{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 $j(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 Nx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Q,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(G)=>String.fromCharCode(G)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Q?.id}}class LO extends A{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 LO($,O,void 0,j)}static from($,O,j){return new LO($,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 A{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 w("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 Ux{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Nx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return BO.byId(this.client,j.draft.db_id)}draftById($){return BO.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 BO.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)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.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 U$.byId(this.client,$)}attachment($){return WO.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 U$.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 zx{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 Ix($,O){return{chat:NO.byId($,O.id),name:O.name,announcements:O.announcements}}class NO extends A{static byId($,O){return new NO($,O)}static from($,O){return new NO($,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",($)=>$?Ix(this.client,$):void 0);added=this.mappedField("added",($)=>$?g$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?g$.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 g$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class C$ extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new C$($,O,j)}static from($,O,j){return new C$($,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",($)=>$?C$.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 A{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",($)=>$?C$.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:C$.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?C$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class g$ extends H${entityType="external_chat";static byId($,O){return new g$($,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",($)=>M.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Ix(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)=>C$.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:C$.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 Hx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>g$.byId(this.client,$.id))}byId($){return g$.byId(this.client,$)}}class Tx{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 X2({login:$,...O}){return{...O,login:$??void 0}}class Rx{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(X2),assignees:j.map(X2),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,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 F$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,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 W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.kind==="anonymous"||$.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 W$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,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)=>r$.byId(this.form,O.id)):[]}}class qj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new qj($,O)}}class y$ extends A{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,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 y$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return Y(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Y$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(Y$.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(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.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 w(`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 w(`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"},(Q)=>({kind:"group",...x(Q)})).with({kind:"condition"},(Q)=>({kind:"condition",column:j(Q.column),test:k(Q.test).with({kind:"options"},(L)=>({...L,options:L.options.map((G)=>G.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((G)=>G.id)})).with({kind:t.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??c$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(Q)=>({...X,kind:"booking",target:Q.target})).with({kind:"gate"},(Q)=>({...X,kind:"gate",rules:x(Q.rules),message:Q.message})).with({kind:"questions"},(Q)=>({...X,kind:"questions",questions:Q.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??c$(),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 w("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:t.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=E$.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}}));if($.kind==="anonymous")return{kind:"anonymous"};let O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await k(K.value).with({type:"options"},(Q)=>({type:"options",value:Q.value.map((L)=>{if(!("id"in L))throw new w("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Q)=>({type:"entities",value:Q.value.map((L)=>({entityType:L.entityType,entity:qj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Q)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new w("row answer requires a relation question");let G=V$.byId(Y$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Q.value.map((J)=>E$.byId(G,J))}}).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(Q)=>Q).exhaustive(()=>{throw new w(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?E$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{kind:"saved",...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.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:p$.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=r$.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:UO.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 Dx{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class DO extends A{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 _x(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class _x{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 Cx{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends A{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 B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class Oj{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new Oj($,O)}async claim($){let O=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Mx{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return Y(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.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(($)=>d.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:Oj.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class CO{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 CO(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 wj extends CO{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 Ax{client;constructor($){this.client=$}async generate($){let O=Y(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(E5)}}));return new wj(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function E5($){return $ instanceof f?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var q5="00000001-0000-0000-0000-000000000001",K2="00000001-0000-0000-0000-000000000002",w5="00000001-0000-0000-0000-000000000004",f5="00000001-0000-0000-0000-000000000014",b5="00000001-0000-0000-0002-000000000001",k5="00000001-0000-0000-0002-000000000004";function g5($){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 G$ extends f{static byId($,O){return new G$($,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 y5($,O)}}));return new G$($,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:M.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 G$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=g5(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new G$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===K2)?.value;return j?.type==="SelectOption"&&j.value.includes(k5)}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 G$($,O.document_id)})}async function y5($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await M.me($)],x=[{propertyId:K2,value:{type:"select_option",option_id:b5}}];if(j.length>0)x.push({propertyId:q5,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:f5,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:w5,value:{type:"date",value:O.dueDate.toISOString()}});return x}class a$ extends A{access=new $$(this.client,"initiative",this);static byId($,O){return new a$($,O)}static from($,O){return new a$($,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",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>G$.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?$O($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Px{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>a$.byId(this.client,$.id))}async summaries(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:a$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return a$.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}var v5=16000000;class fj{client;constructor($){this.client=$}async uploadProfilePicture($,O){if(($ instanceof Blob?$.size:$.byteLength)>v5)throw new w("profile picture is larger than 16 MB");let{file_id:x,upload_url:S}=Y(await this.client.auth.createProfilePictureUpload({body:{file_name:O.fileName,content_type:O.contentType}})),K=await fetch(S,{method:"PUT",headers:{"Content-Type":O.contentType},body:$});if(!K.ok)throw new w(`image upload failed with ${K.status}`);return CO.byId(this.client,x)}async update($){if($.profilePicture)Y(await this.client.auth.putProfilePictureFile({body:{file_id:$.profilePicture.id}}));let O=$.name?.trim();if(O){let[j,...x]=O.split(/\s+/);Y(await this.client.auth.putUserName({query:{first_name:j,last_name:x.join(" ")}}))}}}class Fx{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 zO extends A{async fetch(){return Y(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,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)=>zO.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",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.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 Ex{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.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 qx{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 wx{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 QO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>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 QO($,j.id,j)}static byId($,O){return new QO($,O)}static fromRecord($,O){return new QO($,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 fx{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 QO.fromRecord(this.client,x)})}create($){return QO.create(this.client,$)}definition($){return QO.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({}))}}class bx{client;constructor($){this.client=$}async link(){let $=Y(await this.client.auth.getReferralCode()),O=new URL("/app/signup",this.client.webAppUrl);return O.searchParams.set("referral_code",$),{code:$,url:O.toString()}}async invite($){let O=$.trim();if(!O)throw new w("invite needs an email address");Y(await this.client.auth.sendReferralCode({body:{recipient:O}}))}}function kx($){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 h5($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(kx)})).with({type:"cron"},kx).with({type:"events"},kx).exhaustive()}class v$ extends A{static byId($,O){return new v$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new v$($,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",($)=>M.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?v$.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 v$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...bj($),enabled:$.enabled??!0}})))}toTemplate($){return new Q2(this,M.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:bj($)}))}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)=>d.byId(this.client,O.id)).with({type:"chat"},(O)=>Q$.byId(this.client,O.id)).exhaustive();return $.chat_id?Q$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new gx(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class Q2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class gx{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 bj($){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:h5($.trigger),task:{...O}}}class yx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}async create($){return v$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...bj($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>v$.from(this.client,O))}}class vx{client;constructor($){this.client=$}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}summaries($){return G$.summaries(this.client,$)}findSimilar($){return G$.findSimilar(this.client,$)}forPullRequest($){return G$.forPullRequest(this.client,$)}search($,O){return G$.search(this.client,$,O)}}class hx{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}current(){return _$.current(this.client)}list(){return _$.list(this.client)}}class mx{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 ux{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.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:Q}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Q.map((G)=>[G.id,G]));for(let G of X){let J=L.get(G)??{id:G};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${G}`.toLocaleLowerCase().includes(O))K.push(M.fromName(this.client,J))}}return K}}class YO extends A{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",($)=>M.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 cx{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 A{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",($)=>M.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class dx{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(($)=>NO.from(this.client,$))}}function lx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function Y2($,O,j){let x=[];for(let S of lx(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:f.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:Q$.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 h$($,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:S$.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 G2="00000000-0000-0000-0000-000000000000",rx={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"]},kj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),J2=($,O)=>$==null?O:{"&":[$,O]};function px($,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==="!"){px(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)=>{px(Z,`${O}.${S}[${X}]`)})}class gj{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(rx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(rx).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)px($[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:G2}},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)=>kj(X.email_address)===kj(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=J2(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(rx))if(!x.includes(S))O[K]={l:{[Z]:G2}}}if($.tags?.length){let S=(await this.sets()).flatMap((Q)=>{let L=Q.definition;if(!L)return[];return Q.options.flatMap((G)=>G.value.type==="string"?[{id:G.id,definitionId:L.id,label:G.value.value,scope:Q.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Q of $.tags){let L=S.filter((G)=>kj(G.label)===kj(Q.label.trim())&&(!Q.scope||G.scope===Q.scope));if(!L.length)throw Error(`Unknown tag "${Q.label}". Available tags: ${S.map((G)=>`${G.label} (${G.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Q.label}" is ambiguous; specify personal or team scope.`);for(let G of L)K.set(G.id,G)}let X=[...K.values()].map((Q)=>({l:{pd:Q.definitionId,v:{so:Q.id}}})).reduce((Q,L)=>Q===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Q,L]},void 0);O.propf=J2(O.propf,X)}return O}}class ax{client;constructor($){this.client=$}async page($={}){let O=new gj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new gj(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)=>lx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>Y2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function V2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.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 dO($,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 W${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)}var X$=Symbol.for("@ts-pattern/matcher"),s1=Symbol.for("@ts-pattern/isVariadic");var d0=($)=>Boolean($&&typeof $=="object"),Lj=($)=>$&&!!$[X$],s=($,O,j)=>{if(Lj($)){let x=$[X$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(d0($)){if(!d0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Lj(X)&&X[s1]?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),Q=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,G)=>s(L,Z[G],j))&&S.every((L,G)=>s(L,X[G],j))&&(K.length===0||s(K[0],Q,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)||Lj(K=S)&&K[X$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Z$=($)=>{var O,j,x;return d0($)?Lj($)?(O=(j=(x=$[X$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?lO($,Z$):lO(Object.values($),Z$):[]},lO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function a7(...$){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 e($){return Object.assign($,{optional:()=>p0($),and:(O)=>l($,O),or:(O)=>t1($,O),select:(O)=>O===void 0?rO($):rO(O,$)})}function l0($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[s1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>l0(p0($)),select:(O)=>l0(O===void 0?rO($):rO(O,$))})}function p0($){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Z$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Z$($),matcherType:"optional"})})}var i7=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},n7=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},s7=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function l(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>lO($,Z$),matcherType:"and"})})}function t1(...$){return e({[X$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return lO($,Z$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>lO($,Z$),matcherType:"or"})})}function u($){return{[X$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function rO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return e({[X$]:()=>({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?[]:Z$(j))})})}function e1($){return!0}function w$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var o1=e(u(e1)),t7=e(u(e1)),e7=o1,s$=($)=>Object.assign(e($),{startsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(l($,((j)=>u((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(l($,(j=O,u((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),n1=s$(u(i$)),f$=($)=>Object.assign(e($),{between:(O,j)=>f$(l($,((x,S)=>u((K)=>w$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<j))(O))),gt:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>j))(O))),lte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x<=j))(O))),gte:(O)=>f$(l($,((j)=>u((x)=>w$(x)&&x>=j))(O))),int:()=>f$(l($,u((O)=>w$(O)&&Number.isInteger(O)))),finite:()=>f$(l($,u((O)=>w$(O)&&Number.isFinite(O)))),positive:()=>f$(l($,u((O)=>w$(O)&&O>0))),negative:()=>f$(l($,u((O)=>w$(O)&&O<0)))}),o7=f$(u(w$)),t$=($)=>Object.assign(e($),{between:(O,j)=>t$(l($,((x,S)=>u((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(l($,((j)=>u((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(l($,u((O)=>n$(O)&&O>0))),negative:()=>t$(l($,u((O)=>n$(O)&&O<0)))}),$5=t$(u(n$)),O5=e(u(function($){return typeof $=="boolean"})),j5=e(u(function($){return typeof $=="symbol"})),x5=e(u(function($){return $==null})),S5=e(u(function($){return $!=null})),t={__proto__:null,matcher:X$,optional:p0,array:function(...$){return l0({[X$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Z$(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?[]:Z$($[0])})})},set:function(...$){return e({[X$]:()=>({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:i7(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Z$($[0])})})},map:function(...$){return e({[X$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Q)=>{j[X]=(j[X]||[]).concat([Q])};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:n7(O,(X,Q)=>{let L=s(K,Q,x),G=s(Z,X,x);return L&&G}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},record:function(...$){return e({[X$]:()=>({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,Q)=>{x[X]=(x[X]||[]).concat([Q])},[K,Z]=$.length===1?[n1,$[0]]:$;return{matched:s7(O,(X,Q)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),G=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Q,S);return(J||G)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Z$($[0]),...Z$($[1])]})})},intersection:l,union:t1,not:function($){return e({[X$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:rO,any:o1,unknown:t7,_:e7,string:n1,number:o7,bigint:$5,boolean:O5,symbol:j5,nullish:x5,nonNullable:S5,instanceOf:function($){return e(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return e(u(a7($)))}};class $2 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 r0={matched:!1,value:void 0};function k($){return new Nj($,r0)}class Nj{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=(Q,L)=>{S=!0,K[Q]=L},X=!j.some((Q)=>s(Q,this.input,Z))||x&&!Boolean(x(this.input))?r0:{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 Nj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Nj(this.input,j?{matched:!0,value:O(this.input,this.input)}:r0)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=Z5){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function Z5($){throw new $2($)}class w extends Error{constructor($){super($);this.name="MacroError"}}var O2=500;function X5($){let O=k($).with(t.string,(j)=>j).with({message:t.string},({message:j})=>j).with({error:t.string},({error:j})=>j).otherwise(()=>"").trim();return O.length>O2?`${O.slice(0,O2)}…`:O}class e$ extends w{status;data;constructor($,O){let j=X5(O);super(j?`Macro API error ${$}: ${j}`:`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class a0 extends e${constructor($){super(403,$);this.name="MacroForbiddenError"}}function K5($,O){return $===403?new a0(O):new e$($,O)}class E extends w{constructor($){super($);this.name="MacroNotFoundError"}}function Y($){if($.error!==void 0)throw K5($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>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 A{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 K$ 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 Q5={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function o$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>Q5[x]??x);return`<${$}>${j}</${$}>`}function Y5($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var G5={toMention:()=>({tag:o$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function J5($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(Y5(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:V5(x)}}function V5($){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 B$ extends A{static byId($,O){return new B$($,O)}static from($,O){return new B$($,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 A{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",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:i0($)}))}}function i0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Q,...L}=$;return{...L,channel_ids:O?.map((G)=>G.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Q}}async function Uj($,O,j,x=[]){let{channelId:S,thread:K}=B5(O);if(await L5($)){let{id:X}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((Q)=>({entity_type:W5,entity_id:Q.id,width:Q.width??null,height:Q.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new w("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 w("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 W5="static/image";function B5($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function L5($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${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 o.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)=>o.from(this.client,this.channelId,O))}async reply($,O){let j=await Uj(this.client,this,O$($),O?.images);return o.byId(this.client,this.channelId,j)}}class o 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 o($,O,j,x)}static from($,O,j){return new o($,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 M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(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 zj{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:d.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new n0(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 n0{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return o.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return d.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 L$ extends A{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 L$($,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 b$($,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:M.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 N5=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Q=X?.searchOn??"name_content",L=X?.pageSize??N5;return c(async(G)=>{let{results:J,next_cursor:I}=Y(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Q,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...G?{cursor:G}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class GO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new GO(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 K${async recordActivity($){return new GO(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 L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return b$(this.client,{type:"channel",entity:this},(O)=>o.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new zj(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 Uj(this.client,O?.thread??this,O$($),O?.images);return o.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)=>o.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return o.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}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class M extends K${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 M($,O)}static fromName($,O){return new M($,O.id,O)}static async me($){let{user_id:O}=Y(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}async isAgent(){return(await this.detail.get()).is_agent===!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:o$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class $${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?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?IO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>IO.from(this.client,this,j))}}async request($){let{mine:O}=await this.state();return this.submit($,O?await O.revision():void 0)}async submit($,O){return IO.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:M.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 IO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new IO($,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",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function $O($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}function s0($){return $}class N$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.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 N$.fromRecord($,O,s0(S))}static async list($,O){return Y(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),s0(x)))}async fetch(){return s0(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((j)=>new t0(j,{edit:(x)=>this.decide({action:"edit",item:j.id,draft:x}),submit:()=>this.decide({action:"submit",items:[j.id]}),dismiss:()=>this.decide({action:"dismiss",items:[j.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 t0{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()}}async function Ij($,O,j,x){Y(await $.agentHarness.presentSessionView({path:{session_id:O.id},body:{view:j,executionId:x?.id??null}}))}class pO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new pO($,j,O)}async fetch(){return Y(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};views={present:($)=>Ij(this.client,this.parent,$,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 Hj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Hj($,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 aO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new aO($,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 d extends A{access=new $$(this.client,"agent_session",this);toolApprovalById($){return aO.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:$O($)}))}webUrl(){return`${this.client.webAppUrl}/app/agent/${this.id}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}static byId($,O){return new d($,O)}static async createManaged($,O){let{session:j}=Y(await $.agentHarness.createAgentSession({body:{botId:O?.agent?.id,prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new d($,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");archivedBy=this.field("archivedBy");archivedAt=this.field("archivedAt");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)=>d.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?M.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 autoArchive(){let{overrides:$,defaults:O,autoArchivedAt:j}=Y(await this.client.agentHarness.getAgentSessionAutoArchive({path:{session_id:this.id}}));return{overrides:{onPullRequestMerged:$.onPullRequestMerged??void 0,onRuntimeClosed:$.onRuntimeClosed??void 0},defaults:O,autoArchivedAt:j??void 0}}async setAutoArchive($){Y(await this.client.agentHarness.putAgentSessionAutoArchive({path:{session_id:this.id},body:{onPullRequestMerged:$.onPullRequestMerged??null,onRuntimeClosed:$.onRuntimeClosed??null}}))}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:{archived:$}}))}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 autoArchivePreferences($){return Y(await $.agentHarness.getAgentAutoArchivePreferences())}static async setAutoArchivePreferences($,O){return Y(await $.agentHarness.putAgentAutoArchivePreferences({body:O}))}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)=>Hj.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:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};views={present:($)=>Ij(this.client,this,$)};codeExecutions={byId:($)=>pO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class e0{client;constructor($){this.client=$}byId($){return d.byId(this.client,$)}createManaged($){return d.createManaged(this.client,$)}chooseMode($){return d.chooseMode(this.client,$)}repositories(){return d.repositories(this.client)}repositoryBranches($){return d.repositoryBranches(this.client,$)}forPullRequest($){return d.forPullRequest(this.client,$)}defaultSandboxSize(){return d.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return d.setDefaultSandboxSize(this.client,$)}codingPreferences(){return d.codingPreferences(this.client)}autoArchivePreferences(){return d.autoArchivePreferences(this.client)}setAutoArchivePreferences($){return d.setAutoArchivePreferences(this.client,$)}setCodingPreferences($){return d.setCodingPreferences(this.client,$)}}class o0{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:i0($)})))}}class $x{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 OO extends A{static byId($,O){return new OO($,O)}static from($,O){return new OO($,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 Ox{client;constructor($){this.client=$}byId($){return OO.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>OO.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:OO.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class iO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new w("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 w("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 w("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class R$ extends A{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 m$ extends A{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 m$($,O)}static async list($){let{calendars:O}=Y(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class nO{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 S$ extends A{async fetch(){throw new w(`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 S$($,O)}static fromRecord($,O){return new S$($,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",($)=>$?m$.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:U5($)}));return S$.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 nO(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 S$.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 S$.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 S$.fromRecord(this.client,O)}}function U5($){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 jx{client;async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.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??=I5(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:S$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:j2(K.event,S),inbox:Z?.emailAddress,role:H5(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.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:S$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return S$.byId(this.client,$)}replacement($){return new nO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:z5($)}));return S$.fromRecord(this.client,O)}}function z5($){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 I5($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function j2($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function H5($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&j2($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends A{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 u$ extends A{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 u$($,O,j)}static from($,O,j){return new u$($,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 M.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 u$.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 L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return b$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new $$(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}}))}webUrl(){return`${this.client.webAppUrl}/app/call/${this.id}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}static byId($,O){return new J$($,O)}message($){return u$.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",($)=>M.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 xx{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class Sx{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}}))}}var T5=100;class Zx{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new GO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new Sx($)}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(){for await(let $ of this.records())yield b.byId(this.client,$.id)}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let j=$.toLowerCase();for await(let x of this.records())if(x.name?.toLowerCase().includes(j))yield b.byId(this.client,x.id)}else yield*b.search(this.client,$,O)}records(){return c(async($)=>{let O=Y(await this.client.storage.getChannels({query:{limit:T5,...$?{cursor:$}:{}}}));return{items:O.items,nextCursor:O.next_cursor}})}}class n extends K${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 $$(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}webUrl(){return`${this.client.webAppUrl}/app/project/${this.id}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}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 sO{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 sO($,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 tO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new tO($,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 Q$ extends K${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=Q$.byId(this.client,S.chat_id);return sO.byId(this.client,K,S.stream_id,tO.byId(this.client,K,S.message_id))}access=new $$(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 Q$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Q$($,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 Q$(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}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Q$($,O.chat_id)});toMention(){return{tag:o$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class Xx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class HO extends A{static byId($,O){return new HO($,O)}static from($,O){return new HO($,O.id,O)}async fetch(){let $=Y(await this.client.auth.getTeamInvites()).invites.find((O)=>O.id===this.id);if(!$)throw new E(`team invite ${this.id} not found`);return $}email=this.field("email");role=this.field("team_role");invitedBy=this.mappedField("invited_by",($)=>M.byId(this.client,$));createdAt=this.field("created_at");lastSentAt=this.field("last_sent_at");async revoke(){await this.mutate(($)=>$.auth.deleteTeamInviteHandler({path:{team_invite_id:this.id}}))}}class _$ extends A{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 _$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O?.team)throw new E("caller has no current team");return new _$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new _$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){return(await this.requireCurrent("members")).members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}async invite($,O){let j=[],x=new Set;for(let K of typeof $==="string"?[$]:$){let Z=K.trim(),X=Z.toLowerCase();if(Z&&!x.has(X))x.add(X),j.push(Z)}if(j.length===0)throw new w("invite needs at least one email address");let S=await this.client.auth.inviteToTeam({body:{invites:j.map((K)=>({email:K})),team_id:this.id,...O?.agent&&{is_agent:!0}}});if(S.response?.status===304)return!1;return Y(S),!0}async invites(){return Y(await this.client.auth.getTeamInvites({query:{team_id:this.id}})).invites.map(($)=>HO.from(this.client,$))}async requireCurrent($){let O=Y(await this.client.auth.getTeam());if(!O?.team||O.team.id!==this.id)throw new w(`${$} are only available for the current team (see Team.current)`);return O}}var R5=8;class A$ extends A{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 A$($,O,j)}static from($,O,j){return new A$($,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 M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return eO(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 Tj($,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 dO(S,R5,async(K)=>{let{state:Z,root:X,replies:Q}=Y(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Q].map((L)=>A$.from($,O,L))}})}async function eO($,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 A$.from($,O,S)}class P$ extends H${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_contact",entity:this},(O)=>A$.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 P$($,O)}static from($,O){return new P$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>$?k$.byId(this.client,$):void 0);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 Tj(this.client,this.commentParent)}async comment($,O){return eO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class k$ extends K${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return b$(this.client,{type:"crm_company",entity:this},(O)=>A$.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 k$($,O)}static from($,O){return new k$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>_$.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)=>P$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new k$($,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 P$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Tj(this.client,this.commentParent)}async comment($,O){return eO(this.client,this.commentParent,$,O)}commentById($){return A$.byId(this.client,this.commentParent,$)}}class jO extends A{tableDetail=new W$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new jO($,O)}static from($,O){return new jO($,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",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>_$.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:$O($)}))}async table(){return Rj.from(this.client,this,await this.tableRecord())}async viewPositions($){if($.table.pipeline.id!==this.id)throw Error("View belongs to another pipeline");return Y(await this.client.storage.getCrmPipelineViewPositions({path:{id:this.id,view:$.id}}))}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)=>JO.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)=>JO.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 Rj extends A{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 Rj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>_j.from(this.client,this,$))}async views(){return(await this.pipeline.tableRecord()).views.map(($)=>Dj.byId(this,$.id))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return JO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let $=(await this.table.pipeline.tableRecord()).views.find((O)=>O.id===this.id);if(!$)throw new E(`view ${this.id} is not on table ${this.table.id}`);return $}positions(){return this.table.pipeline.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id,pipelineId:this.table.pipeline.id}}}class JO extends A{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 JO($,O,j)}static from($,O,j){return new JO($,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 _j extends A{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 _j($,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 Kx{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>jO.from(this.client,$))}async create($){return jO.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class Qx{client;pipelines;constructor($){this.client=$;this.pipelines=new Kx($)}companyById($){return k$.byId(this.client,$)}contactById($){return P$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?P$.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)=>P$.from(this.client,x))}async createCompany($){return k$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async createContact($){return P$.from(this.client,Y(await this.client.storage.createCrmTeamContact({body:$})))}async blockedDomains(){return Y(await this.client.storage.listCrmBlockedDomains()).map(($)=>$.domain)}async blockDomain($){Y(await this.client.storage.blockCrmDomain({path:{domain:$}}))}async unblockDomain($){Y(await this.client.storage.unblockCrmDomain({path:{domain:$}}))}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 k$.search(this.client,$)}}var Yx,D5=new Uint8Array(16);function Cj(){if(!Yx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Yx=crypto.getRandomValues.bind(crypto)}return Yx(D5)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function x2($,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 Gx={};function _5($,O,j){let x;if($)x=S2($.random??$.rng?.()??Cj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Cj();C5(Gx,S,K),x=S2(K,Gx.msecs,Gx.seq,O,j)}return O??x2(x)}function C5($,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 S2($,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 c$=_5;class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,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 E${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new E$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Mj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Mj($,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)=>F$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return E$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Mj.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 Aj($,O,j,x={}){let S=Y(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:G,version:J})=>[G.id,J]))}})),K=new Map;for(let G of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!G)continue;let J=K.get(G.id);if(J)J.add(G);else K.set(G.id,new Set([G]))}let Z=(G)=>{let J=K.get(G)?.values().next().value;if(J)return J;let I=O($,G);return K.set(G,new Set([I])),I},X=(G)=>{let J=S.tableDatabases[G];if(!J)throw Error(`SQL response is missing the owner of table ${G}`);return V$.byId(Z(J),G)},Q=new Set(Object.keys(S.newVersions).map((G)=>X(G).database.id));if(S.statement.kind==="schema")Q.add(S.statement.databaseId);for(let G of Q)for(let J of K.get(G)??[])J.invalidateSchema();let L=k(S.statement).with({kind:"select"},(G)=>G).with({kind:"schema"},({databaseId:G,summary:J})=>({kind:"schema",database:Z(G),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:G,tableId:J,tableName:I})=>({kind:G,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:G,tableName:J,columnId:I,columnName:z,to:W})=>{let V=X(G);return{kind:"alterColumnType",table:V,tableName:J,column:F$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?M5(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((G)=>E$.byId(L.table,G)):[],newVersions:Object.entries(S.newVersions).map(([G,J])=>({table:X(G),version:J})),readVersions:Object.entries(S.readVersions).map(([G,J])=>({table:X(G),version:J})),truncatedTables:S.truncatedTables,statement:L}}function M5($,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)=>E$.byId(x,S)):[]}}class Pj{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 Pj($,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 Wx extends e${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 Fj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:t.not("relation")},(O)=>O).exhaustive()}var A5={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 P5($){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})=>A5[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Jx($){return $.map((O)=>({id:c$(),label:O}))}function Z2($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Vx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:t.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function d$($,O,j){let[x]=$;if($.length!==1||!Z2(x,O,j))throw new w(`expected one ${O}.${j} result, got ${$.map(Vx).join(", ")||"none"}`);return x}class Y$ extends A{access=new $$(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 w(`${$} does not belong to database ${this.id}`)}webUrl(){return`${this.client.webAppUrl}/app/database/${this.id}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}static byId($,O){return new Y$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new Y$($,j.id)}async duplicate($){let O=Y(await this.client.storage.duplicateDatabase({path:{id:this.id},body:{name:$?.name}}));return new Y$(this.client,O.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new Y$($,j.database.id))}query($,O){return Aj(this.client,Y$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.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}=d$(await this.applyOps([{kind:"table",table:c$(),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 Wx(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 w(`expected one reorder_tables result, got ${O.map(Vx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),d$(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 Pj.fromRecord(V$.byId(this,$.tableId),M.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 d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Fj(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:Fj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${P5(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Fj(O.to),options:Jx(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:Q})=>({row:X,cells:[{column:S,value:Q}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!Z2(Z,"column","created"))throw new w(`expected a column.created result, got ${Z?Vx(Z):"none"}`);return F$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=d$(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 w(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=d$(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 w(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new w(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=d$(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 w(`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:Fj(O.type),...O.options!==void 0?{options:Jx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=d$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return F$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Jx(O)}}]),"column","options_added")}}class Bx{client;constructor($){this.client=$}query($,O){return Aj(this.client,Y$.byId,$,O)}byId($){return Y$.byId(this.client,$)}create($){return Y$.create(this.client,$)}list(){return Y$.list(this.client)}}class VO extends A{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 l$ extends A{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 l$($,O,j)}static from($,O,j){return new l$($,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 f.byId(this.client,this.documentId)}async author(){return M.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 oO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>Y(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new oO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var F5=8;class f extends K${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 oO.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 L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return b$(this.client,{type:"document",entity:this},(O)=>l$.from(this.client,this.id,O),$)}access=new $$(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 f($,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 f($,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 f($,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 f($,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 f($,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 f($,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",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?f.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 e$(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 f(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 dO(j,F5,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)=>l$.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 l$.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}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new f($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:o$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Ej{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Ej(j.id,j.name))}}class Lx{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 f.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=Y(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:f.byId(this.client,O.document_id),user:O.user_id?M.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:f.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return f.byId(this.client,$)}create($){return f.create(this.client,$)}async createCanvas($){let O=Y(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return f.byId(this.client,O.documentId)}createSnippet($){return f.createSnippet(this.client,$)}createSkill($){return f.createSkill(this.client,$)}systemSkills(){return Ej.list(this.client)}search($,O){return f.search(this.client,$,O)}recent($){return f.recent(this.client,$)}recentlyDeleted(){return f.recentlyDeleted(this.client)}}class WO extends A{async fetch(){let{attachment:$}=Y(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,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 f.byId(this.client,$)}}class z$ extends K${access=new $$(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 S$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=Y(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:U$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}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?$O($.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 $}webUrl(){return`${this.client.webAppUrl}/app/mail/${this.id}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}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)=>U$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.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?U$.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((Q)=>Q.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Q of K)if(Q.detail.clear(),X.has(Q.id))x.push(Q)}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 U$ extends A{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new U$($,O)}static from($,O){return new U$($,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?U$.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 BO extends U${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 BO($,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:{...Nx($),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:$j.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 $j.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 $j{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 $j(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 Nx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Q,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(G)=>String.fromCharCode(G)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Q?.id}}class LO extends A{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 LO($,O,void 0,j)}static from($,O,j){return new LO($,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 A{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 w("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 Ux{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Nx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return BO.byId(this.client,j.draft.db_id)}draftById($){return BO.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 BO.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)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.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 U$.byId(this.client,$)}attachment($){return WO.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 U$.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 zx{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 Ix($,O){return{chat:NO.byId($,O.id),name:O.name,announcements:O.announcements}}class NO extends A{static byId($,O){return new NO($,O)}static from($,O){return new NO($,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",($)=>$?Ix(this.client,$):void 0);added=this.mappedField("added",($)=>$?g$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?g$.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 g$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class C$ extends A{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new C$($,O,j)}static from($,O,j){return new C$($,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",($)=>$?C$.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 A{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",($)=>$?C$.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:C$.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?C$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class g$ extends H${entityType="external_chat";static byId($,O){return new g$($,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",($)=>M.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Ix(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)=>C$.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:C$.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 Hx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>g$.byId(this.client,$.id))}byId($){return g$.byId(this.client,$)}}class Tx{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 X2({login:$,...O}){return{...O,login:$??void 0}}class Rx{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(X2),assignees:j.map(X2),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,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 F$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,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 W$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.kind==="anonymous"||$.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 W$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,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)=>r$.byId(this.form,O.id)):[]}}class qj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new qj($,O)}}class y$ extends A{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,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 y$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return Y(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Y$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(Y$.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(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.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 w(`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 w(`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"},(Q)=>({kind:"group",...x(Q)})).with({kind:"condition"},(Q)=>({kind:"condition",column:j(Q.column),test:k(Q.test).with({kind:"options"},(L)=>({...L,options:L.options.map((G)=>G.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((G)=>G.id)})).with({kind:t.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??c$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(Q)=>({...X,kind:"booking",target:Q.target})).with({kind:"gate"},(Q)=>({...X,kind:"gate",rules:x(Q.rules),message:Q.message})).with({kind:"questions"},(Q)=>({...X,kind:"questions",questions:Q.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??c$(),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 w("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:t.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=E$.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}}));if($.kind==="anonymous")return{kind:"anonymous"};let O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await k(K.value).with({type:"options"},(Q)=>({type:"options",value:Q.value.map((L)=>{if(!("id"in L))throw new w("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Q)=>({type:"entities",value:Q.value.map((L)=>({entityType:L.entityType,entity:qj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Q)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new w("row answer requires a relation question");let G=V$.byId(Y$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Q.value.map((J)=>E$.byId(G,J))}}).with({type:t.union("text","number","boolean","date","date_range","link","clear")},(Q)=>Q).exhaustive(()=>{throw new w(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?E$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{kind:"saved",...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.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:p$.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=r$.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:UO.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}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Dx{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class DO extends A{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 _x(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class _x{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 Cx{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends A{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 B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class Oj{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new Oj($,O)}async claim($){let O=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Mx{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return Y(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.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(($)=>d.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:Oj.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class CO{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 CO(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 wj extends CO{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 Ax{client;constructor($){this.client=$}async generate($){let O=Y(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(E5)}}));return new wj(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function E5($){return $ instanceof f?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var q5="00000001-0000-0000-0000-000000000001",K2="00000001-0000-0000-0000-000000000002",w5="00000001-0000-0000-0000-000000000004",f5="00000001-0000-0000-0000-000000000014",b5="00000001-0000-0000-0002-000000000001",k5="00000001-0000-0000-0002-000000000004";function g5($){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 G$ extends f{static byId($,O){return new G$($,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 y5($,O)}}));return new G$($,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:M.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 G$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=g5(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new G$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===K2)?.value;return j?.type==="SelectOption"&&j.value.includes(k5)}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 G$($,O.document_id)})}async function y5($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await M.me($)],x=[{propertyId:K2,value:{type:"select_option",option_id:b5}}];if(j.length>0)x.push({propertyId:q5,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:f5,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:w5,value:{type:"date",value:O.dueDate.toISOString()}});return x}class a$ extends A{access=new $$(this.client,"initiative",this);webUrl(){return`${this.client.webAppUrl}/app/initiative/${this.id}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}static byId($,O){return new a$($,O)}static from($,O){return new a$($,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",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>G$.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?$O($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Px{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>a$.byId(this.client,$.id))}async summaries(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:a$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return a$.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}var v5=16000000;class fj{client;constructor($){this.client=$}async uploadProfilePicture($,O){if(($ instanceof Blob?$.size:$.byteLength)>v5)throw new w("profile picture is larger than 16 MB");let{file_id:x,upload_url:S}=Y(await this.client.auth.createProfilePictureUpload({body:{file_name:O.fileName,content_type:O.contentType}})),K=await fetch(S,{method:"PUT",headers:{"Content-Type":O.contentType},body:$});if(!K.ok)throw new w(`image upload failed with ${K.status}`);return CO.byId(this.client,x)}async update($){if($.profilePicture)Y(await this.client.auth.putProfilePictureFile({body:{file_id:$.profilePicture.id}}));let O=$.name?.trim();if(O){let[j,...x]=O.split(/\s+/);Y(await this.client.auth.putUserName({query:{first_name:j,last_name:x.join(" ")}}))}}}class Fx{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 zO extends A{async fetch(){return Y(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,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)=>zO.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",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.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 Ex{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.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 qx{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 wx{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 QO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>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 QO($,j.id,j)}static byId($,O){return new QO($,O)}static fromRecord($,O){return new QO($,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 fx{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 QO.fromRecord(this.client,x)})}create($){return QO.create(this.client,$)}definition($){return QO.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({}))}}class bx{client;constructor($){this.client=$}async link(){let $=Y(await this.client.auth.getReferralCode()),O=new URL("/app/signup",this.client.webAppUrl);return O.searchParams.set("referral_code",$),{code:$,url:O.toString()}}async invite($){let O=$.trim();if(!O)throw new w("invite needs an email address");Y(await this.client.auth.sendReferralCode({body:{recipient:O}}))}}function kx($){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 h5($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(kx)})).with({type:"cron"},kx).with({type:"events"},kx).exhaustive()}class v$ extends A{webUrl(){return`${this.client.webAppUrl}/app/routines/${this.id}`}toJSON(){return{...super.toJSON(),url:this.webUrl()}}static byId($,O){return new v$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new v$($,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",($)=>M.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?v$.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 v$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...bj($),enabled:$.enabled??!0}})))}toTemplate($){return new Q2(this,M.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:bj($)}))}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)=>d.byId(this.client,O.id)).with({type:"chat"},(O)=>Q$.byId(this.client,O.id)).exhaustive();return $.chat_id?Q$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new gx(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class Q2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class gx{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 bj($){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:h5($.trigger),task:{...O}}}class yx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}async create($){return v$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...bj($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>v$.from(this.client,O))}}class vx{client;constructor($){this.client=$}byId($){return G$.byId(this.client,$)}create($){return G$.create(this.client,$)}summaries($){return G$.summaries(this.client,$)}findSimilar($){return G$.findSimilar(this.client,$)}forPullRequest($){return G$.forPullRequest(this.client,$)}search($,O){return G$.search(this.client,$,O)}}class hx{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}current(){return _$.current(this.client)}list(){return _$.list(this.client)}}class mx{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 ux{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.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:Q}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Q.map((G)=>[G.id,G]));for(let G of X){let J=L.get(G)??{id:G};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${G}`.toLocaleLowerCase().includes(O))K.push(M.fromName(this.client,J))}}return K}}class YO extends A{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",($)=>M.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 cx{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 A{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",($)=>M.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class dx{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(($)=>NO.from(this.client,$))}}function lx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function Y2($,O,j){let x=[];for(let S of lx(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:f.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:Q$.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 h$($,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:S$.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 G2="00000000-0000-0000-0000-000000000000",rx={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"]},kj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),J2=($,O)=>$==null?O:{"&":[$,O]};function px($,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==="!"){px(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)=>{px(Z,`${O}.${S}[${X}]`)})}class gj{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(rx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(rx).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)px($[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:G2}},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)=>kj(X.email_address)===kj(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=J2(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(rx))if(!x.includes(S))O[K]={l:{[Z]:G2}}}if($.tags?.length){let S=(await this.sets()).flatMap((Q)=>{let L=Q.definition;if(!L)return[];return Q.options.flatMap((G)=>G.value.type==="string"?[{id:G.id,definitionId:L.id,label:G.value.value,scope:Q.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Q of $.tags){let L=S.filter((G)=>kj(G.label)===kj(Q.label.trim())&&(!Q.scope||G.scope===Q.scope));if(!L.length)throw Error(`Unknown tag "${Q.label}". Available tags: ${S.map((G)=>`${G.label} (${G.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Q.label}" is ambiguous; specify personal or team scope.`);for(let G of L)K.set(G.id,G)}let X=[...K.values()].map((Q)=>({l:{pd:Q.definitionId,v:{so:Q.id}}})).reduce((Q,L)=>Q===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Q,L]},void 0);O.propf=J2(O.propf,X)}return O}}class ax{client;constructor($){this.client=$}async page($={}){let O=new gj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new gj(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)=>lx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>Y2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function V2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Q,url:L,...G}){let J,I=Q??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=G.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=G.headers instanceof Headers?G.headers:new Headers(G.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...G,body:G.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(G.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/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/classes/AgentSession.md b/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/classes/AgentSession.mdindex 7eb769d73c..19977f16dc 100644--- a/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/classes/AgentSession.md+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/classes/AgentSession.md@@ -295,18 +295,21 @@ Sharing configuration.### toJSON()-> **toJSON**(): \{ `detail?`: [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md); `id`: `string`; \}+\{ `detail?`: [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)@@ -379,6 +382,18 @@ Replace sharing grants.***+### webUrl()++> **webUrl**(): `string`++The session's URL in the Macro web app; hand it to users as the link.++#### Returns++`string`++***+### autoArchivePreferences()> `static` **autoArchivePreferences**(`client`): `Promise`\<[`AutoArchivePreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/AutoArchivePreferencesBody.md)\>diff --git a/packages/sdk-docs/reference/src/entities/calls/call-record/classes/CallRecord.md b/packages/sdk-docs/reference/src/entities/calls/call-record/classes/CallRecord.mdindex d28f6fb424..e9a1270b62 100644--- a/packages/sdk-docs/reference/src/entities/calls/call-record/classes/CallRecord.md+++ b/packages/sdk-docs/reference/src/entities/calls/call-record/classes/CallRecord.md@@ -219,18 +219,21 @@ Toggle the server's share-with-team setting and return its new value.### toJSON()-> **toJSON**(): \{ `detail?`: [`CallRecord`](../../../../../generated/storage/types.gen/type-aliases/CallRecord.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`CallRecord`](../../../../../generated/storage/types.gen/type-aliases/CallRecord.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`CallRecord`](../../../../../generated/storage/types.gen/type-aliases/CallRecord.md); `id`: `string`; \}+\{ `detail?`: [`CallRecord`](../../../../../generated/storage/types.gen/type-aliases/CallRecord.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`CallRecord`](../../../../../generated/storage/types.gen/type-aliases/CallRecord.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`toJSON`](../../../entity/classes/FavoritableEntity.md#tojson)@@ -252,6 +255,18 @@ Remove this entity from the user's favorites. Returns this handle for chaining.***+### webUrl()++> **webUrl**(): `string`++The call's URL in the Macro web app; hand it to users as the link.++#### Returns++`string`++***+### byId()> `static` **byId**(`client`, `id`): `CallRecord`diff --git a/packages/sdk-docs/reference/src/entities/channels/channel/classes/Channel.md b/packages/sdk-docs/reference/src/entities/channels/channel/classes/Channel.mdindex 829354f26e..a03383a634 100644--- a/packages/sdk-docs/reference/src/entities/channels/channel/classes/Channel.md+++ b/packages/sdk-docs/reference/src/entities/channels/channel/classes/Channel.md@@ -442,18 +442,21 @@ A mixed message and activity timeline page.### toJSON()-> **toJSON**(): \{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \}+\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)diff --git a/packages/sdk-docs/reference/src/entities/chats/chat/classes/Chat.md b/packages/sdk-docs/reference/src/entities/chats/chat/classes/Chat.mdindex 66288f6e99..01befa683a 100644--- a/packages/sdk-docs/reference/src/entities/chats/chat/classes/Chat.md+++ b/packages/sdk-docs/reference/src/entities/chats/chat/classes/Chat.md@@ -240,18 +240,21 @@ value when `value` is omitted.### toJSON()-> **toJSON**(): \{ `detail?`: [`ChatResponse`](../../../../../generated/cognition/types.gen/type-aliases/ChatResponse.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`ChatResponse`](../../../../../generated/cognition/types.gen/type-aliases/ChatResponse.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`ChatResponse`](../../../../../generated/cognition/types.gen/type-aliases/ChatResponse.md); `id`: `string`; \}+\{ `detail?`: [`ChatResponse`](../../../../../generated/cognition/types.gen/type-aliases/ChatResponse.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`ChatResponse`](../../../../../generated/cognition/types.gen/type-aliases/ChatResponse.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)diff --git a/packages/sdk-docs/reference/src/entities/databases/database/classes/Database.md b/packages/sdk-docs/reference/src/entities/databases/database/classes/Database.mdindex f63f6f0a2b..fc6a33b1a4 100644--- a/packages/sdk-docs/reference/src/entities/databases/database/classes/Database.md+++ b/packages/sdk-docs/reference/src/entities/databases/database/classes/Database.md@@ -496,18 +496,21 @@ The table with the given display name, or `undefined` if there is none.### toJSON()-> **toJSON**(): \{ `detail?`: [`DatabaseDetail`](../../../../../generated/storage/types.gen/type-aliases/DatabaseDetail.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`DatabaseDetail`](../../../../../generated/storage/types.gen/type-aliases/DatabaseDetail.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`DatabaseDetail`](../../../../../generated/storage/types.gen/type-aliases/DatabaseDetail.md); `id`: `string`; \}+\{ `detail?`: [`DatabaseDetail`](../../../../../generated/storage/types.gen/type-aliases/DatabaseDetail.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`DatabaseDetail`](../../../../../generated/storage/types.gen/type-aliases/DatabaseDetail.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)@@ -561,6 +564,18 @@ The database's webhooks, oldest first. Takes edit access.***+### webUrl()++> **webUrl**(): `string`++The database's URL in the Macro web app; hand it to users as the link.++#### Returns++`string`++***+### byId()> `static` **byId**(`client`, `id`): `Database`diff --git a/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md b/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.mdindex e18c21a1b9..8c313c35c5 100644--- a/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md+++ b/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md@@ -496,18 +496,21 @@ A mixed message and activity timeline page.### toJSON()-> **toJSON**(): \{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \}+\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)diff --git a/packages/sdk-docs/reference/src/entities/email/thread/classes/EmailThread.md b/packages/sdk-docs/reference/src/entities/email/thread/classes/EmailThread.mdindex cce12804b8..264d8178cc 100644--- a/packages/sdk-docs/reference/src/entities/email/thread/classes/EmailThread.md+++ b/packages/sdk-docs/reference/src/entities/email/thread/classes/EmailThread.md@@ -409,18 +409,21 @@ The thread's subject, from its first message with one.### toJSON()-> **toJSON**(): \{ `detail?`: [`ApiThread`](../../../../../generated/email/types.gen/type-aliases/ApiThread.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`ApiThread`](../../../../../generated/email/types.gen/type-aliases/ApiThread.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`ApiThread`](../../../../../generated/email/types.gen/type-aliases/ApiThread.md); `id`: `string`; \}+\{ `detail?`: [`ApiThread`](../../../../../generated/email/types.gen/type-aliases/ApiThread.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`ApiThread`](../../../../../generated/email/types.gen/type-aliases/ApiThread.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)@@ -502,6 +505,18 @@ Update provider-neutral read, trash, spam, or star state.***+### webUrl()++> **webUrl**(): `string`++The thread's URL in the Macro web app; hand it to users as the link.++#### Returns++`string`++***+### archiveMany()> `static` **archiveMany**(`client`, `threads`, `archived?`): `Promise`\<`EmailThread`[]\>diff --git a/packages/sdk-docs/reference/src/entities/forms/form/classes/Form.md b/packages/sdk-docs/reference/src/entities/forms/form/classes/Form.mdindex 5f974aa56b..f0845ac7c8 100644--- a/packages/sdk-docs/reference/src/entities/forms/form/classes/Form.md+++ b/packages/sdk-docs/reference/src/entities/forms/form/classes/Form.md@@ -179,18 +179,21 @@ Choice and checkbox counts, available to viewers when tally visibility is enable### toJSON()-> **toJSON**(): \{ `detail?`: [`FormDetail`](../../../../../generated/storage/types.gen/type-aliases/FormDetail.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`FormDetail`](../../../../../generated/storage/types.gen/type-aliases/FormDetail.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`FormDetail`](../../../../../generated/storage/types.gen/type-aliases/FormDetail.md); `id`: `string`; \}+\{ `detail?`: [`FormDetail`](../../../../../generated/storage/types.gen/type-aliases/FormDetail.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`FormDetail`](../../../../../generated/storage/types.gen/type-aliases/FormDetail.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)diff --git a/packages/sdk-docs/reference/src/entities/initiatives/initiative/classes/Initiative.md b/packages/sdk-docs/reference/src/entities/initiatives/initiative/classes/Initiative.mdindex b737d238b2..6e40bcadbd 100644--- a/packages/sdk-docs/reference/src/entities/initiatives/initiative/classes/Initiative.md+++ b/packages/sdk-docs/reference/src/entities/initiatives/initiative/classes/Initiative.md@@ -35,18 +35,21 @@ Delete this initiative.### toJSON()-> **toJSON**(): \{ `detail?`: [`InitiativeDetail`](../../../../../generated/storage/types.gen/type-aliases/InitiativeDetail.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`InitiativeDetail`](../../../../../generated/storage/types.gen/type-aliases/InitiativeDetail.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`InitiativeDetail`](../../../../../generated/storage/types.gen/type-aliases/InitiativeDetail.md); `id`: `string`; \}+\{ `detail?`: [`InitiativeDetail`](../../../../../generated/storage/types.gen/type-aliases/InitiativeDetail.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`InitiativeDetail`](../../../../../generated/storage/types.gen/type-aliases/InitiativeDetail.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)@@ -73,6 +76,18 @@ Update the name, membership or sharing configuration.***+### webUrl()++> **webUrl**(): `string`++The initiative's URL in the Macro web app; hand it to users as the link.++#### Returns++`string`++***+### byId()> `static` **byId**(`client`, `id`): `Initiative`diff --git a/packages/sdk-docs/reference/src/entities/projects/project/classes/Project.md b/packages/sdk-docs/reference/src/entities/projects/project/classes/Project.mdindex d12f2bdd3d..ac00824d7d 100644--- a/packages/sdk-docs/reference/src/entities/projects/project/classes/Project.md+++ b/packages/sdk-docs/reference/src/entities/projects/project/classes/Project.md@@ -227,18 +227,21 @@ Read this project's sharing configuration.### toJSON()-> **toJSON**(): \{ `detail?`: [`Project`](../../../../../generated/storage/types.gen/type-aliases/Project.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`Project`](../../../../../generated/storage/types.gen/type-aliases/Project.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`Project`](../../../../../generated/storage/types.gen/type-aliases/Project.md); `id`: `string`; \}+\{ `detail?`: [`Project`](../../../../../generated/storage/types.gen/type-aliases/Project.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`Project`](../../../../../generated/storage/types.gen/type-aliases/Project.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)@@ -282,6 +285,18 @@ Apply multi-select option deltas atomically across this entity's properties.***+### webUrl()++> **webUrl**(): `string`++The project's URL in the Macro web app; hand it to users as the link.++#### Returns++`string`++***+### byId()> `static` **byId**(`client`, `id`): `Project`diff --git a/packages/sdk-docs/reference/src/entities/routines/routine/classes/Routine.md b/packages/sdk-docs/reference/src/entities/routines/routine/classes/Routine.mdindex 82253b905d..d91ef1cb53 100644--- a/packages/sdk-docs/reference/src/entities/routines/routine/classes/Routine.md+++ b/packages/sdk-docs/reference/src/entities/routines/routine/classes/Routine.md@@ -142,18 +142,21 @@ This routine's shared template, or `undefined` when it isn't shared.### toJSON()-> **toJSON**(): \{ `detail?`: [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md); `id`: `string`; \}+\{ `detail?`: [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md) || `id` | `string` |+| `url` | `string` |-#### Inherited from+#### Overrides[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)@@ -177,6 +180,18 @@ Replace the routine's task and trigger configuration.***+### webUrl()++> **webUrl**(): `string`++The routine's URL in the Macro web app; hand it to users as the link.++#### Returns++`string`++***+### byId()> `static` **byId**(`client`, `id`): `Routine`diff --git a/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md b/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.mdindex b2f580a403..f98c265e75 100644--- a/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md+++ b/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md@@ -590,16 +590,19 @@ A mixed message and activity timeline page.### toJSON()-> **toJSON**(): \{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \}+> **toJSON**(): \{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; `url`: `string`; \}++Identity, loaded detail and [webUrl](../../../documents/document/classes/Document.md#weburl), so serialized handles carry their link.#### Returns-\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; \}+\{ `detail?`: [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md); `id`: `string`; `url`: `string`; \}| Name | Type || ------ | ------ || `detail?` | [`DocumentMetadataWithContent`](../../../../../generated/storage/types.gen/type-aliases/DocumentMetadataWithContent.md) || `id` | `string` |+| `url` | `string` |#### Inherited fromdiff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.tsindex 61ced8cecb..699c00f04d 100644--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts@@ -157,6 +157,16 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {);}+ /** The session's URL in the Macro web app; hand it to users as the link. */+ webUrl(): string {+ return `${this.client.webAppUrl}/app/agent/${this.id}`;+ }++ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** A handle to an agent session by id. Details load on first access. */static byId(client: MacroClient, id: string): AgentSession {return new AgentSession(client, id);diff --git a/packages/sdk/src/entities/calls/call-record.ts b/packages/sdk/src/entities/calls/call-record.tsindex dc960a760e..b25a88bd60 100644--- a/packages/sdk/src/entities/calls/call-record.ts+++ b/packages/sdk/src/entities/calls/call-record.ts@@ -77,6 +77,16 @@ export class CallRecord extends FavoritableEntity<CallRecordDetail> {);}+ /** The call's URL in the Macro web app; hand it to users as the link. */+ webUrl(): string {+ return `${this.client.webAppUrl}/app/call/${this.id}`;+ }++ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** A handle to a call record by id. Details load on first access. */static byId(client: MacroClient, id: string): CallRecord {return new CallRecord(client, id);diff --git a/packages/sdk/src/entities/channels/channel.ts b/packages/sdk/src/entities/channels/channel.tsindex 9c6aa240bd..b0cc8bfcde 100644--- a/packages/sdk/src/entities/channels/channel.ts+++ b/packages/sdk/src/entities/channels/channel.ts@@ -339,6 +339,11 @@ export class Channel extends PropertiedEntity<ChannelDetail> {return `${this.client.webAppUrl}/app/channel/${this.id}`;}+ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** Search channels by content, most relevant first, auto-paginated. */static search = entitySearch({type: 'channel',diff --git a/packages/sdk/src/entities/chats/chat.ts b/packages/sdk/src/entities/chats/chat.tsindex 7aa40230f0..a5137721fa 100644--- a/packages/sdk/src/entities/chats/chat.ts+++ b/packages/sdk/src/entities/chats/chat.ts@@ -158,6 +158,11 @@ export class Chat extends PropertiedEntity<ChatDetail> implements Mentionable {return `${this.client.webAppUrl}/app/chat/${this.id}`;}+ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** Search chats by name and content, most relevant first, auto-paginated. */static search = entitySearch({filters: { chat_filters: {} },diff --git a/packages/sdk/src/entities/databases/database.ts b/packages/sdk/src/entities/databases/database.tsindex 202ecd8c23..e810472f2a 100644--- a/packages/sdk/src/entities/databases/database.ts+++ b/packages/sdk/src/entities/databases/database.ts@@ -265,6 +265,16 @@ export class Database extends MacroEntity<DatabaseDetail> {throw new MacroError(`${part} does not belong to database ${this.id}`);}+ /** The database's URL in the Macro web app; hand it to users as the link. */+ webUrl(): string {+ return `${this.client.webAppUrl}/app/database/${this.id}`;+ }++ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** A handle to a database by id. Details load on first access. */static byId(client: MacroClient, id: string): Database {return new Database(client, id);diff --git a/packages/sdk/src/entities/documents/document.ts b/packages/sdk/src/entities/documents/document.tsindex 2677e36116..26ec6d86f8 100644--- a/packages/sdk/src/entities/documents/document.ts+++ b/packages/sdk/src/entities/documents/document.ts@@ -487,6 +487,11 @@ export class Documentreturn `${this.client.webAppUrl}/app/md/${this.id}`;}+ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** Search documents by name and content, most relevant first, auto-paginated. */static search = entitySearch({filters: { document_filters: {} },diff --git a/packages/sdk/src/entities/email/thread.ts b/packages/sdk/src/entities/email/thread.tsindex 14c60bdd75..53fd0e30a8 100644--- a/packages/sdk/src/entities/email/thread.ts+++ b/packages/sdk/src/entities/email/thread.ts@@ -179,6 +179,16 @@ export class EmailThread extends PropertiedEntity<ThreadDetail> {return thread;}+ /** The thread's URL in the Macro web app; hand it to users as the link. */+ webUrl(): string {+ return `${this.client.webAppUrl}/app/mail/${this.id}`;+ }++ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** A handle to a thread by id. Details load on first access. */static byId(client: MacroClient, id: string): EmailThread {return new EmailThread(client, id);diff --git a/packages/sdk/src/entities/forms/form.ts b/packages/sdk/src/entities/forms/form.tsindex 72efe41710..f773c80054 100644--- a/packages/sdk/src/entities/forms/form.ts+++ b/packages/sdk/src/entities/forms/form.ts@@ -665,6 +665,11 @@ export class Form extends MacroEntity<FormDetail> {return `${this.client.webAppUrl}/app/form/${this.id}`;}+ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** The respondent page, which public forms also expose without signing in. */respondUrl(): string {return `${this.client.webAppUrl}/app/form/${this.id}/respond`;diff --git a/packages/sdk/src/entities/initiatives/initiative.ts b/packages/sdk/src/entities/initiatives/initiative.tsindex b2e4a6195c..6ae7f45831 100644--- a/packages/sdk/src/entities/initiatives/initiative.ts+++ b/packages/sdk/src/entities/initiatives/initiative.ts@@ -32,6 +32,16 @@ export class Initiative extends MacroEntity<InitiativeDetail> {/** Access requests and direct user grants. */readonly access = new EntityAccess(this.client, 'initiative', this);+ /** The initiative's URL in the Macro web app; hand it to users as the link. */+ webUrl(): string {+ return `${this.client.webAppUrl}/app/initiative/${this.id}`;+ }++ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** Construct a lazy initiative handle. */static byId(client: MacroClient, id: string): Initiative {return new Initiative(client, id);diff --git a/packages/sdk/src/entities/projects/project.ts b/packages/sdk/src/entities/projects/project.tsindex 396368eeb1..d0ca418d7a 100644--- a/packages/sdk/src/entities/projects/project.ts+++ b/packages/sdk/src/entities/projects/project.ts@@ -51,6 +51,16 @@ export class Project extends PropertiedEntity<ProjectDetail> {return data.projectMetadata;}+ /** The project's URL in the Macro web app; hand it to users as the link. */+ webUrl(): string {+ return `${this.client.webAppUrl}/app/project/${this.id}`;+ }++ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** A handle to a project by id. Details load on first access. */static byId(client: MacroClient, id: string): Project {return new Project(client, id);diff --git a/packages/sdk/src/entities/routines/routine.ts b/packages/sdk/src/entities/routines/routine.tsindex 324c5a2ead..ad74d3fb62 100644--- a/packages/sdk/src/entities/routines/routine.ts+++ b/packages/sdk/src/entities/routines/routine.ts@@ -96,6 +96,16 @@ export interface RoutineOptions {/** A scheduled or event-triggered agent task. */export class Routine extends MacroEntity<ScheduledActionResponse> {+ /** The routine's URL in the Macro web app; hand it to users as the link. */+ webUrl(): string {+ return `${this.client.webAppUrl}/app/routines/${this.id}`;+ }++ /** Identity, loaded detail and {@link webUrl}, so serialized handles carry their link. */+ override toJSON() {+ return { ...super.toJSON(), url: this.webUrl() };+ }+/** Construct a lazy routine handle. */static byId(client: MacroClient, id: string): Routine {return new Routine(client, id);diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.tsindex 069879c995..7cccee7f5b 100644--- a/packages/sdk/tests/agent-sessions.test.ts+++ b/packages/sdk/tests/agent-sessions.test.ts@@ -469,6 +469,28 @@ describe('AgentSession', () => {});});+ test('a created session serializes with its web app link', async () => {+ globalThis.fetch = (async (_input) =>+ Response.json({ session }, { status: 201 })) as typeof fetch;+ const macro = new Macro({+ token: 'user-token',+ hosts: { 'agent-harness': 'https://agent.example.test' },+ webAppUrl: 'https://app.example.test',+ });++ const created = await macro.agentSessions.createManaged({+ prompt: 'Fix it',+ });++ expect(created.webUrl()).toBe(+ 'https://app.example.test/app/agent/0198a4cc-e138-7670-a308-a6b766602700',+ );+ expect(JSON.parse(JSON.stringify(created))).toMatchObject({+ id: '0198a4cc-e138-7670-a308-a6b766602700',+ url: 'https://app.example.test/app/agent/0198a4cc-e138-7670-a308-a6b766602700',+ });+ });+test('prompt is sugar over control and reports queueing', async () => {let request: Request | undefined;globalThis.fetch = (async (input) => {