Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(matrix): let AI agents message, react and manage rooms and members (#16524)

Odai Ahmad2f57efeea6de
diff --git a/bun.lock b/bun.lock
index bc84d2a6550..27f44925caf 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5675,17 +5675,17 @@
},
"packages/pieces/community/matrix": {
"name": "@activepieces/piece-matrix",
- "version": "0.5.1",
+ "version": "0.6.0",
"dependencies": {
- "@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"marked": "4.3.0",
+ "undici": "7.29.1",
},
"devDependencies": {
"@types/marked": "4.3.2",
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/mattermost": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index 28b93f43564..9e9735ccd71 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,18 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Matrix 0.6.0: Send Message returns the event ID, is builder-only, and the Home Server must be the server's own URL
+
+Send Message used to return the raw HTTP response of the send call (`status`, `headers` and a `body` holding `event_id`). From Matrix 0.6.0 it returns `{ eventId, roomId, transactionId }`. The room is now picked from a dropdown of joined rooms (Room Alias stays as an optional fallback), and the action is builder-only: AI agents use the new **Send Text Message** action instead.
+
+The connection's **Home Server** is now checked when it is saved and on every run. It must be an `https` URL of the homeserver itself, such as `https://matrix-client.matrix.org` (plain `http` is accepted only for `localhost`). An Element web link such as `https://app.element.io/#/home` is rejected with a message that says which URL to use instead.
+
+Custom API Call now only accepts URLs on the connection's homeserver. A step that pointed it at another host fails after the upgrade.
+
+#### What you need to do
+
+If a later step reads `body.event_id` from Send Message, read `eventId` instead. If a Custom API Call step calls another host, point it at your homeserver or use the HTTP piece. Agents that used Send Message as a tool switch to Send Text Message. If a Matrix connection fails with the Home Server message, reconnect it with your homeserver's URL (shown in Element under Settings, Help & About). Steps keep running on the version they were built with until you upgrade them.
+
#### Close 0.3.0: Find Lead and Find Contact drop the "Starts With" and "Ends With" match options
Find Lead and Find Contact no longer offer the **Starts With** and **Ends With** match options. They never worked: Close's search ignored them, so a step using one did not filter as its label said. A step upgraded to Close 0.3.0 with one of these options saved fails validation until a supported option is picked.
diff --git a/packages/pieces/community/matrix/package.json b/packages/pieces/community/matrix/package.json
index 2b4b543ecfc..eb956aa1283 100644
--- a/packages/pieces/community/matrix/package.json
+++ b/packages/pieces/community/matrix/package.json
@@ -1,22 +1,23 @@
{
"name": "@activepieces/piece-matrix",
- "version": "0.5.1",
+ "version": "0.6.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"marked": "4.3.0",
- "@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "undici": "7.29.1"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"devDependencies": {
"@types/marked": "4.3.2",
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/matrix/src/i18n/translation.json b/packages/pieces/community/matrix/src/i18n/translation.json
index adfc54a8a2b..a2544d265fc 100644
--- a/packages/pieces/community/matrix/src/i18n/translation.json
+++ b/packages/pieces/community/matrix/src/i18n/translation.json
@@ -2,13 +2,85 @@
"Open standard for interoperable, decentralized, real-time communication": "Open standard for interoperable, decentralized, real-time communication",
"Home Server": "Home Server",
"Access Token": "Access Token",
+ "The client API address of your homeserver, e.g. https://matrix-client.matrix.org (shown under Help & About in Element).": "The client API address of your homeserver, e.g. https://matrix-client.matrix.org (shown under Help & About in Element).",
"\n To obtain access token & Home server:\n\n 1. Log in to the account you want to get the access token for on Element.\n 2. Click on the name in the top left corner of the screen, then select \"Settings\" from the dropdown menu.\n 3. In the Settings dialog, click the \"Help & About\" tab on the left side of the screen.\n 4. Scroll to the bottom of the page and click on the \"click to reveal\" part of the \"Access Token\" section.\n 5. Copy your access token & Home Server URL and paste them into the field": "\n To obtain access token & Home server:\n\n 1. Log in to the account you want to get the access token for on Element.\n 2. Click on the name in the top left corner of the screen, then select \"Settings\" from the dropdown menu.\n 3. In the Settings dialog, click the \"Help & About\" tab on the left side of the screen.\n 4. Scroll to the bottom of the page and click on the \"click to reveal\" part of the \"Access Token\" section.\n 5. Copy your access token & Home Server URL and paste them into the fields below.\n ",
"Send Message": "Send Message",
+ "Ban User": "Ban User",
+ "Create Room": "Create Room",
+ "Edit Message": "Edit Message",
+ "Get Current User": "Get Current User",
+ "Get Message": "Get Message",
+ "Get Room": "Get Room",
+ "Get User Profile": "Get User Profile",
+ "Invite User": "Invite User",
+ "Join Room": "Join Room",
+ "Kick User": "Kick User",
+ "Leave Room": "Leave Room",
+ "List Joined Rooms": "List Joined Rooms",
+ "List Messages": "List Messages",
+ "List Room Members": "List Room Members",
+ "React to Message": "React to Message",
+ "Delete (Redact) Message": "Delete (Redact) Message",
+ "Search Public Rooms": "Search Public Rooms",
+ "Search Users": "Search Users",
+ "Send Text Message": "Send Text Message",
+ "Set Room Name": "Set Room Name",
+ "Set Room Topic": "Set Room Topic",
+ "Unban User": "Unban User",
"Custom API Call": "Custom API Call",
"Send a message to a room": "Send a message to a room",
+ "Ban a user from a room.": "Ban a user from a room.",
+ "Create a new room, optionally public, with invites.": "Create a new room, optionally public, with invites.",
+ "Replace the text of a message this account sent.": "Replace the text of a message this account sent.",
+ "Get the Matrix user ID and device of this connection.": "Get the Matrix user ID and device of this connection.",
+ "Get one event (message) from a room by its ID.": "Get one event (message) from a room by its ID.",
+ "Get a room's name, topic, alias, encryption and member counts. Accepts an alias.": "Get a room's name, topic, alias, encryption and member counts. Accepts an alias.",
+ "Get the display name and avatar of a user.": "Get the display name and avatar of a user.",
+ "Invite a user to a room.": "Invite a user to a room.",
+ "Join a room by ID or alias, or accept an invite.": "Join a room by ID or alias, or accept an invite.",
+ "Remove a user from a room.": "Remove a user from a room.",
+ "Leave a room (or reject an invite), optionally forgetting it.": "Leave a room (or reject an invite), optionally forgetting it.",
+ "List the rooms this account has joined, with their names.": "List the rooms this account has joined, with their names.",
+ "List recent events in a room, newest first.": "List recent events in a room, newest first.",
+ "List the joined members of a room.": "List the joined members of a room.",
+ "Add an emoji reaction to a message.": "Add an emoji reaction to a message.",
+ "Redact a message or reaction, removing its content for everyone.": "Redact a message or reaction, removing its content for everyone.",
+ "Search the homeserver's public room directory.": "Search the homeserver's public room directory.",
+ "Search the user directory by name or user ID.": "Search the user directory by name or user ID.",
+ "Send a text, notice or emote message to a room, optionally as a reply.": "Send a text, notice or emote message to a room, optionally as a reply.",
+ "Rename a room.": "Rename a room.",
+ "Set the topic of a room.": "Set the topic of a room.",
+ "Lift a ban so the user can rejoin.": "Lift a ban so the user can rejoin.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
+ "Room": "Room",
"Room Alias": "Room Alias",
"Message": "Message",
+ "Room ID": "Room ID",
+ "User ID": "User ID",
+ "Reason": "Reason",
+ "Name": "Name",
+ "Topic": "Topic",
+ "Preset": "Preset",
+ "Publish to Room Directory": "Publish to Room Directory",
+ "Alias (local part)": "Alias (local part)",
+ "Invite User IDs": "Invite User IDs",
+ "Event ID": "Event ID",
+ "New Text": "New Text",
+ "Format": "Format",
+ "Transaction ID": "Transaction ID",
+ "Via Servers": "Via Servers",
+ "Forget Room": "Forget Room",
+ "Limit": "Limit",
+ "Offset": "Offset",
+ "From": "From",
+ "Messages Only": "Messages Only",
+ "Reaction": "Reaction",
+ "Search Term": "Search Term",
+ "Server": "Server",
+ "Since": "Since",
+ "Text": "Text",
+ "Message Type": "Message Type",
+ "Reply To Event ID": "Reply To Event ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -18,14 +90,39 @@
"Return Error as Output": "Return Error as Output",
"Timeout": "Timeout",
"Follow redirects": "Follow redirects",
- "Copy it from room settings -> advanced -> room addresses -> main address": "Copy it from room settings -> advanced -> room addresses -> main address",
+ "Pick one of the rooms this account has joined, or fill Room Alias instead.": "Pick one of the rooms this account has joined, or fill Room Alias instead.",
+ "Used when no Room is picked, e.g. #room:example.org": "Used when no Room is picked, e.g. #room:example.org",
"The message to send (markdown)": "The message to send (markdown)",
+ "e.g. @alice:example.org": "e.g. @alice:example.org",
+ "e.g. team-ops for #team-ops:yourserver": "e.g. team-ops for #team-ops:yourserver",
+ "User IDs like @alice:example.org": "User IDs like @alice:example.org",
+ "The message to edit ($...).": "The message to edit ($...).",
+ "Room ID (!...) or alias (#...).": "Room ID (!...) or alias (#...).",
+ "Optional server names, e.g. matrix.org": "Optional server names, e.g. matrix.org",
+ "1-100, default 50.": "1-100, default 50.",
+ "Default 0.": "Default 0.",
+ "1-100, default 20.": "1-100, default 20.",
+ "nextToken of the previous page.": "nextToken of the previous page.",
+ "Usually a single emoji, e.g. 👍": "Usually a single emoji, e.g. 👍",
+ "Directory of another server, e.g. matrix.org. Empty = your homeserver.": "Directory of another server, e.g. matrix.org. Empty = your homeserver.",
+ "1-50, default 10.": "1-50, default 10.",
+ "Room ID (!abc:server) or alias (#room:server).": "Room ID (!abc:server) or alias (#room:server).",
+ "Event ID ($...) to reply to.": "Event ID ($...) to reply to.",
+ "Optional. Reuse the same value to retry a send without posting twice.": "Optional. Reuse the same value to retry a send without posting twice.",
+ "Leave empty to clear it.": "Leave empty to clear it.",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
"Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
"On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
"Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
"Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "Private (invite only)": "Private (invite only)",
+ "Public (anyone can join)": "Public (anyone can join)",
+ "Trusted private (invitees are admins)": "Trusted private (invitees are admins)",
+ "Markdown": "Markdown",
+ "Plain text": "Plain text",
+ "Notice": "Notice",
+ "Emote": "Emote",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
diff --git a/packages/pieces/community/matrix/src/index.ts b/packages/pieces/community/matrix/src/index.ts
index 27de91ec5ef..18d766fd0c9 100644
--- a/packages/pieces/community/matrix/src/index.ts
+++ b/packages/pieces/community/matrix/src/index.ts
@@ -1,56 +1,83 @@
import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import {
- PieceAuth,
- Property,
- createPiece,
-} from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import { sendMessage } from './lib/actions/send-message';
-
-export const matrixAuth = PieceAuth.CustomAuth({
- description: `
- To obtain access token & Home server:
-
- 1. Log in to the account you want to get the access token for on Element.
- 2. Click on the name in the top left corner of the screen, then select "Settings" from the dropdown menu.
- 3. In the Settings dialog, click the "Help & About" tab on the left side of the screen.
- 4. Scroll to the bottom of the page and click on the "click to reveal" part of the "Access Token" section.
- 5. Copy your access token & Home Server URL and paste them into the fields below.
- `,
- props: {
- base_url: Property.ShortText({
- displayName: 'Home Server',
- required: true,
- }),
- access_token: PieceAuth.SecretText({
- displayName: 'Access Token',
- required: true,
- }),
- },
- required: true,
-});
+import { banUser } from './lib/actions/ai/ban-user';
+import { createRoom } from './lib/actions/ai/create-room';
+import { editMessage } from './lib/actions/ai/edit-message';
+import { getCurrentUser } from './lib/actions/ai/get-current-user';
+import { getMessage } from './lib/actions/ai/get-message';
+import { getRoom } from './lib/actions/ai/get-room';
+import { getUserProfile } from './lib/actions/ai/get-user-profile';
+import { inviteUser } from './lib/actions/ai/invite-user';
+import { joinRoom } from './lib/actions/ai/join-room';
+import { kickUser } from './lib/actions/ai/kick-user';
+import { leaveRoom } from './lib/actions/ai/leave-room';
+import { listJoinedRooms } from './lib/actions/ai/list-joined-rooms';
+import { listMessages } from './lib/actions/ai/list-messages';
+import { listRoomMembers } from './lib/actions/ai/list-room-members';
+import { reactToMessage } from './lib/actions/ai/react-to-message';
+import { redactMessage } from './lib/actions/ai/redact-message';
+import { searchPublicRooms } from './lib/actions/ai/search-public-rooms';
+import { searchUsers } from './lib/actions/ai/search-users';
+import { sendTextMessage } from './lib/actions/ai/send-text-message';
+import { setRoomName } from './lib/actions/ai/set-room-name';
+import { setRoomTopic } from './lib/actions/ai/set-room-topic';
+import { unbanUser } from './lib/actions/ai/unban-user';
+import { matrixAuth } from './lib/auth';
+import { matrixClient } from './lib/common/client';
export const matrix = createPiece({
displayName: 'Matrix',
- description:
- 'Open standard for interoperable, decentralized, real-time communication',
-
+ description: 'Open standard for interoperable, decentralized, real-time communication',
logoUrl: 'https://cdn.activepieces.com/pieces/matrix.png',
categories: [PieceCategory.COMMUNICATION],
- minimumSupportedRelease: '0.30.0',
- authors: ["MyWay","kishanprmr","MoShizzle","khaledmashaly","abuaboud"],
+ minimumSupportedRelease: '0.88.2',
+ authors: ['MyWay', 'kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud'],
auth: matrixAuth,
actions: [
sendMessage,
+ banUser,
+ createRoom,
+ editMessage,
+ getCurrentUser,
+ getMessage,
+ getRoom,
+ getUserProfile,
+ inviteUser,
+ joinRoom,
+ kickUser,
+ leaveRoom,
+ listJoinedRooms,
+ listMessages,
+ listRoomMembers,
+ reactToMessage,
+ redactMessage,
+ searchPublicRooms,
+ searchUsers,
+ sendTextMessage,
+ setRoomName,
+ setRoomTopic,
+ unbanUser,
createCustomApiCallAction({
- baseUrl: (auth) => auth?(auth ).props .base_url: '',
auth: matrixAuth,
- authMapping: async (auth) => ({
- Authorization: `Bearer ${
- (auth ).props .access_token
- }`,
- }),
+ baseUrl: (auth) => (auth ? matrixClient.normalizeHomeserver(auth.props.base_url) : ''),
+ authMapping: async (auth, propsValue) => {
+ const baseUrl = matrixClient.normalizeHomeserver(auth.props.base_url);
+ const urlProp = propsValue['url'];
+ const url = matrixClient.isRecord(urlProp) && typeof urlProp['url'] === 'string' ? urlProp['url'].trim() : '';
+ if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//')) {
+ if (!matrixClient.isSameOrigin({ url, baseUrl })) {
+ throw new Error('The URL must be on the Home Server of the connection.');
+ }
+ }
+ if (url.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase() === '%2e%2e')) {
+ throw new Error('The URL must not contain ".." segments.');
+ }
+ return { Authorization: `Bearer ${matrixClient.accessTokenOf(auth.props)}` };
+ },
}),
],
triggers: [],
});
+
+export { matrixAuth };
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/ban-user.ts b/packages/pieces/community/matrix/src/lib/actions/ai/ban-user.ts
new file mode 100644
index 00000000000..aa66c9c9c17
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/ban-user.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const banUser = createAction({
+ auth: matrixAuth,
+ name: 'ban_user',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Ban User',
+ description: 'Ban a user from a room.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Bans a user (@user:server) from a room (roomId !...): removes them if present and blocks rejoining until unban_user. Needs ban power level. Banning an already banned user succeeds and changes nothing.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.membership,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ userId: Property.ShortText({ displayName: 'User ID', description: 'e.g. @alice:example.org', required: true }),
+ reason: Property.ShortText({ displayName: 'Reason', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const userId = matrixIds.userId(propsValue.userId);
+ const reason = matrixClient.optionalText(propsValue.reason);
+ const requestBody: Record<string, unknown> = { user_id: userId };
+ if (reason !== undefined) requestBody['reason'] = reason;
+ await matrixClient.request({ auth: auth.props, method: HttpMethod.POST, path: matrixIds.clientPath('rooms', roomId, 'ban'), body: requestBody });
+ return { roomId, userId, membership: 'ban' };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/create-room.ts b/packages/pieces/community/matrix/src/lib/actions/ai/create-room.ts
new file mode 100644
index 00000000000..7351c5be2c7
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/create-room.ts
@@ -0,0 +1,78 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const createRoom = createAction({
+ auth: matrixAuth,
+ name: 'create_room',
+ classification: 'WRITE',
+ displayName: 'Create Room',
+ description: 'Create a new room, optionally public, with invites.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Creates a new Matrix room owned by this account and returns its roomId (and alias when aliasName was given). preset private_chat (default, invite only), public_chat (anyone can join) or trusted_private_chat (invitees become admins). publishToDirectory lists it in the public room directory. invite takes user IDs (@user:server). aliasName is only the local part (e.g. "team-ops" makes #team-ops:yourserver) and fails if taken. Each call creates another room.',
+ idempotent: false,
+ },
+ outputSchema: matrixOutputSchemas.createdRoom,
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ topic: Property.LongText({ displayName: 'Topic', required: false }),
+ preset: Property.StaticDropdown({
+ displayName: 'Preset',
+ required: false,
+ defaultValue: 'private_chat',
+ options: {
+ options: [
+ { label: 'Private (invite only)', value: 'private_chat' },
+ { label: 'Public (anyone can join)', value: 'public_chat' },
+ { label: 'Trusted private (invitees are admins)', value: 'trusted_private_chat' },
+ ],
+ },
+ }),
+ publishToDirectory: Property.Checkbox({ displayName: 'Publish to Room Directory', required: false, defaultValue: false }),
+ aliasName: Property.ShortText({ displayName: 'Alias (local part)', description: 'e.g. team-ops for #team-ops:yourserver', required: false }),
+ invite: Property.Array({ displayName: 'Invite User IDs', description: 'User IDs like @alice:example.org', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const preset = propsValue.preset ?? 'private_chat';
+ if (!['private_chat', 'public_chat', 'trusted_private_chat'].includes(preset)) {
+ throw new Error('Preset must be private_chat, public_chat or trusted_private_chat.');
+ }
+ const aliasName = matrixClient.optionalText(propsValue.aliasName);
+ if (aliasName !== undefined && !/^[a-z0-9._=/+-]+$/.test(aliasName)) {
+ throw new Error('Alias must be only the local part, using lowercase letters, digits and . _ = - / +.');
+ }
+ const invite = matrixClient.stringList(propsValue.invite).map((user) => matrixIds.userId(user));
+ const requestBody: Record<string, unknown> = {
+ preset,
+ visibility: propsValue.publishToDirectory === true ? 'public' : 'private',
+ };
+ const name = matrixClient.optionalText(propsValue.name);
+ const topic = matrixClient.optionalText(propsValue.topic);
+ if (name !== undefined) requestBody['name'] = name;
+ if (topic !== undefined) requestBody['topic'] = topic;
+ if (aliasName !== undefined) requestBody['room_alias_name'] = aliasName;
+ if (invite.length > 0) requestBody['invite'] = invite;
+ const body = await matrixClient.request({ auth: auth.props, method: HttpMethod.POST, path: matrixIds.clientPath('createRoom'), body: requestBody });
+ const record = matrixClient.isRecord(body) ? body : {};
+ const roomId = matrixClient.stringOr(record['room_id']);
+ if (roomId === null) throw new Error('The homeserver did not return a room ID.');
+ let alias = matrixClient.stringOr(record['room_alias']);
+ if (alias === null && aliasName !== undefined) {
+ try {
+ const state = await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: matrixIds.clientPath('rooms', roomId, 'state', 'm.room.canonical_alias', ''),
+ });
+ alias = matrixClient.isRecord(state) ? matrixClient.stringOr(state['alias']) : null;
+ } catch {
+ alias = null;
+ }
+ }
+ return { roomId, alias };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/edit-message.ts b/packages/pieces/community/matrix/src/lib/actions/ai/edit-message.ts
new file mode 100644
index 00000000000..8761dbf955c
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/edit-message.ts
@@ -0,0 +1,79 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { matrixAuth } from '../../auth';
+import { matrixClient, MatrixAuthValue } from '../../common/client';
+import { matrixCommon } from '../../common/common';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const editMessage = createAction({
+ auth: matrixAuth,
+ name: 'edit_message',
+ classification: 'WRITE',
+ displayName: 'Edit Message',
+ description: 'Replace the text of a message this account sent.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Edits a message previously sent by this account by posting an m.replace edit event; clients then show the new text with an "(edited)" marker. Needs roomId (!...) and eventId ($...) of the original message. Only the original sender can edit, and only text, notice and emote messages; the edit keeps the original message type. The original text stays in the room history. Each call adds a new edit event; a retry after a failed call, or a repeated transactionId, returns the original edit event instead of adding another.',
+ idempotent: false,
+ },
+ outputSchema: matrixOutputSchemas.edited,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ eventId: Property.ShortText({ displayName: 'Event ID', description: 'The message to edit ($...).', required: true }),
+ text: Property.LongText({ displayName: 'New Text', required: true }),
+ format: Property.StaticDropdown({
+ displayName: 'Format',
+ required: false,
+ defaultValue: 'markdown',
+ options: { options: [{ label: 'Markdown', value: 'markdown' }, { label: 'Plain text', value: 'plain' }] },
+ }),
+ transactionId: Property.ShortText({ displayName: 'Transaction ID', required: false }),
+ },
+ async run({ auth, propsValue, run, step }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const eventId = matrixIds.eventId(propsValue.eventId);
+ const text = matrixClient.messageText({ value: propsValue.text, label: 'New Text' });
+ const msgtype = await assertEditable({ auth: auth.props, roomId, eventId });
+ const newContent = await matrixCommon.buildTextContent({ text, msgtype, format: propsValue.format ?? 'markdown' });
+ const content: Record<string, unknown> = {
+ ...newContent,
+ body: `* ${text}`,
+ 'm.new_content': newContent,
+ 'm.relates_to': { rel_type: 'm.replace', event_id: eventId },
+ };
+ if (typeof newContent['formatted_body'] === 'string') content['formatted_body'] = `* ${newContent['formatted_body']}`;
+ const sent = await matrixIds.withTransactionId({
+ value: propsValue.transactionId,
+ run,
+ step,
+ parts: [roomId, content],
+ send: (txnId) => matrixCommon.sendEvent({ auth: auth.props, roomId, eventType: 'm.room.message', content, txnId }),
+ });
+ return { ...sent, editedEventId: eventId };
+ },
+});
+
+async function assertEditable({ auth, roomId, eventId }: { auth: MatrixAuthValue; roomId: string; eventId: string }): Promise<string> {
+ const [original, me] = await Promise.all([
+ matrixClient.request({ auth, method: HttpMethod.GET, path: matrixIds.clientPath('rooms', roomId, 'event', eventId) }),
+ matrixClient.request({ auth, method: HttpMethod.GET, path: matrixIds.clientPath('account', 'whoami') }),
+ ]);
+ const event = matrixCommon.mapEvent({ raw: original, roomId });
+ const userId = matrixClient.isRecord(me) ? matrixClient.stringOr(me['user_id']) : null;
+ if (userId === null) throw new Error('The homeserver did not return the connected user ID.');
+ if (event.sender !== userId) {
+ throw new Error(`Only the original sender can edit a message. ${eventId} was sent by ${event.sender ?? 'an unknown user'}, not ${userId}.`);
+ }
+ if (event.redacted) throw new Error(`Message ${eventId} was deleted and cannot be edited.`);
+ if (event.type !== 'm.room.message') throw new Error(`Event ${eventId} is not a message (type ${event.type ?? 'unknown'}).`);
+ if (event.relType === 'm.replace') {
+ throw new Error(`Event ${eventId} is itself an edit. Edit the original message ${event.relatesToEventId ?? ''} instead.`.trim());
+ }
+ const msgtype = event.msgtype ?? 'm.text';
+ if (!matrixCommon.MSG_TYPES.includes(msgtype)) {
+ throw new Error(`Message ${eventId} is a ${msgtype} message; only text, notice and emote messages can be edited.`);
+ }
+ return msgtype;
+}
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/get-current-user.ts b/packages/pieces/community/matrix/src/lib/actions/ai/get-current-user.ts
new file mode 100644
index 00000000000..07c0243a7c0
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/get-current-user.ts
@@ -0,0 +1,31 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const getCurrentUser = createAction({
+ auth: matrixAuth,
+ name: 'get_current_user',
+ classification: 'READ',
+ displayName: 'Get Current User',
+ description: 'Get the Matrix user ID and device of this connection.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns the user ID (@name:server), device ID and guest flag of the account behind this connection, plus the homeserver URL. Use it to learn who "me" is before acting on rooms. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.currentUser,
+ props: {},
+ async run({ auth }) {
+ const body = await matrixClient.request({ auth: auth.props, method: HttpMethod.GET, path: matrixIds.clientPath('account', 'whoami') });
+ const record = matrixClient.isRecord(body) ? body : {};
+ return {
+ userId: matrixClient.stringOr(record['user_id']),
+ deviceId: matrixClient.stringOr(record['device_id']),
+ isGuest: record['is_guest'] === true,
+ homeserver: matrixClient.normalizeHomeserver(auth.props.base_url),
+ };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/get-message.ts b/packages/pieces/community/matrix/src/lib/actions/ai/get-message.ts
new file mode 100644
index 00000000000..c59a7927ff1
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/get-message.ts
@@ -0,0 +1,36 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixCommon } from '../../common/common';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const getMessage = createAction({
+ auth: matrixAuth,
+ name: 'get_message',
+ classification: 'READ',
+ displayName: 'Get Message',
+ description: 'Get one event (message) from a room by its ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Fetches one event by roomId (!...) and eventId ($...) and returns sender, type, body, formattedBody, timestamp and relation fields. Encrypted events come back with encrypted true and no body (this piece cannot decrypt). Read-only.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.event,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ eventId: Property.ShortText({ displayName: 'Event ID', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const eventId = matrixIds.eventId(propsValue.eventId);
+ const body = await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: matrixIds.clientPath('rooms', roomId, 'event', eventId),
+ });
+ return matrixCommon.mapEvent({ raw: body, roomId });
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/get-room.ts b/packages/pieces/community/matrix/src/lib/actions/ai/get-room.ts
new file mode 100644
index 00000000000..43b848d97db
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/get-room.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixCommon } from '../../common/common';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const getRoom = createAction({
+ auth: matrixAuth,
+ name: 'get_room',
+ classification: 'READ',
+ displayName: 'Get Room',
+ description: 'Get a room\'s name, topic, alias, encryption and member counts. Accepts an alias.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Looks up a room by room ID (!...) or alias (#room:server) and returns roomId, name, topic, canonicalAlias, encrypted, joinRule, historyVisibility, roomVersion, creator, roomType (m.space for spaces) and joined/invited member counts. Use it to turn an alias into a room ID. The account must be in the room (or the room must be world-readable). Read-only.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.room,
+ props: {
+ room: Property.ShortText({ displayName: 'Room', description: 'Room ID (!...) or alias (#...).', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = await matrixCommon.resolveRoom({ auth: auth.props, room: propsValue.room });
+ const body = await matrixClient.request({ auth: auth.props, method: HttpMethod.GET, path: matrixIds.clientPath('rooms', roomId, 'state') });
+ const events = matrixClient.arrayOf(body);
+ const create = contentOf({ events, type: 'm.room.create' });
+ const aliases = contentOf({ events, type: 'm.room.canonical_alias' });
+ const memberships = events
+ .filter((item) => matrixClient.isRecord(item) && item['type'] === 'm.room.member')
+ .map((item) => (matrixClient.isRecord(item) && matrixClient.isRecord(item['content']) ? item['content']['membership'] : undefined));
+ const createEvent = events.find((item) => matrixClient.isRecord(item) && item['type'] === 'm.room.create');
+ return {
+ roomId,
+ name: matrixClient.stringOr(contentOf({ events, type: 'm.room.name' })['name']),
+ topic: matrixClient.stringOr(contentOf({ events, type: 'm.room.topic' })['topic']),
+ canonicalAlias: matrixClient.stringOr(aliases['alias']),
+ altAliases: matrixClient.arrayOf(aliases['alt_aliases']).filter((alias): alias is string => typeof alias === 'string'),
+ encrypted: Object.keys(contentOf({ events, type: 'm.room.encryption' })).length > 0,
+ joinRule: matrixClient.stringOr(contentOf({ events, type: 'm.room.join_rules' })['join_rule']),
+ historyVisibility: matrixClient.stringOr(contentOf({ events, type: 'm.room.history_visibility' })['history_visibility']),
+ roomVersion: matrixClient.stringOr(create['room_version']) ?? '1',
+ creator: matrixClient.stringOr(create['creator']) ?? (matrixClient.isRecord(createEvent) ? matrixClient.stringOr(createEvent['sender']) : null),
+ roomType: matrixClient.stringOr(create['type']),
+ joinedMemberCount: memberships.filter((m) => m === 'join').length,
+ invitedMemberCount: memberships.filter((m) => m === 'invite').length,
+ };
+ },
+});
+
+function contentOf({ events, type }: { events: unknown[]; type: string }): Record<string, unknown> {
+ const event = events.find((item) => matrixClient.isRecord(item) && item['type'] === type && item['state_key'] === '');
+ return matrixClient.isRecord(event) && matrixClient.isRecord(event['content']) ? event['content'] : {};
+}
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/get-user-profile.ts b/packages/pieces/community/matrix/src/lib/actions/ai/get-user-profile.ts
new file mode 100644
index 00000000000..50111576d57
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/get-user-profile.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const getUserProfile = createAction({
+ auth: matrixAuth,
+ name: 'get_user_profile',
+ classification: 'READ',
+ displayName: 'Get User Profile',
+ description: 'Get the display name and avatar of a user.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns the global display name and avatar mxc URI of a user ID (@user:server), on any server. Fails with not found when the user does not exist or hides their profile. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.profile,
+ props: {
+ userId: Property.ShortText({ displayName: 'User ID', description: 'e.g. @alice:example.org', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const userId = matrixIds.userId(propsValue.userId);
+ const body = await matrixClient.request({ auth: auth.props, method: HttpMethod.GET, path: matrixIds.clientPath('profile', userId) });
+ const record = matrixClient.isRecord(body) ? body : {};
+ return { userId, displayName: matrixClient.stringOr(record['displayname']), avatarUrl: matrixClient.stringOr(record['avatar_url']) };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/invite-user.ts b/packages/pieces/community/matrix/src/lib/actions/ai/invite-user.ts
new file mode 100644
index 00000000000..0a455473a49
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/invite-user.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const inviteUser = createAction({
+ auth: matrixAuth,
+ name: 'invite_user',
+ classification: 'WRITE',
+ displayName: 'Invite User',
+ description: 'Invite a user to a room.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Invites a user (@user:server) to a room (roomId !...) this account is in; the user must accept before joining. Needs invite power level in the room. Inviting a user whose invite is still pending succeeds and changes nothing; it errors if the user has already joined or is banned (unban first).',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.membership,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ userId: Property.ShortText({ displayName: 'User ID', description: 'e.g. @alice:example.org', required: true }),
+ reason: Property.ShortText({ displayName: 'Reason', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const userId = matrixIds.userId(propsValue.userId);
+ const reason = matrixClient.optionalText(propsValue.reason);
+ const requestBody: Record<string, unknown> = { user_id: userId };
+ if (reason !== undefined) requestBody['reason'] = reason;
+ await matrixClient.request({ auth: auth.props, method: HttpMethod.POST, path: matrixIds.clientPath('rooms', roomId, 'invite'), body: requestBody });
+ return { roomId, userId, membership: 'invite' };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/join-room.ts b/packages/pieces/community/matrix/src/lib/actions/ai/join-room.ts
new file mode 100644
index 00000000000..912dd402c9d
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/join-room.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const joinRoom = createAction({
+ auth: matrixAuth,
+ name: 'join_room',
+ classification: 'WRITE',
+ displayName: 'Join Room',
+ description: 'Join a room by ID or alias, or accept an invite.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Joins a room (or accepts a pending invite) by room ID (!...) or alias (#room:server) and returns the roomId. Rooms on other servers may need via (server names that are in the room). Joining a room the account is already in succeeds and changes nothing. Fails for invite-only rooms without an invite.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.joinedRoom,
+ props: {
+ room: Property.ShortText({ displayName: 'Room', description: 'Room ID (!...) or alias (#...).', required: true }),
+ via: Property.Array({ displayName: 'Via Servers', description: 'Optional server names, e.g. matrix.org', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const room = matrixIds.roomIdOrAlias(propsValue.room);
+ const via = matrixClient.stringList(propsValue.via);
+ if (via.some((server) => !matrixClient.isServerName(server))) {
+ throw new Error('Via servers must be server names like matrix.org.');
+ }
+ const query = via.length > 0 ? `?${via.map((server) => `via=${encodeURIComponent(server)}`).join('&')}` : '';
+ const body = await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: `${matrixIds.clientPath('join', room)}${query}`,
+ body: {},
+ });
+ const roomId = matrixClient.isRecord(body) ? matrixClient.stringOr(body['room_id']) : null;
+ if (roomId === null) throw new Error('The homeserver did not return a room ID.');
+ return { roomId };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/kick-user.ts b/packages/pieces/community/matrix/src/lib/actions/ai/kick-user.ts
new file mode 100644
index 00000000000..2503fd52f36
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/kick-user.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const kickUser = createAction({
+ auth: matrixAuth,
+ name: 'kick_user',
+ classification: 'WRITE',
+ displayName: 'Kick User',
+ description: 'Remove a user from a room.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Removes a user (@user:server) from a room (roomId !...), or revokes their pending invite. They can rejoin if the room allows it (use ban_user to stop that). Needs kick power level. Errors if the user is neither joined nor invited (e.g. on a repeat call).',
+ idempotent: false,
+ },
+ outputSchema: matrixOutputSchemas.membership,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ userId: Property.ShortText({ displayName: 'User ID', description: 'e.g. @alice:example.org', required: true }),
+ reason: Property.ShortText({ displayName: 'Reason', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const userId = matrixIds.userId(propsValue.userId);
+ const reason = matrixClient.optionalText(propsValue.reason);
+ const requestBody: Record<string, unknown> = { user_id: userId };
+ if (reason !== undefined) requestBody['reason'] = reason;
+ await matrixClient.request({ auth: auth.props, method: HttpMethod.POST, path: matrixIds.clientPath('rooms', roomId, 'kick'), body: requestBody });
+ return { roomId, userId, membership: 'leave' };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/leave-room.ts b/packages/pieces/community/matrix/src/lib/actions/ai/leave-room.ts
new file mode 100644
index 00000000000..694363cbc60
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/leave-room.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const leaveRoom = createAction({
+ auth: matrixAuth,
+ name: 'leave_room',
+ classification: 'WRITE',
+ displayName: 'Leave Room',
+ description: 'Leave a room (or reject an invite), optionally forgetting it.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Leaves a room, or rejects a pending invite, by roomId (!...). With forget true the room is also removed from this account\'s room list and history. Rejoining a private room afterwards needs a new invite. Leaving again succeeds.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.leftRoom,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ forget: Property.Checkbox({ displayName: 'Forget Room', required: false, defaultValue: false }),
+ reason: Property.ShortText({ displayName: 'Reason', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const reason = matrixClient.optionalText(propsValue.reason);
+ await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: matrixIds.clientPath('rooms', roomId, 'leave'),
+ body: reason === undefined ? {} : { reason },
+ });
+ const forget = propsValue.forget === true;
+ if (forget) {
+ await matrixClient.request({ auth: auth.props, method: HttpMethod.POST, path: matrixIds.clientPath('rooms', roomId, 'forget'), body: {} });
+ }
+ return { roomId, left: true, forgotten: forget };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/list-joined-rooms.ts b/packages/pieces/community/matrix/src/lib/actions/ai/list-joined-rooms.ts
new file mode 100644
index 00000000000..d1f13919cfe
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/list-joined-rooms.ts
@@ -0,0 +1,36 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixCommon } from '../../common/common';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const listJoinedRooms = createAction({
+ auth: matrixAuth,
+ name: 'list_joined_rooms',
+ classification: 'SEARCH',
+ displayName: 'List Joined Rooms',
+ description: 'List the rooms this account has joined, with their names.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists rooms the account is joined to, with room ID and name (null when the room has no name, e.g. most direct chats). Returns up to limit (1-100, default 50) rooms starting at offset; total is the number of joined rooms and nextOffset the offset of the next page (null at the end). Read-only.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.joinedRooms,
+ props: {
+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 50.', required: false }),
+ offset: Property.Number({ displayName: 'Offset', description: 'Default 0.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const limit = matrixClient.parseLimit({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 50 });
+ const offset = matrixClient.parseLimit({ value: propsValue.offset, label: 'Offset', min: 0, max: Number.MAX_SAFE_INTEGER, fallback: 0 });
+ const all = await matrixCommon.joinedRoomIds({ auth: auth.props });
+ const page = all.slice(offset, offset + limit);
+ const items = await matrixCommon.mapLimited({
+ items: page,
+ limit: 5,
+ fn: async (roomId) => ({ roomId, name: await matrixCommon.roomName({ auth: auth.props, roomId }) }),
+ });
+ const next = offset + page.length;
+ return { items, count: items.length, total: all.length, hasMore: next < all.length, nextOffset: next < all.length ? next : null };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/list-messages.ts b/packages/pieces/community/matrix/src/lib/actions/ai/list-messages.ts
new file mode 100644
index 00000000000..01928ae5d36
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/list-messages.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixCommon } from '../../common/common';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const listMessages = createAction({
+ auth: matrixAuth,
+ name: 'list_messages',
+ classification: 'SEARCH',
+ displayName: 'List Messages',
+ description: 'List recent events in a room, newest first.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the timeline of a room, newest first, up to limit (1-100, default 20). room accepts a room ID or alias. By default only m.room.message events are returned; set messagesOnly false to include reactions, state and other events. When hasMore is true pass nextToken back as from for the next older page. Encrypted rooms return encrypted true events without body. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.listMessages,
+ props: {
+ room: Property.ShortText({ displayName: 'Room', description: 'Room ID (!...) or alias (#...).', required: true }),
+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 20.', required: false }),
+ from: Property.ShortText({ displayName: 'From', description: 'nextToken of the previous page.', required: false }),
+ messagesOnly: Property.Checkbox({ displayName: 'Messages Only', required: false, defaultValue: true }),
+ },
+ async run({ auth, propsValue }) {
+ const limit = matrixClient.parseLimit({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 20 });
+ const from = matrixClient.optionalText(propsValue.from);
+ const messagesOnly = propsValue.messagesOnly !== false;
+ const roomId = await matrixCommon.resolveRoom({ auth: auth.props, room: propsValue.room });
+ const body = await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: matrixIds.clientPath('rooms', roomId, 'messages'),
+ query: {
+ dir: 'b',
+ limit,
+ from,
+ filter: messagesOnly ? JSON.stringify({ types: ['m.room.message', 'm.room.encrypted'] }) : undefined,
+ },
+ });
+ const record = matrixClient.isRecord(body) ? body : {};
+ const items = matrixClient.arrayOf(record['chunk']).map((event) => matrixCommon.mapEvent({ raw: event, roomId }));
+ const end = matrixClient.stringOr(record['end']);
+ return { items, count: items.length, hasMore: end !== null, nextToken: end };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/list-room-members.ts b/packages/pieces/community/matrix/src/lib/actions/ai/list-room-members.ts
new file mode 100644
index 00000000000..372d355c1de
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/list-room-members.ts
@@ -0,0 +1,33 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const listRoomMembers = createAction({
+ auth: matrixAuth,
+ name: 'list_room_members',
+ classification: 'SEARCH',
+ displayName: 'List Room Members',
+ description: 'List the joined members of a room.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists every joined member of a room (roomId !...) with user ID, display name and avatar mxc URI. Invited, left and banned users are not included. The account must be in the room. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.members,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const body = await matrixClient.request({ auth: auth.props, method: HttpMethod.GET, path: matrixIds.clientPath('rooms', roomId, 'joined_members') });
+ const joined = matrixClient.isRecord(body) && matrixClient.isRecord(body['joined']) ? body['joined'] : {};
+ const items = Object.entries(joined).map(([userId, info]) => {
+ const record = matrixClient.isRecord(info) ? info : {};
+ return { userId, displayName: matrixClient.stringOr(record['display_name']), avatarUrl: matrixClient.stringOr(record['avatar_url']) };
+ });
+ return { items, count: items.length };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/react-to-message.ts b/packages/pieces/community/matrix/src/lib/actions/ai/react-to-message.ts
new file mode 100644
index 00000000000..97942609d7b
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/react-to-message.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { matrixAuth } from '../../auth';
+import { MatrixApiError, matrixClient } from '../../common/client';
+import { matrixCommon } from '../../common/common';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const reactToMessage = createAction({
+ auth: matrixAuth,
+ name: 'react_to_message',
+ classification: 'WRITE',
+ displayName: 'React to Message',
+ description: 'Add an emoji reaction to a message.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds a reaction (usually one emoji such as 👍) to an event in a room. Needs roomId (!...) and eventId ($...). If this account already reacted with the same key the call succeeds with alreadyReacted true and no new event. Remove a reaction with redact_message on the reaction event ID.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.reaction,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ eventId: Property.ShortText({ displayName: 'Event ID', required: true }),
+ key: Property.ShortText({ displayName: 'Reaction', description: 'Usually a single emoji, e.g. 👍', required: true }),
+ transactionId: Property.ShortText({ displayName: 'Transaction ID', required: false }),
+ },
+ async run({ auth, propsValue, run, step }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const eventId = matrixIds.eventId(propsValue.eventId);
+ const key = matrixClient.requiredText({ value: propsValue.key, label: 'Reaction' });
+ return matrixIds.withTransactionId({
+ value: propsValue.transactionId,
+ run,
+ step,
+ parts: [roomId, eventId, key],
+ send: async (txnId) => {
+ try {
+ const sent = await matrixCommon.sendEvent({
+ auth: auth.props,
+ roomId,
+ eventType: 'm.reaction',
+ content: { 'm.relates_to': { rel_type: 'm.annotation', event_id: eventId, key } },
+ txnId,
+ });
+ return { eventId: sent.eventId, roomId, reactedToEventId: eventId, key, alreadyReacted: false, transactionId: txnId };
+ } catch (error) {
+ if (error instanceof MatrixApiError && error.errcode === 'M_DUPLICATE_ANNOTATION') {
+ return { eventId: null, roomId, reactedToEventId: eventId, key, alreadyReacted: true, transactionId: txnId };
+ }
+ throw error;
+ }
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/redact-message.ts b/packages/pieces/community/matrix/src/lib/actions/ai/redact-message.ts
new file mode 100644
index 00000000000..e81754d30c2
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/redact-message.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const redactMessage = createAction({
+ auth: matrixAuth,
+ name: 'redact_message',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete (Redact) Message',
+ description: 'Redact a message or reaction, removing its content for everyone.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Redacts (deletes) an event in a room: its content is stripped for every member and cannot be restored. Works on messages, edits and reactions. Needs roomId (!...) and eventId ($...); other users\' events need moderator power level. Redacting an already redacted event succeeds and changes nothing.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.redaction,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ eventId: Property.ShortText({ displayName: 'Event ID', required: true }),
+ reason: Property.ShortText({ displayName: 'Reason', required: false }),
+ transactionId: Property.ShortText({ displayName: 'Transaction ID', required: false }),
+ },
+ async run({ auth, propsValue, run, step }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const eventId = matrixIds.eventId(propsValue.eventId);
+ const reason = matrixClient.optionalText(propsValue.reason);
+ return matrixIds.withTransactionId({
+ value: propsValue.transactionId,
+ run,
+ step,
+ parts: [roomId, eventId, reason ?? null],
+ send: async (txnId) => {
+ const body = await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.PUT,
+ path: matrixIds.clientPath('rooms', roomId, 'redact', eventId, txnId),
+ body: reason === undefined ? {} : { reason },
+ });
+ return {
+ redactionEventId: matrixClient.isRecord(body) ? matrixClient.stringOr(body['event_id']) : null,
+ roomId,
+ redactedEventId: eventId,
+ transactionId: txnId,
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/search-public-rooms.ts b/packages/pieces/community/matrix/src/lib/actions/ai/search-public-rooms.ts
new file mode 100644
index 00000000000..36525d0b7bb
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/search-public-rooms.ts
@@ -0,0 +1,67 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const searchPublicRooms = createAction({
+ auth: matrixAuth,
+ name: 'search_public_rooms',
+ classification: 'SEARCH',
+ displayName: 'Search Public Rooms',
+ description: 'Search the homeserver\'s public room directory.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Searches the public room directory of the connection\'s homeserver (or of server, e.g. matrix.org) by a term matched against name, topic and alias. Returns up to limit (1-100, default 20) rooms; when hasMore is true pass nextToken back as since for the next page. Leave query empty to browse. Read-only; does not join anything.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.publicRooms,
+ props: {
+ query: Property.ShortText({ displayName: 'Search Term', required: false }),
+ server: Property.ShortText({ displayName: 'Server', description: 'Directory of another server, e.g. matrix.org. Empty = your homeserver.', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 20.', required: false }),
+ since: Property.ShortText({ displayName: 'Since', description: 'nextToken of the previous page.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const limit = matrixClient.parseLimit({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 20 });
+ const term = matrixClient.optionalText(propsValue.query);
+ const server = matrixClient.optionalText(propsValue.server);
+ if (server !== undefined && !matrixClient.isServerName(server)) {
+ throw new Error('Server must be a server name like matrix.org.');
+ }
+ const requestBody: Record<string, unknown> = { limit };
+ const since = matrixClient.optionalText(propsValue.since);
+ if (since !== undefined) requestBody['since'] = since;
+ if (term !== undefined) requestBody['filter'] = { generic_search_term: term };
+ const body = await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: matrixIds.clientPath('publicRooms'),
+ query: { server },
+ body: requestBody,
+ });
+ const record = matrixClient.isRecord(body) ? body : {};
+ const items = matrixClient.arrayOf(record['chunk']).map(mapPublicRoom);
+ const next = matrixClient.stringOr(record['next_batch']);
+ const total = record['total_room_count_estimate'];
+ return { items, count: items.length, totalEstimate: typeof total === 'number' ? total : null, hasMore: next !== null, nextToken: next };
+ },
+});
+
+function mapPublicRoom(raw: unknown) {
+ const room = matrixClient.isRecord(raw) ? raw : {};
+ const members = room['num_joined_members'];
+ return {
+ roomId: matrixClient.stringOr(room['room_id']),
+ name: matrixClient.stringOr(room['name']),
+ topic: matrixClient.stringOr(room['topic']),
+ canonicalAlias: matrixClient.stringOr(room['canonical_alias']),
+ numJoinedMembers: typeof members === 'number' ? members : null,
+ worldReadable: room['world_readable'] === true,
+ guestCanJoin: room['guest_can_join'] === true,
+ joinRule: matrixClient.stringOr(room['join_rule']),
+ roomType: matrixClient.stringOr(room['room_type']),
+ avatarUrl: matrixClient.stringOr(room['avatar_url']),
+ };
+}
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/search-users.ts b/packages/pieces/community/matrix/src/lib/actions/ai/search-users.ts
new file mode 100644
index 00000000000..06bfde124e6
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/search-users.ts
@@ -0,0 +1,44 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const searchUsers = createAction({
+ auth: matrixAuth,
+ name: 'search_users',
+ classification: 'SEARCH',
+ displayName: 'Search Users',
+ description: 'Search the user directory by name or user ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Searches the homeserver user directory by display name or user ID and returns up to limit (1-50, default 10) users. Most servers only return users who share a room with this account or are in public rooms. limited true means more matched than returned; refine the term. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.searchUsers,
+ props: {
+ query: Property.ShortText({ displayName: 'Search Term', required: true }),
+ limit: Property.Number({ displayName: 'Limit', description: '1-50, default 10.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const term = matrixClient.requiredText({ value: propsValue.query, label: 'Search Term' });
+ const limit = matrixClient.parseLimit({ value: propsValue.limit, label: 'Limit', min: 1, max: 50, fallback: 10 });
+ const body = await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: matrixIds.clientPath('user_directory', 'search'),
+ body: { search_term: term, limit },
+ });
+ const record = matrixClient.isRecord(body) ? body : {};
+ const items = matrixClient.arrayOf(record['results']).map((raw) => {
+ const user = matrixClient.isRecord(raw) ? raw : {};
+ return {
+ userId: matrixClient.stringOr(user['user_id']),
+ displayName: matrixClient.stringOr(user['display_name']),
+ avatarUrl: matrixClient.stringOr(user['avatar_url']),
+ };
+ });
+ return { items, count: items.length, limited: record['limited'] === true };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/send-text-message.ts b/packages/pieces/community/matrix/src/lib/actions/ai/send-text-message.ts
new file mode 100644
index 00000000000..ba85185d9be
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/send-text-message.ts
@@ -0,0 +1,62 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixCommon } from '../../common/common';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const sendTextMessage = createAction({
+ auth: matrixAuth,
+ name: 'send_text_message',
+ classification: 'WRITE',
+ displayName: 'Send Text Message',
+ description: 'Send a text, notice or emote message to a room, optionally as a reply.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Posts a message to a Matrix room the account has joined. room accepts a room ID (!abc:server) or an alias (#room:server). format markdown (default) also sends sanitized HTML; plain sends text only. msgtype m.text (default), m.notice (bot-style) or m.emote (/me). Set replyToEventId to send it as a reply to that event. Each call posts a new message. If a send fails (for example a timeout after the server stored it), the automatic retry of that same send reuses its transaction ID, so the server returns the original eventId instead of posting twice. Passing a transactionId that repeats a previous call from the same connection also returns the original eventId. Text sent into an end-to-end encrypted room is delivered unencrypted.',
+ idempotent: false,
+ },
+ outputSchema: matrixOutputSchemas.sent,
+ props: {
+ room: Property.ShortText({ displayName: 'Room', description: 'Room ID (!abc:server) or alias (#room:server).', required: true }),
+ text: Property.LongText({ displayName: 'Text', required: true }),
+ format: Property.StaticDropdown({
+ displayName: 'Format',
+ required: false,
+ defaultValue: 'markdown',
+ options: { options: [{ label: 'Markdown', value: 'markdown' }, { label: 'Plain text', value: 'plain' }] },
+ }),
+ msgtype: Property.StaticDropdown({
+ displayName: 'Message Type',
+ required: false,
+ defaultValue: 'm.text',
+ options: { options: [{ label: 'Text', value: 'm.text' }, { label: 'Notice', value: 'm.notice' }, { label: 'Emote', value: 'm.emote' }] },
+ }),
+ replyToEventId: Property.ShortText({ displayName: 'Reply To Event ID', description: 'Event ID ($...) to reply to.', required: false }),
+ transactionId: Property.ShortText({
+ displayName: 'Transaction ID',
+ description: 'Optional. Reuse the same value to retry a send without posting twice.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue, run, step }) {
+ const text = matrixClient.messageText({ value: propsValue.text, label: 'Text' });
+ const replyText = matrixClient.optionalText(propsValue.replyToEventId);
+ const replyTo = replyText === undefined ? undefined : matrixIds.eventId(replyText);
+ const content = await matrixCommon.buildTextContent({
+ text,
+ msgtype: propsValue.msgtype ?? 'm.text',
+ format: propsValue.format ?? 'markdown',
+ });
+ if (replyTo) content['m.relates_to'] = { 'm.in_reply_to': { event_id: replyTo } };
+ const roomId = await matrixCommon.resolveRoom({ auth: auth.props, room: propsValue.room });
+ return matrixIds.withTransactionId({
+ value: propsValue.transactionId,
+ run,
+ step,
+ parts: [roomId, content],
+ send: (txnId) => matrixCommon.sendEvent({ auth: auth.props, roomId, eventType: 'm.room.message', content, txnId }),
+ });
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/set-room-name.ts b/packages/pieces/community/matrix/src/lib/actions/ai/set-room-name.ts
new file mode 100644
index 00000000000..dbedf6461aa
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/set-room-name.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const setRoomName = createAction({
+ auth: matrixAuth,
+ name: 'set_room_name',
+ classification: 'WRITE',
+ displayName: 'Set Room Name',
+ description: 'Rename a room.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Sets the display name of a room (roomId !...). An empty name clears it, so clients fall back to the alias or member names. Needs state-event power level. Setting the same name again is harmless.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.stateSet,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ name: Property.ShortText({ displayName: 'Name', description: 'Leave empty to clear it.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const value = typeof propsValue.name === 'string' ? propsValue.name.trim() : '';
+ const body = await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.PUT,
+ path: matrixIds.clientPath('rooms', roomId, 'state', 'm.room.name', ''),
+ body: { name: value },
+ });
+ return { eventId: matrixClient.isRecord(body) ? matrixClient.stringOr(body['event_id']) : null, roomId };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/set-room-topic.ts b/packages/pieces/community/matrix/src/lib/actions/ai/set-room-topic.ts
new file mode 100644
index 00000000000..02d83466937
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/set-room-topic.ts
@@ -0,0 +1,35 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const setRoomTopic = createAction({
+ auth: matrixAuth,
+ name: 'set_room_topic',
+ classification: 'WRITE',
+ displayName: 'Set Room Topic',
+ description: 'Set the topic of a room.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Sets the topic (description line) of a room (roomId !...). An empty topic clears it. Needs state-event power level. Setting the same topic again is harmless.',
+ idempotent: true,
+ },
+ outputSchema: matrixOutputSchemas.stateSet,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ topic: Property.ShortText({ displayName: 'Topic', description: 'Leave empty to clear it.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const value = typeof propsValue.topic === 'string' ? propsValue.topic.trim() : '';
+ const body = await matrixClient.request({
+ auth: auth.props,
+ method: HttpMethod.PUT,
+ path: matrixIds.clientPath('rooms', roomId, 'state', 'm.room.topic', ''),
+ body: { topic: value },
+ });
+ return { eventId: matrixClient.isRecord(body) ? matrixClient.stringOr(body['event_id']) : null, roomId };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/ai/unban-user.ts b/packages/pieces/community/matrix/src/lib/actions/ai/unban-user.ts
new file mode 100644
index 00000000000..62523cef667
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/actions/ai/unban-user.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixAuth } from '../../auth';
+import { matrixClient } from '../../common/client';
+import { matrixIds } from '../../common/ids';
+import { matrixOutputSchemas } from '../../common/output-schemas';
+
+export const unbanUser = createAction({
+ auth: matrixAuth,
+ name: 'unban_user',
+ classification: 'WRITE',
+ displayName: 'Unban User',
+ description: 'Lift a ban so the user can rejoin.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lifts the ban of a user (@user:server) in a room (roomId !...). It does not re-invite or rejoin them. Needs ban power level. Errors (M_BAD_STATE) if the user is not banned, e.g. on a repeat call.',
+ idempotent: false,
+ },
+ outputSchema: matrixOutputSchemas.membership,
+ props: {
+ roomId: Property.ShortText({ displayName: 'Room ID', required: true }),
+ userId: Property.ShortText({ displayName: 'User ID', description: 'e.g. @alice:example.org', required: true }),
+ reason: Property.ShortText({ displayName: 'Reason', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const roomId = matrixIds.roomId(propsValue.roomId);
+ const userId = matrixIds.userId(propsValue.userId);
+ const reason = matrixClient.optionalText(propsValue.reason);
+ const requestBody: Record<string, unknown> = { user_id: userId };
+ if (reason !== undefined) requestBody['reason'] = reason;
+ await matrixClient.request({ auth: auth.props, method: HttpMethod.POST, path: matrixIds.clientPath('rooms', roomId, 'unban'), body: requestBody });
+ return { roomId, userId, membership: 'leave' };
+ },
+});
diff --git a/packages/pieces/community/matrix/src/lib/actions/send-message.ts b/packages/pieces/community/matrix/src/lib/actions/send-message.ts
index 257da129000..7587f4aa4d6 100644
--- a/packages/pieces/community/matrix/src/lib/actions/send-message.ts
+++ b/packages/pieces/community/matrix/src/lib/actions/send-message.ts
@@ -1,6 +1,46 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { getRoomId, sendMessage as sendMatrixMessage } from '../common/common';
-import { matrixAuth } from '../..';
+import { matrixAuth } from '../auth';
+import { matrixClient } from '../common/client';
+import { matrixCommon } from '../common/common';
+import { matrixIds } from '../common/ids';
+import { matrixOutputSchemas } from '../common/output-schemas';
+
+const MAX_DROPDOWN_ROOMS = 200;
+
+const roomDropdown = Property.Dropdown({
+ auth: matrixAuth,
+ displayName: 'Room',
+ description: 'Pick one of the rooms this account has joined, or fill Room Alias instead.',
+ required: false,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, placeholder: 'Connect your Matrix account first', options: [] };
+ }
+ try {
+ const rooms = await matrixCommon.joinedRoomIds({ auth: auth.props });
+ const shown = rooms.slice(0, MAX_DROPDOWN_ROOMS);
+ const options = await matrixCommon.mapLimited({
+ items: shown,
+ limit: 5,
+ fn: async (roomId) => ({ label: (await matrixCommon.roomName({ auth: auth.props, roomId })) ?? roomId, value: roomId }),
+ });
+ options.sort((a, b) => a.label.localeCompare(b.label));
+ return {
+ disabled: false,
+ options,
+ placeholder:
+ rooms.length > shown.length ? `Showing ${shown.length} of ${rooms.length} rooms; use Room Alias for others` : undefined,
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ placeholder: error instanceof Error ? `Could not load rooms: ${error.message}` : 'Could not load rooms',
+ options: [],
+ };
+ }
+ },
+});
export const sendMessage = createAction({
auth: matrixAuth,
@@ -8,14 +48,15 @@ export const sendMessage = createAction({
classification: 'WRITE',
displayName: 'Send Message',
description: 'Send a message to a room',
- audience: 'both',
- aiMetadata: { description: 'Posts a markdown message to a Matrix room, resolving the room alias to its internal room ID first. Use to deliver chat notifications or updates to a Matrix/Element channel. Requires the room alias (from room settings -> advanced -> room addresses -> main address); not idempotent, as each call posts a new message.', idempotent: false },
+ audience: 'human',
+ outputSchema: matrixOutputSchemas.sent,
props: {
+ room: roomDropdown,
room_alias: Property.ShortText({
displayName: 'Room Alias',
description:
- 'Copy it from room settings -> advanced -> room addresses -> main address',
- required: true,
+ 'Used when no Room is picked, e.g. #room:example.org',
+ required: false,
}),
message: Property.LongText({
displayName: 'Message',
@@ -23,18 +64,24 @@ export const sendMessage = createAction({
required: true,
}),
},
- async run({ auth, propsValue }) {
- const baseUrl = auth.props.base_url.replace(/\/$/, '');
- const accessToken = auth.props.access_token;
- const roomId = (
- await getRoomId(baseUrl, propsValue.room_alias, accessToken)
- ).body.room_id;
-
- return await sendMatrixMessage(
- baseUrl,
- roomId,
- accessToken,
- propsValue.message
- );
+ async run({ auth, propsValue, run, step }) {
+ const message = matrixClient.messageText({ value: propsValue.message, label: 'Message' });
+ const picked = matrixClient.optionalText(propsValue.room);
+ const alias = matrixClient.optionalText(propsValue.room_alias);
+ if (picked === undefined && alias === undefined) {
+ throw new Error('Pick a Room or fill Room Alias.');
+ }
+ const roomId =
+ picked !== undefined
+ ? matrixIds.roomId(picked)
+ : (await matrixCommon.resolveAlias({ auth: auth.props, alias: matrixIds.roomAlias(alias) })).roomId;
+ const content = await matrixCommon.buildTextContent({ text: message, msgtype: 'm.text', format: 'markdown' });
+ return matrixIds.withTransactionId({
+ value: undefined,
+ run,
+ step,
+ parts: [roomId, content],
+ send: (txnId) => matrixCommon.sendEvent({ auth: auth.props, roomId, eventType: 'm.room.message', content, txnId }),
+ });
},
});
diff --git a/packages/pieces/community/matrix/src/lib/auth.ts b/packages/pieces/community/matrix/src/lib/auth.ts
new file mode 100644
index 00000000000..e0134d93f4f
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/auth.ts
@@ -0,0 +1,57 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { PieceAuth, Property } from '@activepieces/pieces-framework';
+import { MatrixApiError, matrixClient } from './common/client';
+import { matrixIds } from './common/ids';
+
+export const matrixAuth = PieceAuth.CustomAuth({
+ description: `
+ To obtain access token & Home server:
+
+ 1. Log in to the account you want to get the access token for on Element.
+ 2. Click on the name in the top left corner of the screen, then select "Settings" from the dropdown menu.
+ 3. In the Settings dialog, click the "Help & About" tab on the left side of the screen.
+ 4. Scroll to the bottom of the page and click on the "click to reveal" part of the "Access Token" section.
+ 5. Copy your access token & Home Server URL and paste them into the fields below.
+ `,
+ props: {
+ base_url: Property.ShortText({
+ displayName: 'Home Server',
+ description: 'The client API address of your homeserver, e.g. https://matrix-client.matrix.org (shown under Help & About in Element).',
+ required: true,
+ }),
+ access_token: PieceAuth.SecretText({
+ displayName: 'Access Token',
+ required: true,
+ }),
+ },
+ validate: async ({ auth }) => {
+ try {
+ matrixClient.normalizeHomeserver(auth.base_url);
+ matrixClient.accessTokenOf(auth);
+ } catch (error) {
+ return { valid: false, error: error instanceof Error ? error.message : 'Invalid connection.' };
+ }
+ try {
+ const body = await matrixClient.request({ auth, method: HttpMethod.GET, path: matrixIds.clientPath('account', 'whoami') });
+ if (!matrixClient.isRecord(body) || typeof body['user_id'] !== 'string') {
+ return { valid: false, error: 'The Home Server URL does not point to a Matrix client API.' };
+ }
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof MatrixApiError && (error.status === 401 || error.status === 403)) {
+ return { valid: false, error: 'Invalid access token.' };
+ }
+ if (error instanceof MatrixApiError && (error.status === 404 || error.status === 405)) {
+ return {
+ valid: false,
+ error: 'This address does not serve the Matrix client API. Use the homeserver URL shown in Element under Settings > Help & About (e.g. https://matrix-client.matrix.org).',
+ };
+ }
+ return {
+ valid: false,
+ error: error instanceof Error ? `Could not reach the homeserver: ${error.message}` : 'Could not reach the homeserver.',
+ };
+ }
+ },
+ required: true,
+});
diff --git a/packages/pieces/community/matrix/src/lib/common/client.ts b/packages/pieces/community/matrix/src/lib/common/client.ts
new file mode 100644
index 00000000000..650b1d986fa
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/common/client.ts
@@ -0,0 +1,262 @@
+import { httpClient, HttpMethod, HttpResponse, QueryParams } from '@activepieces/pieces-common';
+
+const REQUEST_TIMEOUT_MS = 30_000;
+const MAX_RATE_LIMIT_RETRIES = 2;
+const MAX_RETRY_WAIT_MS = 30_000;
+const LOCAL_HOSTS = ['localhost', '127.0.0.1', '[::1]'];
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export class MatrixApiError extends Error {
+ constructor(
+ message: string,
+ public readonly status: number,
+ public readonly errcode: string | undefined,
+ public readonly responseBody: unknown,
+ ) {
+ super(message);
+ this.name = 'MatrixApiError';
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function normalizeHomeserver(raw: unknown): string {
+ const text = typeof raw === 'string' ? raw.trim() : '';
+ if (!text) {
+ throw new Error('The Matrix connection has no Home Server URL.');
+ }
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`;
+ let parsed: URL;
+ try {
+ parsed = new URL(withScheme);
+ } catch {
+ throw new Error('The Home Server is not a valid URL. Use an address like https://matrix-client.matrix.org.');
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ throw new Error('The Home Server URL must start with https://.');
+ }
+ if (parsed.protocol === 'http:' && !LOCAL_HOSTS.includes(parsed.hostname)) {
+ throw new Error('The Home Server URL must use https:// (http:// is only allowed for localhost).');
+ }
+ if (parsed.username || parsed.password) {
+ throw new Error('The Home Server URL must not contain a username or password.');
+ }
+ if (parsed.hash.startsWith('#/')) {
+ throw new Error(
+ 'The Home Server looks like a web app link (it contains #/). Use the homeserver address from Element > Settings > Help & About, e.g. https://matrix-client.matrix.org.',
+ );
+ }
+ if (parsed.search || parsed.hash || text.includes('?') || text.includes('#')) {
+ throw new Error('The Home Server URL must not contain a query string or fragment.');
+ }
+ const path = parsed.pathname.replace(/\/+$/, '');
+ if (/(^|[/\\])\.\.?([/\\?#]|$)/.test(text.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '/')) || path.split('/').some((part) => part === '..' || part === '.')) {
+ throw new Error('The Home Server URL must not contain relative path segments.');
+ }
+ return `${parsed.origin}${path}`;
+}
+
+function isSameOrigin({ url, baseUrl }: { url: string; baseUrl: string }): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ if (parsed.username || parsed.password) return false;
+ const base = new URL(baseUrl);
+ if (parsed.origin !== base.origin) return false;
+ const basePath = base.pathname.replace(/\/+$/, '');
+ if (basePath === '') return true;
+ return parsed.pathname === basePath || parsed.pathname.startsWith(`${basePath}/`);
+}
+
+function accessTokenOf(auth: MatrixAuthValue): string {
+ const token = typeof auth.access_token === 'string' ? auth.access_token.trim() : '';
+ if (!token) {
+ throw new Error('The Matrix connection has no Access Token.');
+ }
+ return token;
+}
+
+function hintFor({ status, errcode }: { status: number; errcode: string | undefined }): string {
+ if (errcode === 'M_UNKNOWN_TOKEN' || status === 401) return ' The access token is invalid or was logged out; reconnect Matrix.';
+ if (errcode === 'M_FORBIDDEN') return ' Check the room membership and power levels of this account and the target user.';
+ if (errcode === 'M_NOT_FOUND' || status === 404) return ' Check the room, event or user ID.';
+ if (errcode === 'M_LIMIT_EXCEEDED' || status === 429) return ' The homeserver is rate limiting this account; try again later.';
+ if (errcode === 'M_UNRECOGNIZED') return ' The homeserver does not support this endpoint.';
+ return '';
+}
+
+function toApiError({ status, body }: { status: number; body: unknown }): MatrixApiError {
+ const errcode = isRecord(body) && typeof body['errcode'] === 'string' ? body['errcode'] : undefined;
+ let text = 'request failed';
+ if (status >= 300 && status < 400) text = 'unexpected redirect';
+ else if (isRecord(body) && typeof body['error'] === 'string' && body['error'].trim()) text = body['error'].trim().replace(/\.+$/, '');
+ else if (typeof body === 'string' && body.trim()) text = body.trim().slice(0, 300);
+ const code = errcode ? ` ${errcode}` : '';
+ return new MatrixApiError(`Matrix API error (${status}${code}): ${text}.${hintFor({ status, errcode })}`, status, errcode, body);
+}
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+function failureOf(error: unknown): { status: number; body: unknown; headers: unknown } | null {
+ if (error === null || typeof error !== 'object') return null;
+ const response = Reflect.get(error, 'response');
+ if (!isRecord(response)) return null;
+ const status = response['status'];
+ return typeof status === 'number' ? { status, body: response['body'], headers: response['headers'] } : null;
+}
+
+function retryWaitMs({ body, headers }: { body: unknown; headers: unknown }): number {
+ let wait = 1000;
+ if (isRecord(body) && typeof body['retry_after_ms'] === 'number') {
+ wait = body['retry_after_ms'];
+ } else if (isRecord(headers)) {
+ const header = headers['retry-after'];
+ const seconds = Number(Array.isArray(header) ? header[0] : header);
+ if (Number.isFinite(seconds)) wait = seconds * 1000;
+ }
+ return Math.min(Math.max(wait, 0), MAX_RETRY_WAIT_MS);
+}
+
+function buildQuery(query?: Record<string, string | number | boolean | undefined>): QueryParams {
+ return Object.fromEntries(
+ Object.entries(query ?? {})
+ .filter(([, value]) => value !== undefined)
+ .map(([key, value]) => [key, String(value)]),
+ );
+}
+
+async function sendOnce({ baseUrl, token, method, path, query, body }: SendOnceParams): Promise<{ status: number; body: unknown; headers: unknown }> {
+ const headers: Record<string, string> = { accept: 'application/json', authorization: `Bearer ${token}` };
+ if (body !== undefined) headers['content-type'] = 'application/json';
+ const dispatcher = await verifiedTls();
+ try {
+ const response: HttpResponse = await httpClient.sendRequest(
+ {
+ method,
+ url: `${baseUrl}${path}`,
+ headers,
+ queryParams: buildQuery(query),
+ body,
+ timeout: REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ },
+ { dispatcher },
+ );
+ return { status: response.status, body: response.body, headers: response.headers };
+ } catch (error) {
+ const failure = failureOf(error);
+ if (!failure) throw error;
+ return failure;
+ }
+}
+
+async function request({ auth, method, path, query, body }: MatrixRequest): Promise<unknown> {
+ const baseUrl = normalizeHomeserver(auth.base_url);
+ const token = accessTokenOf(auth);
+ for (let attempt = 0; ; attempt++) {
+ const result = await sendOnce({ baseUrl, token, method, path, query, body });
+ if (result.status >= 200 && result.status < 300) {
+ return result.body;
+ }
+ if (result.status === 429 && attempt < MAX_RATE_LIMIT_RETRIES) {
+ await new Promise((resolve) => setTimeout(resolve, retryWaitMs(result)));
+ continue;
+ }
+ throw toApiError(result);
+ }
+}
+
+function arrayOf(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+
+function stringOr(value: unknown): string | null {
+ return typeof value === 'string' ? value : null;
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (typeof value !== 'string') return undefined;
+ const text = value.trim();
+ return text === '' ? undefined : text;
+}
+
+function requiredText({ value, label }: { value: unknown; label: string }): string {
+ const text = optionalText(value);
+ if (text === undefined) throw new Error(`${label} is required.`);
+ return text;
+}
+
+function messageText({ value, label }: { value: unknown; label: string }): string {
+ if (typeof value !== 'string' || value.trim() === '') throw new Error(`${label} is required.`);
+ return value;
+}
+
+function isServerName(value: string): boolean {
+ return /^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:\d{1,5})?$/.test(value);
+}
+
+function parseLimit({ value, label, min, max, fallback }: { value: unknown; label: string; min: number; max: number; fallback: number }): number {
+ if (value === undefined || value === null || value === '') return fallback;
+ const parsed = typeof value === 'string' ? Number(value.trim()) : value;
+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);
+ }
+ return parsed;
+}
+
+function stringList(value: unknown): string[] {
+ if (Array.isArray(value)) {
+ return value.flatMap((item) => (typeof item === 'string' ? item.split(',') : [])).map((item) => item.trim()).filter((item) => item !== '');
+ }
+ if (typeof value === 'string') {
+ return value.split(',').map((item) => item.trim()).filter((item) => item !== '');
+ }
+ return [];
+}
+
+export const matrixClient = {
+ request,
+ normalizeHomeserver,
+ isSameOrigin,
+ accessTokenOf,
+ isRecord,
+ arrayOf,
+ stringOr,
+ optionalText,
+ requiredText,
+ messageText,
+ isServerName,
+ parseLimit,
+ stringList,
+ retryWaitMs,
+};
+
+type SendOnceParams = {
+ baseUrl: string;
+ token: string;
+ method: HttpMethod;
+ path: string;
+ query?: Record<string, string | number | boolean | undefined>;
+ body?: unknown;
+};
+
+export type MatrixAuthValue = {
+ base_url: string;
+ access_token: string;
+};
+
+export type MatrixRequest = {
+ auth: MatrixAuthValue;
+ method: HttpMethod;
+ path: string;
+ query?: Record<string, string | number | boolean | undefined>;
+ body?: unknown;
+};
diff --git a/packages/pieces/community/matrix/src/lib/common/common.ts b/packages/pieces/community/matrix/src/lib/common/common.ts
index 8d2e3c8bfbd..bbc12a298c6 100644
--- a/packages/pieces/community/matrix/src/lib/common/common.ts
+++ b/packages/pieces/community/matrix/src/lib/common/common.ts
@@ -1,51 +1,141 @@
-import {
- httpClient,
- HttpMethod,
- AuthenticationType,
- HttpResponse,
-} from '@activepieces/pieces-common';
-import { marked } from 'marked';
-
-export async function getRoomId(
- baseUrl: string,
- roomAlias: string,
- accessToken: string
-): Promise<HttpResponse> {
- const response = httpClient.sendRequest({
+import { HttpMethod } from '@activepieces/pieces-common';
+import { matrixClient, MatrixApiError, MatrixAuthValue } from './client';
+import { matrixIds } from './ids';
+import { matrixMarkdown } from './markdown';
+
+const MSG_TYPES = ['m.text', 'm.notice', 'm.emote'];
+
+async function resolveAlias({ auth, alias }: { auth: MatrixAuthValue; alias: string }): Promise<{ roomId: string; servers: string[] }> {
+ const body = await matrixClient.request({
+ auth,
method: HttpMethod.GET,
- url: `${baseUrl}/_matrix/client/r0/directory/room/${encodeURIComponent(
- roomAlias
- )}`,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: accessToken,
- },
+ path: matrixIds.clientPath('directory', 'room', matrixIds.roomAlias(alias)),
});
+ const record = matrixClient.isRecord(body) ? body : {};
+ const roomId = record['room_id'];
+ if (typeof roomId !== 'string') {
+ throw new Error(`The homeserver did not return a room ID for ${alias}.`);
+ }
+ return { roomId, servers: matrixClient.arrayOf(record['servers']).filter((s): s is string => typeof s === 'string') };
+}
+
+async function resolveRoom({ auth, room }: { auth: MatrixAuthValue; room: unknown }): Promise<string> {
+ const value = matrixIds.roomIdOrAlias(room);
+ if (value.startsWith('!')) return value;
+ return (await resolveAlias({ auth, alias: value })).roomId;
+}
- return response;
-}
-
-export async function sendMessage(
- baseUrl: string,
- roomId: string,
- accessToken: string,
- message: string
-): Promise<HttpResponse> {
- const response = httpClient.sendRequest({
- method: HttpMethod.POST,
- url:
- `${baseUrl}/_matrix/client/r0/rooms/` + roomId + '/send/m.room.message',
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: accessToken,
- },
- body: {
- msgtype: 'm.text',
- body: message,
- format: 'org.matrix.custom.html',
- formatted_body: marked(message),
- },
+async function buildTextContent({ text, msgtype, format }: { text: string; msgtype: string; format: string }): Promise<Record<string, unknown>> {
+ if (!MSG_TYPES.includes(msgtype)) {
+ throw new Error(`Message type must be one of ${MSG_TYPES.join(', ')}.`);
+ }
+ const content: Record<string, unknown> = { msgtype, body: text };
+ if (format === 'markdown') {
+ content['format'] = 'org.matrix.custom.html';
+ content['formatted_body'] = await matrixMarkdown.toSafeHtml(text);
+ } else if (format !== 'plain') {
+ throw new Error('Format must be markdown or plain.');
+ }
+ return content;
+}
+
+async function sendEvent({ auth, roomId, eventType, content, txnId }: { auth: MatrixAuthValue; roomId: string; eventType: string; content: Record<string, unknown>; txnId: string }): Promise<{ eventId: string; roomId: string; transactionId: string }> {
+ const body = await matrixClient.request({
+ auth,
+ method: HttpMethod.PUT,
+ path: matrixIds.clientPath('rooms', roomId, 'send', eventType, txnId),
+ body: content,
});
+ const eventId = matrixClient.isRecord(body) ? body['event_id'] : undefined;
+ if (typeof eventId !== 'string') {
+ throw new Error('The homeserver did not return an event ID.');
+ }
+ return { eventId, roomId, transactionId: txnId };
+}
- return response;
+async function roomName({ auth, roomId }: { auth: MatrixAuthValue; roomId: string }): Promise<string | null> {
+ try {
+ const body = await matrixClient.request({
+ auth,
+ method: HttpMethod.GET,
+ path: matrixIds.clientPath('rooms', roomId, 'state', 'm.room.name', ''),
+ });
+ return matrixClient.isRecord(body) ? matrixClient.stringOr(body['name']) : null;
+ } catch (error) {
+ if (error instanceof MatrixApiError && (error.status === 404 || error.status === 403)) return null;
+ throw error;
+ }
}
+
+async function joinedRoomIds({ auth }: { auth: MatrixAuthValue }): Promise<string[]> {
+ const body = await matrixClient.request({ auth, method: HttpMethod.GET, path: matrixIds.clientPath('joined_rooms') });
+ const rooms = matrixClient.isRecord(body) ? matrixClient.arrayOf(body['joined_rooms']) : [];
+ return rooms.filter((room): room is string => typeof room === 'string');
+}
+
+async function mapLimited<T, R>({ items, limit, fn }: { items: T[]; limit: number; fn: (item: T) => Promise<R> }): Promise<R[]> {
+ const results: R[] = new Array(items.length);
+ let next = 0;
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
+ while (next < items.length) {
+ const index = next++;
+ results[index] = await fn(items[index]);
+ }
+ });
+ await Promise.all(workers);
+ return results;
+}
+
+function mapEvent({ raw, roomId }: { raw: unknown; roomId: string | null }): MatrixEventSummary {
+ const event = matrixClient.isRecord(raw) ? raw : {};
+ const content = matrixClient.isRecord(event['content']) ? event['content'] : {};
+ const relates = matrixClient.isRecord(content['m.relates_to']) ? content['m.relates_to'] : {};
+ const inReply = matrixClient.isRecord(relates['m.in_reply_to']) ? relates['m.in_reply_to'] : {};
+ const unsigned = matrixClient.isRecord(event['unsigned']) ? event['unsigned'] : {};
+ const ts = event['origin_server_ts'];
+ return {
+ eventId: matrixClient.stringOr(event['event_id']),
+ roomId: matrixClient.stringOr(event['room_id']) ?? roomId,
+ sender: matrixClient.stringOr(event['sender']),
+ type: matrixClient.stringOr(event['type']),
+ msgtype: matrixClient.stringOr(content['msgtype']),
+ body: matrixClient.stringOr(content['body']),
+ formattedBody: matrixClient.stringOr(content['formatted_body']),
+ timestamp: typeof ts === 'number' ? new Date(ts).toISOString() : null,
+ relType: matrixClient.stringOr(relates['rel_type']),
+ relatesToEventId: matrixClient.stringOr(relates['event_id']),
+ inReplyToEventId: matrixClient.stringOr(inReply['event_id']),
+ stateKey: matrixClient.stringOr(event['state_key']),
+ encrypted: event['type'] === 'm.room.encrypted',
+ redacted: matrixClient.isRecord(unsigned['redacted_because']),
+ };
+}
+
+export const matrixCommon = {
+ resolveAlias,
+ resolveRoom,
+ buildTextContent,
+ sendEvent,
+ roomName,
+ joinedRoomIds,
+ mapLimited,
+ mapEvent,
+ MSG_TYPES,
+};
+
+export type MatrixEventSummary = {
+ eventId: string | null;
+ roomId: string | null;
+ sender: string | null;
+ type: string | null;
+ msgtype: string | null;
+ body: string | null;
+ formattedBody: string | null;
+ timestamp: string | null;
+ relType: string | null;
+ relatesToEventId: string | null;
+ inReplyToEventId: string | null;
+ stateKey: string | null;
+ encrypted: boolean;
+ redacted: boolean;
+};
diff --git a/packages/pieces/community/matrix/src/lib/common/ids.ts b/packages/pieces/community/matrix/src/lib/common/ids.ts
new file mode 100644
index 00000000000..e94ae1132a6
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/common/ids.ts
@@ -0,0 +1,96 @@
+import { createHash, randomUUID } from 'crypto';
+
+const CLIENT_PREFIX = '/_matrix/client/v3';
+const FAILED_SEND_TTL_MS = 30 * 60 * 1000;
+const MAX_FAILED_SENDS = 500;
+const failedSends = new Map<string, { txnId: string; at: number }>();
+
+function clean(value: unknown): string {
+ return typeof value === 'string' ? value.trim() : '';
+}
+
+function check({ value, sigil, label, example, needsServer }: { value: unknown; sigil: string; label: string; example: string; needsServer: boolean }): string {
+ const text = clean(value);
+ const body = text.slice(1);
+ const valid =
+ text.startsWith(sigil) &&
+ body.length > 0 &&
+ text.length <= 255 &&
+ !/[\s\x00-\x1f\x7f]/.test(text) &&
+ (!needsServer || /^[^:]+:[^:].*$/.test(body));
+ if (!valid) {
+ throw new Error(`${label} must look like ${example}.`);
+ }
+ return text;
+}
+
+function roomId(value: unknown): string {
+ return check({ value, sigil: '!', label: 'Room ID', example: '!abc123:example.org', needsServer: false });
+}
+
+function roomAlias(value: unknown): string {
+ return check({ value, sigil: '#', label: 'Room alias', example: '#room:example.org', needsServer: true });
+}
+
+function roomIdOrAlias(value: unknown): string {
+ const text = clean(value);
+ if (text.startsWith('#')) return roomAlias(text);
+ if (text.startsWith('!')) return roomId(text);
+ throw new Error('Room must be a room ID like !abc123:example.org or an alias like #room:example.org.');
+}
+
+function userId(value: unknown): string {
+ return check({ value, sigil: '@', label: 'User ID', example: '@alice:example.org', needsServer: true });
+}
+
+function eventId(value: unknown): string {
+ return check({ value, sigil: '$', label: 'Event ID', example: '$AbC123', needsServer: false });
+}
+
+function transactionId(value: unknown): string | undefined {
+ const text = clean(value);
+ if (text === '') return undefined;
+ if (!/^[A-Za-z0-9._~-]{1,128}$/.test(text)) {
+ throw new Error('Transaction ID may only contain letters, digits and . _ ~ - (max 128 characters).');
+ }
+ return text;
+}
+
+async function withTransactionId<T>({ value, run, step, parts, send }: { value: unknown; run: { id: string }; step: { name: string }; parts: unknown[]; send: (txnId: string) => Promise<T> }): Promise<T> {
+ const explicit = transactionId(value);
+ if (explicit !== undefined) return send(explicit);
+ const now = Date.now();
+ for (const [key, entry] of failedSends) {
+ if (now - entry.at > FAILED_SEND_TTL_MS) failedSends.delete(key);
+ }
+ const key = createHash('sha256').update(JSON.stringify([run.id, step.name, ...parts])).digest('hex');
+ const txnId = failedSends.get(key)?.txnId ?? `ap-${randomUUID()}`;
+ try {
+ const result = await send(txnId);
+ failedSends.delete(key);
+ return result;
+ } catch (error) {
+ failedSends.delete(key);
+ failedSends.set(key, { txnId, at: now });
+ if (failedSends.size > MAX_FAILED_SENDS) {
+ const oldest = failedSends.keys().next().value;
+ if (oldest !== undefined) failedSends.delete(oldest);
+ }
+ throw error;
+ }
+}
+
+function clientPath(...segments: string[]): string {
+ return `${CLIENT_PREFIX}/${segments.map((segment) => encodeURIComponent(segment)).join('/')}`;
+}
+
+export const matrixIds = {
+ roomId,
+ roomAlias,
+ roomIdOrAlias,
+ userId,
+ eventId,
+ transactionId,
+ withTransactionId,
+ clientPath,
+};
diff --git a/packages/pieces/community/matrix/src/lib/common/markdown.ts b/packages/pieces/community/matrix/src/lib/common/markdown.ts
new file mode 100644
index 00000000000..c5eed061d76
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/common/markdown.ts
@@ -0,0 +1,29 @@
+const SAFE_LINK = /^(https?:|mailto:|matrix:)/i;
+
+function escapeHtml(text: string): string {
+ return text
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
+async function toSafeHtml(markdown: string): Promise<string> {
+ const { marked } = await import('marked');
+ const renderer = new marked.Renderer();
+ renderer.html = (html: string) => escapeHtml(html);
+ renderer.link = (href: string | null, title: string | null, text: string) => {
+ if (!href || !SAFE_LINK.test(href.trim())) return text;
+ const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
+ return `<a href="${escapeHtml(href.trim())}"${titleAttr}>${text}</a>`;
+ };
+ renderer.image = (href: string | null, _title: string | null, text: string) => {
+ const label = escapeHtml(text || 'image');
+ if (!href || !/^https?:/i.test(href.trim())) return label;
+ return `<a href="${escapeHtml(href.trim())}">${label}</a>`;
+ };
+ return marked.parse(markdown, { renderer, mangle: false, headerIds: false }).trim();
+}
+
+export const matrixMarkdown = { toSafeHtml, escapeHtml };
diff --git a/packages/pieces/community/matrix/src/lib/common/output-schemas.ts b/packages/pieces/community/matrix/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..88620799c26
--- /dev/null
+++ b/packages/pieces/community/matrix/src/lib/common/output-schemas.ts
@@ -0,0 +1,169 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const eventFields: OutputSchema['fields'] = [
+ { key: 'eventId', label: 'Event ID' },
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'sender', label: 'Sender' },
+ { key: 'type', label: 'Event Type' },
+ { key: 'msgtype', label: 'Message Type', description: 'm.text, m.notice, m.emote, m.image, ... Null for non-message events.' },
+ { key: 'body', label: 'Body', description: 'Plain-text body. Null for encrypted or redacted events.' },
+ { key: 'formattedBody', label: 'Formatted Body', format: 'html' },
+ { key: 'timestamp', label: 'Sent At', format: 'datetime' },
+ { key: 'relType', label: 'Relation Type', description: 'm.replace for edits, m.annotation for reactions, m.thread for threads.' },
+ { key: 'relatesToEventId', label: 'Relates To Event ID' },
+ { key: 'inReplyToEventId', label: 'In Reply To Event ID' },
+ { key: 'stateKey', label: 'State Key' },
+ { key: 'encrypted', label: 'Encrypted', format: 'boolean', description: 'True for end-to-end encrypted events, which this piece cannot decrypt.' },
+ { key: 'redacted', label: 'Redacted', format: 'boolean' },
+];
+
+const sentFields: OutputSchema['fields'] = [
+ { key: 'eventId', label: 'Event ID' },
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'transactionId', label: 'Transaction ID', description: 'Send again with this ID to retry without posting a duplicate.' },
+];
+
+const membershipFields: OutputSchema['fields'] = [
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'userId', label: 'User ID' },
+ { key: 'membership', label: 'Membership', description: 'The membership the user now has: invite, leave or ban.' },
+];
+
+const publicRoomFields: OutputSchema['fields'] = [
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'topic', label: 'Topic' },
+ { key: 'canonicalAlias', label: 'Alias' },
+ { key: 'numJoinedMembers', label: 'Members', format: 'number' },
+ { key: 'worldReadable', label: 'World Readable', format: 'boolean' },
+ { key: 'guestCanJoin', label: 'Guests Can Join', format: 'boolean' },
+ { key: 'joinRule', label: 'Join Rule' },
+ { key: 'roomType', label: 'Room Type', description: 'm.space for spaces, null for normal rooms.' },
+ { key: 'avatarUrl', label: 'Avatar (mxc URI)' },
+];
+
+const userFields: OutputSchema['fields'] = [
+ { key: 'userId', label: 'User ID' },
+ { key: 'displayName', label: 'Display Name' },
+ { key: 'avatarUrl', label: 'Avatar (mxc URI)' },
+];
+
+export const matrixOutputSchemas = {
+ sent: { fields: sentFields } satisfies OutputSchema,
+ edited: {
+ fields: [...sentFields, { key: 'editedEventId', label: 'Edited Event ID' }],
+ } satisfies OutputSchema,
+ reaction: {
+ fields: [
+ { key: 'eventId', label: 'Reaction Event ID', description: 'Null when this account had already reacted with the same key.' },
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'reactedToEventId', label: 'Reacted To Event ID' },
+ { key: 'key', label: 'Reaction' },
+ { key: 'alreadyReacted', label: 'Already Reacted', format: 'boolean' },
+ { key: 'transactionId', label: 'Transaction ID' },
+ ],
+ } satisfies OutputSchema,
+ redaction: {
+ fields: [
+ { key: 'redactionEventId', label: 'Redaction Event ID' },
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'redactedEventId', label: 'Redacted Event ID' },
+ { key: 'transactionId', label: 'Transaction ID' },
+ ],
+ } satisfies OutputSchema,
+ event: { fields: eventFields } satisfies OutputSchema,
+ listMessages: {
+ fields: [
+ { key: 'items', label: 'Events', labelKey: 'body', listItems: eventFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextToken', label: 'Next Token', description: 'Pass as From to get the next page. Null when there is no more.' },
+ ],
+ } satisfies OutputSchema,
+ currentUser: {
+ fields: [
+ { key: 'userId', label: 'User ID' },
+ { key: 'deviceId', label: 'Device ID' },
+ { key: 'isGuest', label: 'Guest', format: 'boolean' },
+ { key: 'homeserver', label: 'Homeserver', format: 'url' },
+ ],
+ } satisfies OutputSchema,
+ joinedRooms: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Rooms',
+ labelKey: 'name',
+ listItems: [
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'name', label: 'Name' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'total', label: 'Total Joined Rooms', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextOffset', label: 'Next Offset', format: 'number' },
+ ],
+ } satisfies OutputSchema,
+ room: {
+ fields: [
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'topic', label: 'Topic' },
+ { key: 'canonicalAlias', label: 'Alias' },
+ { key: 'altAliases', label: 'Other Aliases' },
+ { key: 'encrypted', label: 'Encrypted', format: 'boolean' },
+ { key: 'joinRule', label: 'Join Rule' },
+ { key: 'historyVisibility', label: 'History Visibility' },
+ { key: 'roomVersion', label: 'Room Version' },
+ { key: 'creator', label: 'Creator' },
+ { key: 'roomType', label: 'Room Type' },
+ { key: 'joinedMemberCount', label: 'Joined Members', format: 'number' },
+ { key: 'invitedMemberCount', label: 'Invited Members', format: 'number' },
+ ],
+ } satisfies OutputSchema,
+ publicRooms: {
+ fields: [
+ { key: 'items', label: 'Rooms', labelKey: 'name', listItems: publicRoomFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'totalEstimate', label: 'Total (estimate)', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextToken', label: 'Next Token' },
+ ],
+ } satisfies OutputSchema,
+ createdRoom: {
+ fields: [
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'alias', label: 'Alias', description: 'The full alias (#name:server) when Alias was given, otherwise null.' },
+ ],
+ } satisfies OutputSchema,
+ joinedRoom: { fields: [{ key: 'roomId', label: 'Room ID' }] } satisfies OutputSchema,
+ leftRoom: {
+ fields: [
+ { key: 'roomId', label: 'Room ID' },
+ { key: 'left', label: 'Left', format: 'boolean' },
+ { key: 'forgotten', label: 'Forgotten', format: 'boolean' },
+ ],
+ } satisfies OutputSchema,
+ membership: { fields: membershipFields } satisfies OutputSchema,
+ stateSet: {
+ fields: [
+ { key: 'eventId', label: 'State Event ID' },
+ { key: 'roomId', label: 'Room ID' },
+ ],
+ } satisfies OutputSchema,
+ members: {
+ fields: [
+ { key: 'items', label: 'Members', labelKey: 'displayName', listItems: userFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ } satisfies OutputSchema,
+ profile: { fields: userFields } satisfies OutputSchema,
+ searchUsers: {
+ fields: [
+ { key: 'items', label: 'Users', labelKey: 'displayName', listItems: userFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'limited', label: 'Limited', format: 'boolean', description: 'True when the server cut the results off at the limit.' },
+ ],
+ } satisfies OutputSchema,
+};
diff --git a/packages/pieces/community/matrix/test/matrix.test.ts b/packages/pieces/community/matrix/test/matrix.test.ts
new file mode 100644
index 00000000000..d9bd17d100f
--- /dev/null
+++ b/packages/pieces/community/matrix/test/matrix.test.ts
@@ -0,0 +1,311 @@
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { matrix } from '../src';
+import { MatrixApiError, matrixClient } from '../src/lib/common/client';
+import { matrixIds } from '../src/lib/common/ids';
+import { matrixMarkdown } from '../src/lib/common/markdown';
+
+const auth = { props: { base_url: 'https://matrix.example.org/', access_token: 'secret-token' } };
+
+function action(name: string) {
+ const found = matrix.actions()[name];
+ if (!found) throw new Error(`missing ${name}`);
+ return found;
+}
+
+function runAction({ name, propsValue = {}, connection = auth, runId = 'run1', stepName = 'step_1' }: { name: string; propsValue?: Record<string, unknown>; connection?: unknown; runId?: string; stepName?: string }) {
+ return Reflect.apply(action(name).run, undefined, [{ auth: connection, propsValue, run: { id: runId }, step: { name: stepName } }]);
+}
+
+function mockOk(body: unknown) {
+ return vi.spyOn(httpClient, 'sendRequest').mockResolvedValue({ status: 200, headers: {}, body });
+}
+
+function httpFailure({ status, body }: { status: number; body: unknown }) {
+ return Object.assign(new Error('http'), { response: { status, body, headers: {} } });
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe('normalizeHomeserver', () => {
+ it('adds https and strips trailing slashes', () => {
+ expect(matrixClient.normalizeHomeserver('matrix.org')).toBe('https://matrix.org');
+ expect(matrixClient.normalizeHomeserver(' https://h.example.org/// ')).toBe('https://h.example.org');
+ expect(matrixClient.normalizeHomeserver('http://localhost:8008')).toBe('http://localhost:8008');
+ });
+ it.each([
+ 'http://matrix.org',
+ 'ftp://matrix.org',
+ 'https://u:[email protected]',
+ 'https://matrix.org/?x=1',
+ 'https://matrix.org/#x',
+ 'https://matrix.org/a/../b',
+ '',
+ ])('rejects %s', (value) => {
+ expect(() => matrixClient.normalizeHomeserver(value)).toThrow();
+ });
+ it('explains an Element web link', () => {
+ expect(() => matrixClient.normalizeHomeserver('https://app.element.io/#/home')).toThrow(/web app link/);
+ });
+});
+
+describe('ids', () => {
+ it('validates sigils', () => {
+ expect(matrixIds.roomId('!abc:x.org')).toBe('!abc:x.org');
+ expect(matrixIds.roomId('!opaqueV12id')).toBe('!opaqueV12id');
+ expect(() => matrixIds.roomId('#a:x.org')).toThrow();
+ expect(() => matrixIds.roomId('!a b:x.org')).toThrow();
+ expect(matrixIds.roomAlias('#team/ops:x.org')).toBe('#team/ops:x.org');
+ expect(matrixIds.userId('@team/bot:x.org')).toBe('@team/bot:x.org');
+ expect(matrixIds.clientPath('directory', 'room', '#team/ops:x.org')).toBe('/_matrix/client/v3/directory/room/%23team%2Fops%3Ax.org');
+ expect(() => matrixIds.userId('@alice')).toThrow();
+ expect(() => matrixIds.roomAlias('#room')).toThrow();
+ expect(() => matrixIds.eventId('abc')).toThrow();
+ expect(() => matrixIds.roomIdOrAlias('room')).toThrow();
+ });
+ it('encodes every path segment', () => {
+ expect(matrixIds.clientPath('rooms', '!a:b.org', 'event', '$e+/=')).toBe('/_matrix/client/v3/rooms/!a%3Ab.org/event/%24e%2B%2F%3D');
+ });
+ it('generates or validates transaction ids', () => {
+ expect(matrixIds.transactionId(undefined)).toBeUndefined();
+ expect(matrixIds.transactionId('retry-1')).toBe('retry-1');
+ expect(() => matrixIds.transactionId('a/b')).toThrow();
+ });
+});
+
+describe('markdown', () => {
+ it('escapes raw html and drops unsafe links', async () => {
+ const html = await matrixMarkdown.toSafeHtml('**hi** <img src=x onerror=alert(1)> [x](javascript:alert(1)) [ok](https://a.org)');
+ expect(html).toContain('<strong>hi</strong>');
+ expect(html).not.toContain('<img');
+ expect(html).toContain('&lt;img');
+ expect(html).not.toContain('javascript:');
+ expect(html).toContain('<a href="https://a.org">ok</a>');
+ });
+});
+
+describe('request errors', () => {
+ it('maps errcode into a MatrixApiError with responseBody', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue(httpFailure({ status: 403, body: { errcode: 'M_FORBIDDEN', error: 'nope' } }));
+ const error = await runAction({ name: 'get_current_user' }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(MatrixApiError);
+ expect(error).toMatchObject({ status: 403, errcode: 'M_FORBIDDEN', responseBody: { errcode: 'M_FORBIDDEN', error: 'nope' } });
+ });
+ it('does not double the vendor full stop', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue(httpFailure({ status: 403, body: { errcode: 'M_FORBIDDEN', error: 'x is already in the room.' } }));
+ await expect(runAction({ name: 'get_current_user' })).rejects.toThrow('Matrix API error (403 M_FORBIDDEN): x is already in the room. Check');
+ });
+ it('retries M_LIMIT_EXCEEDED with a clamped wait', async () => {
+ vi.useFakeTimers();
+ const spy = vi
+ .spyOn(httpClient, 'sendRequest')
+ .mockRejectedValueOnce(httpFailure({ status: 429, body: { errcode: 'M_LIMIT_EXCEEDED', retry_after_ms: 999999 } }))
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { user_id: '@me:x.org' } });
+ const pending = runAction({ name: 'get_current_user' });
+ await vi.advanceTimersByTimeAsync(30_000);
+ await expect(pending).resolves.toMatchObject({ userId: '@me:x.org' });
+ expect(spy).toHaveBeenCalledTimes(2);
+ expect(matrixClient.retryWaitMs({ body: { retry_after_ms: 999999 }, headers: {} })).toBe(30_000);
+ });
+});
+
+describe('send_text_message', () => {
+ it('PUTs with txnId, bearer token and sanitized html', async () => {
+ const spy = mockOk({ event_id: '$ev' });
+ const out = await runAction({
+ name: 'send_text_message',
+ propsValue: { room: '!r:x.org', text: 'hi <b>x</b>', transactionId: 't1', replyToEventId: '$p' },
+ });
+ expect(out).toEqual({ eventId: '$ev', roomId: '!r:x.org', transactionId: 't1' });
+ const request = spy.mock.calls[0][0];
+ expect(request.method).toBe(HttpMethod.PUT);
+ expect(request.url).toBe('https://matrix.example.org/_matrix/client/v3/rooms/!r%3Ax.org/send/m.room.message/t1');
+ expect(request.headers).toMatchObject({ authorization: 'Bearer secret-token' });
+ expect(request.followRedirects).toBe(false);
+ expect(request.body).toMatchObject({
+ msgtype: 'm.text',
+ body: 'hi <b>x</b>',
+ format: 'org.matrix.custom.html',
+ 'm.relates_to': { 'm.in_reply_to': { event_id: '$p' } },
+ });
+ expect(request.body.formatted_body).toBe('<p>hi &lt;b&gt;x&lt;/b&gt;</p>');
+ });
+ it('resolves an alias first and sends plain text', async () => {
+ const spy = vi
+ .spyOn(httpClient, 'sendRequest')
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { room_id: '!r:x.org', servers: [] } })
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { event_id: '$ev' } });
+ await runAction({ name: 'send_text_message', propsValue: { room: '#room:x.org', text: 'hello', format: 'plain', msgtype: 'm.notice' } });
+ expect(spy.mock.calls[0][0].url).toBe('https://matrix.example.org/_matrix/client/v3/directory/room/%23room%3Ax.org');
+ expect(spy.mock.calls[1][0].body).toEqual({ msgtype: 'm.notice', body: 'hello' });
+ });
+ it('rejects a bad room before any request', async () => {
+ const spy = mockOk({});
+ await expect(runAction({ name: 'send_text_message', propsValue: { room: 'general', text: 'x' } })).rejects.toThrow();
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
+describe('send_message (human)', () => {
+ it('needs a room or an alias', async () => {
+ await expect(runAction({ name: 'send_message', propsValue: { message: 'x' } })).rejects.toThrow('Pick a Room');
+ });
+ it('returns only event and room ids, not the http response', async () => {
+ mockOk({ event_id: '$ev' });
+ const out = await runAction({ name: 'send_message', propsValue: { room: '!r:x.org', message: 'x' } });
+ expect(Object.keys(out).sort()).toEqual(['eventId', 'roomId', 'transactionId']);
+ });
+ it('reuses the txnId only to retry a failed send', async () => {
+ const spy = vi
+ .spyOn(httpClient, 'sendRequest')
+ .mockRejectedValueOnce(httpFailure({ status: 502, body: {} }))
+ .mockResolvedValue({ status: 200, headers: {}, body: { event_id: '$ev' } });
+ const props = { room: '!r:x.org', message: 'retry-me' };
+ await expect(runAction({ name: 'send_message', propsValue: props, runId: 'retry-run' })).rejects.toThrow();
+ const retried = await runAction({ name: 'send_message', propsValue: props, runId: 'retry-run' });
+ const failedUrl = spy.mock.calls.at(-2)?.[0].url;
+ expect(spy.mock.calls.at(-1)?.[0].url).toBe(failedUrl);
+ const next = await runAction({ name: 'send_message', propsValue: props, runId: 'retry-run' });
+ expect(next.transactionId).not.toBe(retried.transactionId);
+ });
+});
+
+describe('send_text_message repeats', () => {
+ it('posts identical successful calls separately (loops, MCP)', async () => {
+ mockOk({ event_id: '$ev' });
+ const a = await runAction({ name: 'send_text_message', propsValue: { room: '!r:x.org', text: 'hi' }, runId: 'mcp-flow-run-id' });
+ const b = await runAction({ name: 'send_text_message', propsValue: { room: '!r:x.org', text: 'hi' }, runId: 'mcp-flow-run-id' });
+ expect(a.transactionId).toMatch(/^ap-[0-9a-f-]{36}$/);
+ expect(b.transactionId).not.toBe(a.transactionId);
+ });
+ it('uses an explicit transactionId as given', async () => {
+ mockOk({ event_id: '$ev' });
+ const a = await runAction({ name: 'send_text_message', propsValue: { room: '!r:x.org', text: 'hi', transactionId: 'fixed-1' } });
+ expect(a.transactionId).toBe('fixed-1');
+ });
+});
+
+describe('react_to_message', () => {
+ it('treats a duplicate annotation as already reacted', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue(httpFailure({ status: 400, body: { errcode: 'M_DUPLICATE_ANNOTATION', error: 'dup' } }));
+ await expect(runAction({ name: 'react_to_message', propsValue: { roomId: '!r:x.org', eventId: '$e', key: '👍' } })).resolves.toMatchObject({
+ alreadyReacted: true,
+ eventId: null,
+ });
+ });
+});
+
+describe('list_messages', () => {
+ it('sends dir, limit, from and the message filter', async () => {
+ const spy = mockOk({ chunk: [{ event_id: '$1', type: 'm.room.message', sender: '@a:x.org', origin_server_ts: 0, content: { msgtype: 'm.text', body: 'b' } }], end: 'tok2' });
+ const out = await runAction({ name: 'list_messages', propsValue: { room: '!r:x.org', limit: 5, from: 'tok1' } });
+ expect(spy.mock.calls[0][0].queryParams).toEqual({ dir: 'b', limit: '5', from: 'tok1', filter: '{"types":["m.room.message","m.room.encrypted"]}' });
+ expect(out).toMatchObject({ count: 1, hasMore: true, nextToken: 'tok2', items: [{ eventId: '$1', body: 'b', timestamp: '1970-01-01T00:00:00.000Z' }] });
+ });
+});
+
+describe('greptile fixes', () => {
+ function routed(original: unknown) {
+ return vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ if (request.url.endsWith('/account/whoami')) return { status: 200, headers: {}, body: { user_id: '@me:x.org' } };
+ if (request.method === HttpMethod.GET) return { status: 200, headers: {}, body: original };
+ return { status: 200, headers: {}, body: { event_id: '$edit' } };
+ });
+ }
+ const mine = { event_id: '$e', type: 'm.room.message', sender: '@me:x.org', content: { msgtype: 'm.text', body: 'old' } };
+ it('edit_message sends an m.replace for own messages', async () => {
+ const spy = routed(mine);
+ const out = await runAction({ name: 'edit_message', propsValue: { roomId: '!r:x.org', eventId: '$e', text: 'new', format: 'plain' } });
+ expect(out).toMatchObject({ eventId: '$edit', editedEventId: '$e' });
+ expect(spy.mock.calls.at(-1)?.[0].body).toMatchObject({ 'm.relates_to': { rel_type: 'm.replace', event_id: '$e' } });
+ });
+ it('edit_message keeps the original notice or emote message type', async () => {
+ for (const msgtype of ['m.notice', 'm.emote']) {
+ vi.restoreAllMocks();
+ const spy = routed({ ...mine, content: { msgtype, body: 'old' } });
+ await runAction({ name: 'edit_message', propsValue: { roomId: '!r:x.org', eventId: '$e', text: 'new', format: 'plain' } });
+ const body = spy.mock.calls.at(-1)?.[0].body;
+ expect(body).toMatchObject({ msgtype, 'm.new_content': { msgtype, body: 'new' } });
+ }
+ });
+ it('edit_message refuses non-text messages such as images', async () => {
+ const spy = routed({ ...mine, content: { msgtype: 'm.image', body: 'pic.png' } });
+ await expect(runAction({ name: 'edit_message', propsValue: { roomId: '!r:x.org', eventId: '$e', text: 'new' } })).rejects.toThrow('only text, notice and emote');
+ expect(spy.mock.calls.every((call) => call[0].method === HttpMethod.GET)).toBe(true);
+ });
+ it('edit_message refuses another sender, redacted or edit events', async () => {
+ for (const { original, msg } of [
+ { original: { ...mine, sender: '@other:x.org' }, msg: 'Only the original sender' },
+ { original: { ...mine, unsigned: { redacted_because: {} } }, msg: 'was deleted' },
+ { original: { ...mine, content: { body: '* x', 'm.relates_to': { rel_type: 'm.replace', event_id: '$o' } } }, msg: 'itself an edit' },
+ ]) {
+ vi.restoreAllMocks();
+ const spy = routed(original);
+ await expect(runAction({ name: 'edit_message', propsValue: { roomId: '!r:x.org', eventId: '$e', text: 'new' } })).rejects.toThrow(msg);
+ expect(spy.mock.calls.every((call) => call[0].method === HttpMethod.GET)).toBe(true);
+ }
+ });
+ it('keeps leading whitespace in message bodies but rejects blank text', async () => {
+ const spy = mockOk({ event_id: '$ev' });
+ await runAction({ name: 'send_text_message', propsValue: { room: '!r:x.org', text: ' code()', format: 'plain' } });
+ expect(spy.mock.calls[0][0].body).toEqual({ msgtype: 'm.text', body: ' code()' });
+ await expect(runAction({ name: 'send_text_message', propsValue: { room: '!r:x.org', text: ' ' } })).rejects.toThrow('Text is required');
+ });
+ it('fills roomId from the request when events omit it', async () => {
+ mockOk({ event_id: '$e', type: 'm.room.message', sender: '@a:x.org', content: { body: 'b' } });
+ await expect(runAction({ name: 'get_message', propsValue: { roomId: '!r:x.org', eventId: '$e' } })).resolves.toMatchObject({ roomId: '!r:x.org' });
+ vi.restoreAllMocks();
+ mockOk({ chunk: [{ event_id: '$1', type: 'm.room.message', content: { body: 'b' } }] });
+ const out = await runAction({ name: 'list_messages', propsValue: { room: '!r:x.org' } });
+ expect(out.items[0].roomId).toBe('!r:x.org');
+ });
+ it('join_room accepts bracketed IPv6 via servers', async () => {
+ const spy = mockOk({ room_id: '!r:x.org' });
+ await runAction({ name: 'join_room', propsValue: { room: '!r:x.org', via: ['[2001:db8::1]:8448', 'matrix.org'] } });
+ expect(spy.mock.calls[0][0].url).toContain('via=%5B2001%3Adb8%3A%3A1%5D%3A8448&via=matrix.org');
+ await expect(runAction({ name: 'join_room', propsValue: { room: '!r:x.org', via: ['bad/server'] } })).rejects.toThrow('Via servers');
+ });
+});
+
+describe('create_room', () => {
+ it('still returns roomId when the alias lookup fails', async () => {
+ vi.spyOn(httpClient, 'sendRequest')
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { room_id: '!new:x.org' } })
+ .mockRejectedValueOnce(httpFailure({ status: 404, body: { errcode: 'M_NOT_FOUND', error: 'none' } }));
+ await expect(runAction({ name: 'create_room', propsValue: { aliasName: 'team-ops' } })).resolves.toEqual({ roomId: '!new:x.org', alias: null });
+ });
+});
+
+describe('auth.validate', () => {
+ const validate = matrix.auth?.validate;
+ it('accepts a working token', async () => {
+ mockOk({ user_id: '@me:x.org' });
+ expect(await validate?.({ auth: auth.props, server: { apiUrl: '', publicUrl: '' } })).toEqual({ valid: true });
+ });
+ it('reports an invalid token on 401', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue(httpFailure({ status: 401, body: { errcode: 'M_UNKNOWN_TOKEN', error: 'x' } }));
+ expect(await validate?.({ auth: auth.props, server: { apiUrl: '', publicUrl: '' } })).toEqual({ valid: false, error: 'Invalid access token.' });
+ });
+ it('rejects a non-homeserver URL before any request', async () => {
+ const spy = mockOk({});
+ const result = await validate?.({ auth: { ...auth.props, base_url: 'https://app.element.io/#/home' }, server: { apiUrl: '', publicUrl: '' } });
+ expect(result).toMatchObject({ valid: false });
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
+describe('metadata', () => {
+ it('has exactly one agent-visible send action and schemas everywhere', () => {
+ const actions = Object.values(matrix.actions());
+ const ai = actions.filter((a) => a.audience === 'ai' || a.audience === 'both').map((a) => a.name);
+ expect(ai.filter((name) => name.startsWith('send'))).toEqual(['send_text_message']);
+ expect(action('send_message').audience).toBe('human');
+ for (const a of actions) {
+ if (a.name === 'custom_api_call') continue;
+ expect(a.outputSchema, a.name).toBeDefined();
+ }
+ });
+});
diff --git a/packages/pieces/community/matrix/vitest.config.ts b/packages/pieces/community/matrix/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/matrix/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})