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
chore(sdk): hydrate inbound events, cleanup bot channel sending (#5689)
Wolf Mermelsteinb4725b000904
diff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex d234e86d66..905b23dc18 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -94,7 +94,9 @@ Most entities carry user-defined properties and can be favorited:```tsawait doc.favorite();-await doc.setProperty('prop_status', { text: 'In review' });+await doc.setProperty(macro.properties.byId('prop_status'), {+ text: 'In review',+});const props = await doc.properties();```@@ -113,6 +115,21 @@ await channel.send(msg`Hey ${user}, take a look at ${doc}. cc ${here}`);These will render as @mentions in the Macro UI.+### Posting to a channel webhook++The web UI can hand you a webhook URL and token for a channel. That token is a+bot token, so it goes in the normal place:++```ts+const macro = new Macro({+ auth: { type: 'bot', token: process.env.MACRO_WEBHOOK_TOKEN },+});++await macro.channels+ .byId(channelId)+ .send(msg`Deploy ${sha} finished. ${here}`);+```+# Webhook EventsPass a `webhookSecret` (or set `MACRO_WEBHOOK_SECRET`) to receive events. Youdiff --git a/packages/sdk/bun.lock b/packages/sdk/bun.lockindex 3ddb60791b..7f356348ba 100644--- a/packages/sdk/bun.lock+++ b/packages/sdk/bun.lock@@ -4,6 +4,9 @@"workspaces": {"": {"name": "@macro/sdk",+ "dependencies": {+ "ts-pattern": "^5.8.0",+ },"devDependencies": {"@biomejs/biome": "2.4.12","@hey-api/openapi-ts": "0.99.0",@@ -191,6 +194,8 @@"shebang-regex": ["[email protected]", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],+ "ts-pattern": ["[email protected]", "", {}, "sha512-6s5V71mX8qBUmlgbrfL33xDUwO0fq48rxAu2LBE11WBeGdpCPOsXksQbZJHvHwhrd3QjUusd3mAOM5Gg0mFBLg=="],+"typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],"undici-types": ["[email protected]", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],diff --git a/packages/sdk/examples/channel-probe.ts b/packages/sdk/examples/channel-probe.tsindex b9d78992aa..5583b7d616 100644--- a/packages/sdk/examples/channel-probe.ts+++ b/packages/sdk/examples/channel-probe.ts@@ -21,10 +21,8 @@ if (!channelId || !actAs || !botToken) {}const env = (process.env.MACRO_ENV ?? 'dev') as Env;-const macro = new Macro({- env,- auth: { type: 'bot', token: botToken },-}).requestedAs(actAs);+const bot = new Macro({ env, auth: { type: 'bot', token: botToken } });+const macro = bot.requestedAs(bot.users.byId(actAs));const channel = macro.channels.byId(channelId);async function step<T>(name: string, run: () => Promise<T>): Promise<T | null> {diff --git a/packages/sdk/examples/channel-webhook.ts b/packages/sdk/examples/channel-webhook.tsnew file mode 100644index 0000000000..2f7844d4bd--- /dev/null+++ b/packages/sdk/examples/channel-webhook.ts@@ -0,0 +1,41 @@+/**+ * Post to a channel using a webhook token copied out of the Macro web UI.+ *+ * The token is an ordinary bot token, so this is just `channel.send()` — the+ * SDK works out that the credential can only reach the webhook endpoint and+ * routes there. Mentions still land, because `msg` embeds `<m-*>` tags in the+ * content and the backend parses them back out.+ *+ * usage: MACRO_WEBHOOK_TOKEN=mbot_... bun examples/channel-webhook.ts <channel-id> [mention-user-id]+ */+import { Env } from '../src/config';+import { here, Macro, msg } from '../src/macro';++const token = process.env.MACRO_WEBHOOK_TOKEN;+const [channelId, mentionUserId] = process.argv.slice(2);++if (!token || !channelId) {+ console.error(+ 'usage: MACRO_WEBHOOK_TOKEN=mbot_... bun examples/channel-webhook.ts <channel-id> [mention-user-id]',+ );+ process.exit(1);+}++const macro = new Macro({+ env: (process.env.MACRO_ENV ?? 'dev') as Env,+ auth: { type: 'bot', token },+});+const channel = macro.channels.byId(channelId);++// Plain text.+await channel.send('Build started.');++// Rich framing. `macro.users.byId` is a lazy handle — no request is made just+// to mention someone.+const target = mentionUserId ? macro.users.byId(mentionUserId) : here;+const sent = await channel.send(+ msg`Build **passed** on \`main\`. Nice work ${target}.`,+);++const self = await macro.bots.me();+console.log(`posted ${sent.id} as ${self.name} (${self.owner?.type}-owned)`);diff --git a/packages/sdk/examples/webhook-events.ts b/packages/sdk/examples/webhook-events.tsindex 4635e5c77a..1e82b5d089 100644--- a/packages/sdk/examples/webhook-events.ts+++ b/packages/sdk/examples/webhook-events.ts@@ -13,10 +13,8 @@ if (!url || !actAs || !botToken) {const env = (process.env.MACRO_ENV ?? 'dev') as Env;const port = Number(process.env.PORT ?? 8787);-const macro = new Macro({- env,- auth: { type: 'bot', token: botToken },-}).requestedAs(actAs);+const bot = new Macro({ env, auth: { type: 'bot', token: botToken } });+const macro = bot.requestedAs(bot.users.byId(actAs));// `as const` keeps the literal types so `.on()` infers each event's payload;// `satisfies` makes a typo in this list a compile error.@@ -80,4 +78,22 @@ const events = new Macro({for (const name of ALL_EVENTS) {events.on(name, (event) => console.log(name, event.metadata));}++// Handlers also get ORM handles for whatever the payload names — no going back+// to the SDK with an id. The set is exact per event, so `e.document` exists+// here and `e.channel` would not compile.+events.on('document.created', async (e) => {+ const owner = await e.owner.name();+ console.log(+ ` -> ${await e.document.name()} created by ${owner ?? 'someone'}`,+ );+});++events.on('channel.message_posted', async (e) => {+ // `sender` is undefined when a bot posted: the wire type is a bare string+ // for both, so only a real user id resolves to a handle.+ const from = e.sender ? ((await e.sender.name()) ?? e.sender.id) : 'a bot';+ console.log(` -> ${from} posted in ${await e.channel.name()}`);+});+receiver = events.webhook();diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex 082994cce7..58cd91c4bc 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -35,6 +35,9 @@"lint": "biome check","format": "biome format --write"},+ "dependencies": {+ "ts-pattern": "^5.8.0"+ },"devDependencies": {"@biomejs/biome": "2.4.12","@types/bun": "^1.3.5",diff --git a/packages/sdk/src/config.ts b/packages/sdk/src/config.tsindex de4bd21a29..3194f86c93 100644--- a/packages/sdk/src/config.ts+++ b/packages/sdk/src/config.ts@@ -104,7 +104,7 @@ export interface MacroOpts {webhookSecret?: string;wsVerify?: string;/** User id the bot acts for, sent as `x-macro-bot-for-macro-user-id` on- * every request. Bot auth only. Set via `macro.requestedAs(userId)` rather+ * every request. Bot auth only. Set via `macro.requestedAs(user)` rather* than directly. */requestedAs?: string;}diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex d279257a47..3f4f59bb74 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -272,7 +272,6 @@ export const storageExcluded = ['jobProcessingResultHandler','leaveOrEndCall','patchViewHandler',- 'postChannelBotWebhook','postChannelMessages','postItemsSoup','postItemsSoupAst',diff --git a/packages/sdk/src/entities/channels/channel.ts b/packages/sdk/src/entities/channels/channel.tsindex 18997143c0..07eb7971c1 100644--- a/packages/sdk/src/entities/channels/channel.ts+++ b/packages/sdk/src/entities/channels/channel.ts@@ -13,6 +13,7 @@ import { entitySearch } from '../search';import type { Team } from '../teams/team';import type { User } from '../users/user';import { Message } from './message';+import { postToChannel } from './post';import type { Thread } from './thread';type ChannelDetail = GetChannelResponses[200];@@ -99,25 +100,22 @@ export class Channel extends PropertiedEntity<ChannelDetail> {/** The channel's type (e.g. `public`, `dm`, `private`). */readonly type = this.field('channel_type');- /** Post a message. Plain text, or a rich body composed with `msg`. */+ /**+ * Post a message. Plain text, or a rich body composed with `msg`.+ *+ * Works with a channel webhook token as well as a normal one — see+ * {@link postToChannel} for which endpoint that picks and what it costs.+ */async send(body: string | RichMessage,opts?: { thread?: Thread },): Promise<Message> {- const { content, mentions } = toBody(body);- const res = unwrap(- await this.client.storage.postMessage({- path: { channel_id: this.id },- body: {- content,- mentions,- attachments: [],- thread_id: opts?.thread?.rootId ?? null,- nonce: crypto.randomUUID(),- },- }),+ const id = await postToChannel(+ this.client,+ opts?.thread ?? this,+ toBody(body),);- return Message.byId(this.client, this.id, res.id);+ return Message.byId(this.client, this.id, id);}/** The messages in this channel, most recent first, auto-paginated. */diff --git a/packages/sdk/src/entities/channels/message.ts b/packages/sdk/src/entities/channels/message.tsindex fd1829f328..2a64cf1be5 100644--- a/packages/sdk/src/entities/channels/message.ts+++ b/packages/sdk/src/entities/channels/message.ts@@ -3,7 +3,7 @@ import type {GetMessageWithContextResponses,GetThreadRepliesResponses,} from '../../../generated/storage/types.gen';-import type { RichMessage, SimpleMention } from '../../mentions';+import { type RichMessage, type SimpleMention, toBody } from '../../mentions';import { MacroNotFoundError, unwrap } from '../../utils';import type { MacroClient } from '../../utils/client';import { FavoritableEntity } from '../entity';@@ -138,12 +138,17 @@ export class Message extends FavoritableEntity<MessageData> {return this;}- /** Replace this message's body. */- async edit(content: string): Promise<this> {+ /**+ * Replace this message's body.+ *+ * @param body - Plain text, or a rich body composed with {@link msg}.+ */+ async edit(body: string | RichMessage): Promise<this> {+ const { content, mentions } = toBody(body);await this.mutate((c) =>c.storage.patchMessage({path: { channel_id: this.channelId, message_id: this.id },- body: { content },+ body: { content, mentions },}),);return this;diff --git a/packages/sdk/src/entities/channels/post.ts b/packages/sdk/src/entities/channels/post.tsnew file mode 100644index 0000000000..3f8d4789a0--- /dev/null+++ b/packages/sdk/src/entities/channels/post.ts@@ -0,0 +1,91 @@+import type { RichMessage } from '../../mentions';+import { MacroError, unwrap } from '../../utils';+import type { MacroClient } from '../../utils/client';+import type { Channel } from './channel';+import type { Thread } from './thread';++/**+ * Post a message using the endpoint supported by the caller's credentials.+ *+ * Most credentials use `POST /channels/{id}/message`. User-owned bots without+ * an acting user instead use `POST /channels/{id}/webhook`, which authorizes+ * through channel membership. The bot owner is read from `GET /bots/me` and+ * cached by the client.+ *+ * The webhook endpoint supports content only. Mentions in `<m-*>` tags still+ * work, but threads and attachments are not supported.+ *+ * Posting to a `Thread` puts the message in that thread; to a `Channel`, at the+ * channel root. One target rather than a channel plus a thread id, so the two+ * can't disagree.+ */+export async function postToChannel(+ client: MacroClient,+ target: Channel | Thread,+ body: RichMessage,+): Promise<string> {+ const { channelId, thread } = resolve(target);++ if (await hasEntityAccess(client)) {+ const { id } = unwrap(+ await client.storage.postMessage({+ path: { channel_id: channelId },+ body: {+ content: body.content,+ mentions: body.mentions,+ attachments: [],+ thread_id: thread?.rootId ?? null,+ nonce: crypto.randomUUID(),+ },+ }),+ );+ return id;+ }++ if (thread) {+ throw new MacroError(+ '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',+ );+ }++ const { message_id } = unwrap(+ await client.storage.postChannelBotWebhook({+ path: { channel_id: channelId },+ body: { content: body.content },+ // Not a claim to be acting as a user — no acting user is sent. The+ // header is required to parse but never read here (the route resolves+ // no access scope, only bot identity plus channel membership), and+ // `user` is the value that authenticates: the inherited default would+ // be `team`, which a user-owned bot is rejected for. If this route ever+ // moves onto entity access, this breaks — user scope without an acting+ // user is refused there.+ headers: { 'x-macro-bot-scope': 'user' },+ }),+ );+ return message_id;+}++/** Split a target into the channel to post in and the thread to post under. */+function resolve(target: Channel | Thread): {+ channelId: string;+ thread?: Thread;+} {+ return 'rootId' in target+ ? { channelId: target.channelId, thread: target }+ : { channelId: target.id };+}++/**+ * Whether this credential resolves to a scope the entity-access routes accept.+ *+ * User tokens always do. A bot does when it acts for a user, or when it is+ * team-owned — a team-owned bot's participant row grants its role in any+ * channel, so membership alone is enough there too.+ */+async function hasEntityAccess(client: MacroClient): Promise<boolean> {+ if (client.authConfig.type !== 'bot' || client.hasActingUser()) return true;+ const { owner } = await client.selfBot();+ return owner?.type === 'team';+}diff --git a/packages/sdk/src/entities/channels/thread.ts b/packages/sdk/src/entities/channels/thread.tsindex e6f3d4a14c..f3d9bb3ab4 100644--- a/packages/sdk/src/entities/channels/thread.ts+++ b/packages/sdk/src/entities/channels/thread.ts@@ -3,6 +3,7 @@ import { unwrap } from '../../utils';import type { MacroClient } from '../../utils/client';import { Channel } from './channel';import { Message } from './message';+import { postToChannel } from './post';/*** A thread within a channel, rooted at a top-level message. Replies and@@ -45,19 +46,7 @@ export class Thread {* @returns The created reply.*/async reply(body: string | RichMessage): Promise<Message> {- const { content, mentions } = toBody(body);- const { id } = unwrap(- await this.client.storage.postMessage({- path: { channel_id: this.channelId },- body: {- content,- mentions,- attachments: [],- thread_id: this.rootId,- nonce: crypto.randomUUID(),- },- }),- );+ const id = await postToChannel(this.client, this, toBody(body));return Message.byId(this.client, this.channelId, id);}}diff --git a/packages/sdk/src/entities/entity.ts b/packages/sdk/src/entities/entity.tsindex 4ed6352ab1..fbdf27797b 100644--- a/packages/sdk/src/entities/entity.ts+++ b/packages/sdk/src/entities/entity.ts@@ -25,8 +25,11 @@ export interface Propertied extends Favoritable {properties(opts?: {includeMetadata?: boolean;}): Promise<EntityPropertyWithDefinition[]>;- setProperty(propertyId: string, value?: SetPropertyValue): Promise<void>;- deleteProperty(entityPropertyId: string): Promise<void>;+ setProperty(+ property: PropertyDefinition,+ value?: SetPropertyValue,+ ): Promise<void>;+ deleteProperty(assignment: EntityPropertyWithDefinition): Promise<void>;}/** A delta to apply to one multi-select property. */@@ -180,19 +183,18 @@ export abstract class PropertiedEntity<Detail>}/**- * Set a property value on this entity by property definition id, or attach- * the property without a value when `value` is omitted.+ * Set a property value on this entity, or attach the property without a+ * value when `value` is omitted.*/async setProperty(- propertyId: string,+ property: PropertyDefinition,value?: SetPropertyValue,): Promise<void> {unwrap(await this.client.properties.setEntityProperty({path: {- entity_type: this.propertyEntityType,- entity_id: this.id,- property_id: propertyId,+ ...this.propertyReference(),+ property_id: property.id,},body: { value: value ?? null },}),@@ -221,14 +223,13 @@ export abstract class PropertiedEntity<Detail>);}- /**- * Remove a property from this entity by its entity-property assignment id- * (the `property.id` of a {@link properties} entry).- */- async deleteProperty(entityPropertyId: string): Promise<void> {+ /** Remove a property from this entity, given its {@link properties} entry. */+ async deleteProperty(+ assignment: EntityPropertyWithDefinition,+ ): Promise<void> {unwrap(await this.client.properties.deleteEntityProperty({- path: { entity_property_id: entityPropertyId },+ path: { entity_property_id: assignment.property.id },}),);}diff --git a/packages/sdk/src/entities/favorites/namespace.ts b/packages/sdk/src/entities/favorites/namespace.tsindex 58f83a9373..87545eb428 100644--- a/packages/sdk/src/entities/favorites/namespace.ts+++ b/packages/sdk/src/entities/favorites/namespace.ts@@ -4,7 +4,7 @@ import type {} from '../../../generated/storage/types.gen';import { unwrap } from '../../utils';import type { MacroClient } from '../../utils/client';-import type { MacroEntityType } from '../entity';+import type { FavoritableEntity } from '../entity';export type { Favorite, FavoriteEntityRef };@@ -18,20 +18,22 @@ export class FavoritesNamespace {return favorites;}- /** Favorite an entity by type and id. Returns the favorite record. */- async add(entityType: MacroEntityType, entityId: string): Promise<Favorite> {+ /**+ * Favorite an entity. Returns the favorite record.+ */+ async add(entity: FavoritableEntity<unknown>): Promise<Favorite> {return unwrap(await this.client.storage.addFavorite({- body: { entityId, entityType },+ body: { entityId: entity.id, entityType: entity.entityType },}),);}- /** Remove a favorite by entity type and id. */- async remove(entityType: MacroEntityType, entityId: string): Promise<void> {+ /** Remove an entity from the user's favorites. */+ async remove(entity: FavoritableEntity<unknown>): Promise<void> {unwrap(await this.client.storage.removeFavoriteByEntity({- path: { entity_type: entityType, entity_id: entityId },+ path: { entity_type: entity.entityType, entity_id: entity.id },}),);}diff --git a/packages/sdk/src/entities/pins/namespace.ts b/packages/sdk/src/entities/pins/namespace.tsindex 8af2a99b57..c2d9989450 100644--- a/packages/sdk/src/entities/pins/namespace.ts+++ b/packages/sdk/src/entities/pins/namespace.ts@@ -4,6 +4,7 @@ import type {} from '../../../generated/storage/types.gen';import { unwrap } from '../../utils';import type { MacroClient } from '../../utils/client';+import type { FavoritableEntity } from '../entity';export type { PinnedItem, ReorderPinRequest };@@ -17,25 +18,25 @@ export class PinsNamespace {return data?.recent ?? [];}- /** Pin an item at an index. `pinType` is the item's type (e.g. `document`). */+ /** Pin an entity to a slot. `index` is the slot to put it in. */async add(- pinnedItemId: string,- opts: { pinType: string; pinIndex: number },+ entity: FavoritableEntity<unknown>,+ opts: { index: number },): Promise<void> {unwrap(await this.client.storage.addPinHandler({- path: { pinned_item_id: pinnedItemId },- body: { pinType: opts.pinType, pinIndex: opts.pinIndex },+ path: { pinned_item_id: entity.id },+ body: { pinType: entity.entityType, pinIndex: opts.index },}),);}- /** Unpin an item. `pinType` is the item's type (e.g. `document`). */- async remove(pinnedItemId: string, pinType: string): Promise<void> {+ /** Unpin an entity. */+ async remove(entity: FavoritableEntity<unknown>): Promise<void> {unwrap(await this.client.storage.removePinHandler({- path: { pinned_item_id: pinnedItemId },- body: { pinType },+ path: { pinned_item_id: entity.id },+ body: { pinType: entity.entityType },}),);}diff --git a/packages/sdk/src/entities/properties/namespace.ts b/packages/sdk/src/entities/properties/namespace.tsindex ce3ecbc0bf..ae62992b34 100644--- a/packages/sdk/src/entities/properties/namespace.ts+++ b/packages/sdk/src/entities/properties/namespace.ts@@ -107,16 +107,14 @@ export class PropertiesNamespace {/** Add a select option to a multi-select property value on an entity. */async addEntityPropertyOption(opts: {- entityType: PropertyEntityType;- entityId: string;+ entity: PropertiedEntity<unknown>;property: PropertyDefinition;option: PropertyOption;}): Promise<void> {return unwrap(await this.client.properties.addEntityPropertyOption({path: {- entity_type: opts.entityType,- entity_id: opts.entityId,+ ...opts.entity.propertyReference(),property_id: opts.property.id,option_id: opts.option.id,},@@ -126,16 +124,14 @@ export class PropertiesNamespace {/** Remove a select option from a multi-select property value on an entity. */async removeEntityPropertyOption(opts: {- entityType: PropertyEntityType;- entityId: string;+ entity: PropertiedEntity<unknown>;property: PropertyDefinition;option: PropertyOption;}): Promise<void> {return unwrap(await this.client.properties.removeEntityPropertyOption({path: {- entity_type: opts.entityType,- entity_id: opts.entityId,+ ...opts.entity.propertyReference(),property_id: opts.property.id,option_id: opts.option.id,},diff --git a/packages/sdk/src/events/hydrate/channel.ts b/packages/sdk/src/events/hydrate/channel.tsnew file mode 100644index 0000000000..61c97f4b47--- /dev/null+++ b/packages/sdk/src/events/hydrate/channel.ts@@ -0,0 +1,162 @@+import { match } from 'ts-pattern';+import { Channel } from '../../entities/channels/channel';+import { Message } from '../../entities/channels/message';+import { Thread } from '../../entities/channels/thread';+import { User } from '../../entities/users/user';+import type { MacroClient } from '../../utils/client';+import type { MacroEvent } from '../types';++export type ChannelEvent = Extract<+ MacroEvent,+ { event_type: `channel.${string}` }+>;++/** Wire prefix on a user principal; bots instead arrive as `bot|<uuid>`. */+const USER_PREFIX = 'macro|';++/**+ * Resolve a channel principal to a user handle, or undefined when it names a+ * bot. Lower-cased to match how the backend stores ids. Note `|` is legal in an+ * email, so `macro|bot|[email protected]` is a user.+ */+export function userFromPrincipal(client: MacroClient, principalId: string) {+ return principalId.startsWith(USER_PREFIX) &&+ principalId.length > USER_PREFIX.length+ ? User.byId(client, principalId.toLowerCase())+ : undefined;+}++/** Attach SDK entity handles to a channel webhook event. */+export function hydrateChannelEvent(client: MacroClient, event: ChannelEvent) {+ return match(event)+ .with({ event_type: 'channel.created' }, ({ metadata }) => ({+ event_type: 'channel.created' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ actor: userFromPrincipal(client, metadata.actor),+ participants: metadata.participant_user_ids.map((userId) =>+ User.byId(client, userId),+ ),+ }))+ .with({ event_type: 'channel.updated' }, ({ metadata }) => ({+ event_type: 'channel.updated' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ actor: userFromPrincipal(client, metadata.actor),+ }))+ .with({ event_type: 'channel.deleted' }, ({ metadata }) => ({+ event_type: 'channel.deleted' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ actor: userFromPrincipal(client, metadata.actor),+ }))+ .with({ event_type: 'channel.message_posted' }, ({ metadata }) => ({+ event_type: 'channel.message_posted' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ message: Message.byId(+ client,+ metadata.channel_id,+ metadata.message_id,+ metadata.mentions,+ ),+ sender: userFromPrincipal(client, metadata.sender),+ thread: metadata.thread_id+ ? new Thread(client, metadata.channel_id, metadata.thread_id)+ : undefined,+ }))+ .with({ event_type: 'channel.mentioned' }, ({ metadata }) => ({+ event_type: 'channel.mentioned' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ message: Message.byId(+ client,+ metadata.channel_id,+ metadata.message_id,+ [],+ ),+ sender: userFromPrincipal(client, metadata.sender),+ thread: metadata.thread_id+ ? new Thread(client, metadata.channel_id, metadata.thread_id)+ : undefined,+ }))+ .with({ event_type: 'channel.message_patched' }, ({ metadata }) => ({+ event_type: 'channel.message_patched' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ message: Message.byId(+ client,+ metadata.channel_id,+ metadata.message_id,+ [],+ ),+ actor: userFromPrincipal(client, metadata.actor),+ thread: metadata.thread_id+ ? new Thread(client, metadata.channel_id, metadata.thread_id)+ : undefined,+ }))+ .with({ event_type: 'channel.message_deleted' }, ({ metadata }) => ({+ event_type: 'channel.message_deleted' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ message: Message.byId(+ client,+ metadata.channel_id,+ metadata.message_id,+ [],+ ),+ actor: userFromPrincipal(client, metadata.actor),+ thread: metadata.thread_id+ ? new Thread(client, metadata.channel_id, metadata.thread_id)+ : undefined,+ }))+ .with(+ { event_type: 'channel.message_attachment_created' },+ ({ metadata }) => ({+ event_type: 'channel.message_attachment_created' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ message: Message.byId(+ client,+ metadata.channel_id,+ metadata.message_id,+ [],+ ),+ actor: userFromPrincipal(client, metadata.actor),+ }),+ )+ .with(+ { event_type: 'channel.message_attachment_removed' },+ ({ metadata }) => ({+ event_type: 'channel.message_attachment_removed' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ message: Message.byId(+ client,+ metadata.channel_id,+ metadata.message_id,+ [],+ ),+ actor: userFromPrincipal(client, metadata.actor),+ }),+ )+ .with({ event_type: 'channel.participant_added' }, ({ metadata }) => ({+ event_type: 'channel.participant_added' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ addedBy: userFromPrincipal(client, metadata.added_by),+ addedUsers: metadata.added_user_ids.map((userId) =>+ User.byId(client, userId),+ ),+ }))+ .with({ event_type: 'channel.participant_removed' }, ({ metadata }) => ({+ event_type: 'channel.participant_removed' as const,+ metadata,+ channel: Channel.byId(client, metadata.channel_id),+ removedBy: User.byId(client, metadata.removed_by),+ removedUsers: metadata.removed_user_ids.map((userId) =>+ User.byId(client, userId),+ ),+ }))+ .exhaustive();+}diff --git a/packages/sdk/src/events/hydrate/document.ts b/packages/sdk/src/events/hydrate/document.tsnew file mode 100644index 0000000000..4fa376277c--- /dev/null+++ b/packages/sdk/src/events/hydrate/document.ts@@ -0,0 +1,86 @@+import { match } from 'ts-pattern';+import { Document } from '../../entities/documents/document';+import { Project } from '../../entities/projects/project';+import { User } from '../../entities/users/user';+import type { MacroClient } from '../../utils/client';+import type { MacroEvent } from '../types';++export type DocumentEvent = Extract<+ MacroEvent,+ { event_type: `document.${string}` }+>;++/** Attach SDK entity handles to a document webhook event. */+export function hydrateDocumentEvent(+ client: MacroClient,+ event: DocumentEvent,+) {+ return match(event)+ .with({ event_type: 'document.created' }, ({ metadata }) => ({+ event_type: 'document.created' as const,+ metadata,+ document: Document.byId(client, metadata.document_id),+ owner: User.byId(client, metadata.owner),+ project: metadata.project_id+ ? Project.byId(client, metadata.project_id)+ : undefined,+ }))+ .with({ event_type: 'document.updated' }, ({ metadata }) => ({+ event_type: 'document.updated' as const,+ metadata,+ document: Document.byId(client, metadata.document_id),+ owner: User.byId(client, metadata.owner),+ actor: metadata.actor_user_id+ ? User.byId(client, metadata.actor_user_id)+ : undefined,+ project: metadata.project_id+ ? Project.byId(client, metadata.project_id)+ : undefined,+ previousProject: metadata.previous_project_id+ ? Project.byId(client, metadata.previous_project_id)+ : undefined,+ }))+ .with({ event_type: 'document.deleted' }, ({ metadata }) => ({+ event_type: 'document.deleted' as const,+ metadata,+ document: Document.byId(client, metadata.document_id),+ actor: metadata.actor_user_id+ ? User.byId(client, metadata.actor_user_id)+ : undefined,+ project: metadata.project_id+ ? Project.byId(client, metadata.project_id)+ : undefined,+ }))+ .with({ event_type: 'document.content_uploaded' }, ({ metadata }) => ({+ event_type: 'document.content_uploaded' as const,+ metadata,+ document: Document.byId(client, metadata.document_id),+ owner: User.byId(client, metadata.owner),+ }))+ .with({ event_type: 'document.sync_content_updated' }, ({ metadata }) => ({+ event_type: 'document.sync_content_updated' as const,+ metadata,+ document: Document.byId(client, metadata.document_id),+ }))+ .with({ event_type: 'document.purged' }, ({ metadata }) => ({+ event_type: 'document.purged' as const,+ metadata,+ document: Document.byId(client, metadata.document_id),+ }))+ .with({ event_type: 'document.copied' }, ({ metadata }) => ({+ event_type: 'document.copied' as const,+ metadata,+ document: Document.byId(client, metadata.document_id),+ sourceDocument: Document.byId(client, metadata.source_document_id),+ owner: User.byId(client, metadata.owner),+ project: metadata.project_id+ ? Project.byId(client, metadata.project_id)+ : undefined,+ }))+ .with({ event_type: 'document.interaction' }, ({ metadata }) => ({+ event_type: 'document.interaction' as const,+ metadata,+ document: Document.byId(client, metadata.document_id),+ }))+ .exhaustive();+}diff --git a/packages/sdk/src/events/receiver.ts b/packages/sdk/src/events/receiver.tsindex 91fcde7110..61703aedc5 100644--- a/packages/sdk/src/events/receiver.ts+++ b/packages/sdk/src/events/receiver.ts@@ -1,6 +1,8 @@-import { Message } from '../entities/channels/message';+import { match, P } from 'ts-pattern';import { MacroError } from '../utils';import type { MacroClient } from '../utils/client';+import { hydrateChannelEvent } from './hydrate/channel';+import { hydrateDocumentEvent } from './hydrate/document';import type {DeliveryHeaders,EventHandler,@@ -15,18 +17,16 @@ type AnyHandler = (event: unknown) => void | Promise<void>;/** Sent by Macro when validating a newly registered endpoint; acked, never dispatched. */const VALIDATION_EVENT = 'webhook.validation.test';-// Runtime mirror of `MessageEventName`: any payload naming a message gets a-// hydrated handle.+/** Attach the entity handles defined for each webhook event. */function hydrate(client: MacroClient, event: MacroEvent): EventMap[EventName] {- const meta = event.metadata;- if ('message_id' in meta && 'channel_id' in meta) {- const mentions = 'mentions' in meta ? meta.mentions : [];- return {- metadata: meta,- message: Message.byId(client, meta.channel_id, meta.message_id, mentions),- } as EventMap[EventName];- }- return { metadata: meta } as EventMap[EventName];+ return match(event)+ .with({ event_type: P.string.startsWith('document.') }, (documentEvent) =>+ hydrateDocumentEvent(client, documentEvent),+ )+ .with({ event_type: P.string.startsWith('channel.') }, (channelEvent) =>+ hydrateChannelEvent(client, channelEvent),+ )+ .exhaustive();}/**@@ -101,11 +101,11 @@ export class MacroEvents {const event = JSON.parse(rawBody) as MacroEvent;if (!('event_type' in event)) return;- const set = this.handlers.get(event.event_type);- if (!set || set.size === 0) return;+ const handlers = this.handlers.get(event.event_type);+ if (!handlers || handlers.size === 0) return;const payload = hydrate(this.client, event);- await Promise.all([...set].map((handler) => handler(payload)));+ await Promise.all([...handlers].map((handler) => handler(payload)));}/**diff --git a/packages/sdk/src/events/types.ts b/packages/sdk/src/events/types.tsindex e48c79c116..bcdb3c4f69 100644--- a/packages/sdk/src/events/types.ts+++ b/packages/sdk/src/events/types.ts@@ -1,10 +1,11 @@// Event names and payloads come from the backend's OpenAPI spec// (`WebhookEvent` in generated/storage/schemas), so this file stays in-// lockstep with what the backend actually delivers. Message events-// additionally carry a hydrated `message` ORM handle.+// lockstep with what the backend actually delivers. On top of the raw+// `metadata`, handlers get ORM handles for every entity the payload names.import type { WebhookEvent } from '../../generated/storage/types.gen';-import type { Message } from '../entities/channels/message';+import type { hydrateChannelEvent } from './hydrate/channel';+import type { hydrateDocumentEvent } from './hydrate/document';/** A webhook delivery body, exactly as Macro serializes it. */export type MacroEvent = WebhookEvent;@@ -19,24 +20,25 @@ export type EventPayload<E extends EventName> = Extract<>['metadata'];/**- * Events whose payload names a message; handlers get a `message` handle.- * Derived structurally (payload carries `channel_id` + `message_id`), so a- * new backend event that names a message is hydrated with no SDK change.- * The receiver's runtime check mirrors this shape.+ * Every hydrated event the receiver can dispatch, as one discriminated union.+ *+ * The `hydrate*` functions are the single source of truth for which handles+ * ride along with which event — this reads their inferred return types back+ * rather than restating the mapping.*/-export type MessageEventName = {- [E in EventName]: EventPayload<E> extends {- channel_id: string;- message_id: string;- }- ? E- : never;-}[EventName];+type HydratedEvent =+ | ReturnType<typeof hydrateChannelEvent>+ | ReturnType<typeof hydrateDocumentEvent>;+/**+ * What a handler receives, per event: the raw `metadata` plus the ORM handles+ * named by that event's ids.+ *+ * Handles are free to construct and load lazily, so hydrating every event costs+ * nothing until a handler reads a field or calls a method on one.+ */export type EventMap = {- [E in EventName]: E extends MessageEventName- ? { metadata: EventPayload<E>; message: Message }- : { metadata: EventPayload<E> };+ [E in EventName]: Extract<HydratedEvent, { event_type: E }>;};export type EventHandler<E extends EventName> = (diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.tsindex 8354ac2e17..255e3dfbdf 100644--- a/packages/sdk/src/macro.ts+++ b/packages/sdk/src/macro.ts@@ -15,6 +15,7 @@ import { PropertiesNamespace } from './entities/properties/namespace';import { TaskNamespace } from './entities/tasks/namespace';import { TeamNamespace } from './entities/teams/namespace';import { UserNamespace } from './entities/users/namespace';+import type { User } from './entities/users/user';import { WebhooksNamespace } from './entities/webhooks/namespace';import type { MacroEvents } from './events/receiver';import { MacroClient } from './utils/client';@@ -92,10 +93,10 @@ export class Macro<T extends MacroOpts = MacroOpts> {return this._client.myPrincipalId();}- /** Clone of this SDK acting on behalf of `userId` (sent as+ /** Clone of this SDK acting on behalf of `user` (sent as* `x-macro-bot-for-macro-user-id`). Bot auth only — throws for user auth,* since a user token always acts as its own user. */- requestedAs(userId: string): Macro<T> {- return new Macro({ ...this.opts, requestedAs: userId });+ requestedAs(user: User): Macro<T> {+ return new Macro({ ...this.opts, requestedAs: user.id });}}diff --git a/packages/sdk/src/utils/client.ts b/packages/sdk/src/utils/client.tsindex 7abb4caa75..e809b1ef48 100644--- a/packages/sdk/src/utils/client.ts+++ b/packages/sdk/src/utils/client.ts@@ -7,6 +7,7 @@ import { Sdk as PropertiesSdk } from '../../generated/properties/sdk.gen';import { Sdk as SearchSdk } from '../../generated/search/sdk.gen';import { createClient } from '../../generated/storage/client';import { Sdk as StorageSdk } from '../../generated/storage/sdk.gen';+import type { Bot } from '../../generated/storage/types.gen';import {type Env,HOSTS,@@ -35,12 +36,12 @@ export class MacroClient {/** Resolved authentication config (distinct from `auth`, the auth-service SDK). */readonly authConfig: MacroAuth;private readonly requestedAs?: string;+ private selfBotRecord?: Promise<Bot>;private selfPrincipal?: Promise<string>;constructor(opts: MacroOpts) {const env: Env = opts.env ?? 'dev';- const localPortmap =- env === 'local' ? resolveLocalPortmap() : undefined;+ const localPortmap = env === 'local' ? resolveLocalPortmap() : undefined;const hosts = { ...HOSTS[env], ...localPortmap?.hosts, ...opts.hosts };const envWebUrl =typeof process !== 'undefined' ? process.env.MACRO_WEB_URL : undefined;@@ -90,6 +91,18 @@ export class MacroClient {return this.authConfig.type === 'user' || this.requestedAs !== undefined;}+ /**+ * The authenticated bot's own record, fetched once and cached. Bot auth+ * only. Failed lookups are not cached, so a later call retries.+ */+ selfBot(): Promise<Bot> {+ this.selfBotRecord ??= new BotsNamespace(this).me().catch((error) => {+ this.selfBotRecord = undefined;+ throw error;+ });+ return this.selfBotRecord;+ }+/*** The authenticated caller's mentionable principal — `bot|<uuid>` for bot* auth, `macro|<email>` for user auth — fetched once and cached. Failed@@ -98,7 +111,7 @@ export class MacroClient {myPrincipalId(): Promise<string> {this.selfPrincipal ??= (this.authConfig.type === 'bot'- ? new BotsNamespace(this).me().then((bot) => `bot|${bot.id}`)+ ? this.selfBot().then((bot) => `bot|${bot.id}`): User.me(this).then((user) => user.id)).catch((error) => {this.selfPrincipal = undefined;@@ -114,6 +127,9 @@ export class MacroClient {const tok = typeof source === 'function' ? await source() : source;if (this.authConfig.type === 'bot') {request.headers.set('x-macro-bot-token', tok);+ // A per-call scope wins: the channel webhook fallback pins `user`,+ // the only scope a user-owned bot can present (a team scope with no+ // owning team is rejected outright).if (!request.headers.has('x-macro-bot-scope')) {request.headers.set('x-macro-bot-scope',diff --git a/packages/sdk/tests/channel-principal.test.ts b/packages/sdk/tests/channel-principal.test.tsnew file mode 100644index 0000000000..0718032e89--- /dev/null+++ b/packages/sdk/tests/channel-principal.test.ts@@ -0,0 +1,29 @@+import { describe, expect, test } from 'bun:test';+import { userFromPrincipal } from '../src/events/hydrate/channel';+import type { MacroClient } from '../src/utils/client';++const client = {} as MacroClient;++describe('userFromPrincipal', () => {+ test('resolves user principals, normalizing case', () => {+ expect(userFromPrincipal(client, 'macro|[email protected]')?.id).toBe(+ 'macro|[email protected]',+ );+ });++ test('only treats a leading bot| as a bot, since | is legal in an email', () => {+ expect(userFromPrincipal(client, 'macro|bot|[email protected]')?.id).toBe(+ 'macro|bot|[email protected]',+ );+ });++ test('gives no user for bots or empty principals', () => {+ for (const id of [+ 'bot|00000000-0000-0000-0000-000000000001',+ 'macro|',+ '',+ ]) {+ expect(userFromPrincipal(client, id)).toBeUndefined();+ }+ });+});