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(jsm-operations): add Jira Service Management Operations piece (Opsgenie successor) (#15900)

Odai Ahmad5a04282688d8
diff --git a/bun.lock b/bun.lock
index 769cf0e35b8..44135415ffd 100644
--- a/bun.lock
+++ b/bun.lock
@@ -4744,6 +4744,18 @@
"tslib": "2.6.2",
},
},
+ "packages/pieces/community/jsm-operations": {
+ "name": "@activepieces/piece-jsm-operations",
+ "version": "0.0.1",
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*",
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6",
+ },
+ },
"packages/pieces/community/json": {
"name": "@activepieces/piece-json",
"version": "0.1.12",
@@ -11889,6 +11901,8 @@
"@activepieces/piece-jotform": ["@activepieces/piece-jotform@workspace:packages/pieces/community/jotform"],
+ "@activepieces/piece-jsm-operations": ["@activepieces/piece-jsm-operations@workspace:packages/pieces/community/jsm-operations"],
+
"@activepieces/piece-json": ["@activepieces/piece-json@workspace:packages/pieces/community/json"],
"@activepieces/piece-jungle-grid": ["@activepieces/piece-jungle-grid@workspace:packages/pieces/community/jungle-grid"],
diff --git a/packages/pieces/community/jsm-operations/.eslintrc.json b/packages/pieces/community/jsm-operations/.eslintrc.json
new file mode 100644
index 00000000000..9ee1a0770e8
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/.eslintrc.json
@@ -0,0 +1,26 @@
+{
+ "extends": ["../../../../.eslintrc.json"],
+ "ignorePatterns": ["!**/*"],
+ "overrides": [
+ { "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], "rules": {} },
+ {
+ "files": ["*.ts", "*.tsx"],
+ "rules": {
+ "no-restricted-imports": [
+ "error",
+ {
+ "patterns": [
+ "lodash",
+ "lodash/*",
+ "@activepieces/core-*",
+ "@activepieces/server*",
+ "@activepieces/engine",
+ "@activepieces/shared"
+ ]
+ }
+ ]
+ }
+ },
+ { "files": ["*.js", "*.jsx"], "rules": {} }
+ ]
+}
diff --git a/packages/pieces/community/jsm-operations/package.json b/packages/pieces/community/jsm-operations/package.json
new file mode 100644
index 00000000000..96659d18f56
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@activepieces/piece-jsm-operations",
+ "version": "0.0.1",
+ "main": "./dist/src/index.js",
+ "types": "./dist/src/index.d.ts",
+ "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'",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@activepieces/pieces-common": "workspace:*",
+ "@activepieces/pieces-framework": "workspace:*"
+ },
+ "devDependencies": {
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
+ }
+}
diff --git a/packages/pieces/community/jsm-operations/src/i18n/translation.json b/packages/pieces/community/jsm-operations/src/i18n/translation.json
new file mode 100644
index 00000000000..385f73648b2
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/i18n/translation.json
@@ -0,0 +1,145 @@
+{
+ "Opsgenie alerts in Jira Service Management: create, acknowledge, close and route on-call alerts, and see who is on call.": "Opsgenie alerts in Jira Service Management: create, acknowledge, close and route on-call alerts, and see who is on call.",
+ "Create Alert": "Create Alert",
+ "Get Alert": "Get Alert",
+ "Find Alerts": "Find Alerts",
+ "Acknowledge Alert": "Acknowledge Alert",
+ "Unacknowledge Alert": "Unacknowledge Alert",
+ "Close Alert": "Close Alert",
+ "Add Note to Alert": "Add Note to Alert",
+ "Add Tags to Alert": "Add Tags to Alert",
+ "Remove Tags from Alert": "Remove Tags from Alert",
+ "Assign Alert": "Assign Alert",
+ "Add Responder to Alert": "Add Responder to Alert",
+ "Escalate Alert": "Escalate Alert",
+ "Snooze Alert": "Snooze Alert",
+ "Update Alert": "Update Alert",
+ "Get Who Is On Call": "Get Who Is On Call",
+ "Custom API Call": "Custom API Call",
+ "Create a new alert and route it to teams, users or schedules.": "Create a new alert and route it to teams, users or schedules.",
+ "Get one alert by its ID or alias.": "Get one alert by its ID or alias.",
+ "Search alerts with a JSM Operations search query.": "Search alerts with a JSM Operations search query.",
+ "Acknowledge an alert so responders know someone is on it.": "Acknowledge an alert so responders know someone is on it.",
+ "Put an acknowledged alert back to open.": "Put an acknowledged alert back to open.",
+ "Close an alert once the problem is resolved.": "Close an alert once the problem is resolved.",
+ "Add a note to an alert.": "Add a note to an alert.",
+ "Add one or more tags to an alert.": "Add one or more tags to an alert.",
+ "Remove one or more tags from an alert.": "Remove one or more tags from an alert.",
+ "Make a user the owner of an alert. Not available on the JSM Free plan.": "Make a user the owner of an alert. Not available on the JSM Free plan.",
+ "Add a team, user, schedule or escalation as a responder.": "Add a team, user, schedule or escalation as a responder.",
+ "Escalate an alert to the next level of an escalation policy.": "Escalate an alert to the next level of an escalation policy.",
+ "Pause notifications for an alert until a set time. Not on JSM Free.": "Pause notifications for an alert until a set time. Not on JSM Free.",
+ "Change the message, description or priority of an alert.": "Change the message, description or priority of an alert.",
+ "Get who is on call for a schedule, now or at a given time.": "Get who is on call for a schedule, now or at a given time.",
+ "Call any JSM Operations endpoint with this connection.": "Call any JSM Operations endpoint with this connection.",
+ "Message": "Message",
+ "Description": "Description",
+ "Priority": "Priority",
+ "Alias": "Alias",
+ "Responder Teams": "Responder Teams",
+ "Responder Users": "Responder Users",
+ "Responder Schedules": "Responder Schedules",
+ "Responder Escalations": "Responder Escalations",
+ "Responders by Name (API Key Connections)": "Responders by Name (API Key Connections)",
+ "Tags": "Tags",
+ "Entity": "Entity",
+ "Source": "Source",
+ "Note": "Note",
+ "Extra Properties": "Extra Properties",
+ "Custom Actions": "Custom Actions",
+ "Created By": "Created By",
+ "Alert ID or Alias": "Alert ID or Alias",
+ "Identify Alert By": "Identify Alert By",
+ "Search Query": "Search Query",
+ "Sort By": "Sort By",
+ "Order": "Order",
+ "Max Results": "Max Results",
+ "Skip": "Skip",
+ "Done By": "Done By",
+ "Added By": "Added By",
+ "Assignee": "Assignee",
+ "Responder Type": "Responder Type",
+ "Responder": "Responder",
+ "Escalation": "Escalation",
+ "Snooze Until": "Snooze Until",
+ "New Message": "New Message",
+ "New Description": "New Description",
+ "Schedule": "Schedule",
+ "At Time": "At Time",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
+ "Short summary of the problem. Up to 130 characters.": "Short summary of the problem. Up to 130 characters.",
+ "Full details of the alert. Up to 15,000 characters.": "Full details of the alert. Up to 15,000 characters.",
+ "P1 is the most urgent, P5 the least.": "P1 is the most urgent, P5 the least.",
+ "Your own unique key for the alert. Open duplicates are merged.": "Your own unique key for the alert. Open duplicates are merged.",
+ "Teams to notify. Needs an Atlassian Account connection.": "Teams to notify. Needs an Atlassian Account connection.",
+ "Users to notify. Needs an Atlassian Account connection.": "Users to notify. Needs an Atlassian Account connection.",
+ "Schedules whose on-call users are notified.": "Schedules whose on-call users are notified.",
+ "Escalation policies to start for this alert.": "Escalation policies to start for this alert.",
+ "For API key connections: responders by team name or user email.": "For API key connections: responders by team name or user email.",
+ "Labels for searching and grouping alerts.": "Labels for searching and grouping alerts.",
+ "The server, service or app the alert is about.": "The server, service or app the alert is about.",
+ "The tool that raised the alert.": "The tool that raised the alert.",
+ "A first note to attach to the alert.": "A first note to attach to the alert.",
+ "Custom key-value details shown on the alert.": "Custom key-value details shown on the alert.",
+ "Names of custom alert actions to show on the alert.": "Names of custom alert actions to show on the alert.",
+ "API key connections only: who is shown as the creator.": "API key connections only: who is shown as the creator.",
+ "The alert ID, or its alias if you pick Alias below.": "The alert ID, or its alias if you pick Alias below.",
+ "Whether the value above is the alert ID or its alias.": "Whether the value above is the alert ID or its alias.",
+ "Alert search syntax. Leave empty to list all alerts.": "Alert search syntax. Leave empty to list all alerts.",
+ "How many alerts to return, from 1 to 100.": "How many alerts to return, from 1 to 100.",
+ "How many matching alerts to skip, for paging.": "How many matching alerts to skip, for paging.",
+ "Optional note to add to the alert at the same time.": "Optional note to add to the alert at the same time.",
+ "API key connections only: the name shown for this change.": "API key connections only: the name shown for this change.",
+ "API key connections only: where the change came from.": "API key connections only: where the change came from.",
+ "The note text. Up to 25,000 characters.": "The note text. Up to 25,000 characters.",
+ "API key connections only: the name shown on the note.": "API key connections only: the name shown on the note.",
+ "API key connections only: where the note came from.": "API key connections only: where the note came from.",
+ "Tags to add to the alert.": "Tags to add to the alert.",
+ "Tags to remove from the alert.": "Tags to remove from the alert.",
+ "The user who will own the alert. Type to search.": "The user who will own the alert. Type to search.",
+ "What kind of responder to add.": "What kind of responder to add.",
+ "The team, user, schedule or escalation to add.": "The team, user, schedule or escalation to add.",
+ "The escalation policy to use, listed with its team.": "The escalation policy to use, listed with its team.",
+ "When notifications should start again. Must be in the future.": "When notifications should start again. Must be in the future.",
+ "Leave empty to keep the current message. Up to 130 characters.": "Leave empty to keep the current message. Up to 130 characters.",
+ "Leave empty to keep the current description.": "Leave empty to keep the current description.",
+ "The on-call schedule to check.": "The on-call schedule to check.",
+ "Leave empty to check who is on call right now.": "Leave empty to check who is on call right now.",
+ "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.",
+ "P1 - Critical": "P1 - Critical",
+ "P2 - High": "P2 - High",
+ "P3 - Moderate": "P3 - Moderate",
+ "P4 - Low": "P4 - Low",
+ "P5 - Informational": "P5 - Informational",
+ "Alert ID": "Alert ID",
+ "Created at": "Created at",
+ "Last occurred at": "Last occurred at",
+ "Inserted at": "Inserted at",
+ "Newest / highest first": "Newest / highest first",
+ "Oldest / lowest first": "Oldest / lowest first",
+ "Team": "Team",
+ "User": "User",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
+ "New Alert": "New Alert",
+ "Triggers when a new alert is created.": "Triggers when a new alert is created.",
+ "Only Alerts Matching": "Only Alerts Matching",
+ "Optional alert search query to filter new alerts.": "Optional alert search query to filter new alerts."
+}
\ No newline at end of file
diff --git a/packages/pieces/community/jsm-operations/src/index.ts b/packages/pieces/community/jsm-operations/src/index.ts
new file mode 100644
index 00000000000..9e077ba54e8
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/index.ts
@@ -0,0 +1,56 @@
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { acknowledgeAlertAction } from './lib/actions/acknowledge-alert';
+import { addNoteAction } from './lib/actions/add-note';
+import { addResponderAction } from './lib/actions/add-responder';
+import { addTagsAction } from './lib/actions/add-tags';
+import { assignAlertAction } from './lib/actions/assign-alert';
+import { closeAlertAction } from './lib/actions/close-alert';
+import { createAlertAction } from './lib/actions/create-alert';
+import { jsmCustomApiCall } from './lib/actions/custom-api-call';
+import { escalateAlertAction } from './lib/actions/escalate-alert';
+import { findAlertsAction } from './lib/actions/find-alerts';
+import { getAlertAction } from './lib/actions/get-alert';
+import { getOnCallAction } from './lib/actions/get-on-call';
+import { removeTagsAction } from './lib/actions/remove-tags';
+import { snoozeAlertAction } from './lib/actions/snooze-alert';
+import { unacknowledgeAlertAction } from './lib/actions/unacknowledge-alert';
+import { updateAlertAction } from './lib/actions/update-alert';
+import { jsmOpsAuth } from './lib/auth';
+import { newAlertTrigger } from './lib/triggers/new-alert';
+
+export const jsmOperations = createPiece({
+ displayName: 'Jira Service Management Operations',
+ description:
+ 'Opsgenie alerts in Jira Service Management: create, acknowledge, close and route on-call alerts, and see who is on call.',
+ minimumSupportedRelease: '0.88.2',
+ logoUrl: 'https://cdn.activepieces.com/pieces/jira.png',
+ categories: [PieceCategory.DEVELOPER_TOOLS],
+ auth: jsmOpsAuth,
+ authors: ['OdaiAhmed99'],
+ actions: [
+ createAlertAction,
+ getAlertAction,
+ findAlertsAction,
+ acknowledgeAlertAction,
+ unacknowledgeAlertAction,
+ closeAlertAction,
+ addNoteAction,
+ addTagsAction,
+ removeTagsAction,
+ assignAlertAction,
+ addResponderAction,
+ escalateAlertAction,
+ snoozeAlertAction,
+ updateAlertAction,
+ getOnCallAction,
+ jsmCustomApiCall.withCloudId(
+ createCustomApiCallAction({
+ auth: jsmOpsAuth,
+ baseUrl: jsmCustomApiCall.baseUrl,
+ authMapping: jsmCustomApiCall.authMapping,
+ }),
+ ),
+ ],
+ triggers: [newAlertTrigger],
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/acknowledge-alert.ts b/packages/pieces/community/jsm-operations/src/lib/actions/acknowledge-alert.ts
new file mode 100644
index 00000000000..acf8a4e9efc
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/acknowledge-alert.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { alertActionOutputSchema } from '../output-schemas';
+
+export const acknowledgeAlertAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'acknowledge_alert',
+ classification: 'WRITE',
+ displayName: 'Acknowledge Alert',
+ description: 'Acknowledge an alert so responders know someone is on it.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Acknowledges an open JSM Operations or Opsgenie alert by ID or alias, optionally adding a note, and waits briefly for the result. Works with both connection types. Acknowledging an already acknowledged alert has no further effect, so it is safe to retry. If the optional note cannot be added, the alert is still acknowledged and note_added is false with the reason in note_error; retrying would add the note again.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'Optional note to add to the alert at the same time.',
+ required: false,
+ }),
+ user: Property.ShortText({
+ displayName: 'Done By',
+ description: 'API key connections only: the name shown for this change.',
+ required: false,
+ advanced: true,
+ }),
+ source: Property.ShortText({
+ displayName: 'Source',
+ description: 'API key connections only: where the change came from.',
+ required: false,
+ advanced: true,
+ }),
+ },
+ outputSchema: alertActionOutputSchema,
+ async run(context) {
+ const { alert, identifierType, note, user, source } = context.propsValue;
+ return jsmOps.sendAlertAction({
+ auth: context.auth,
+ alert,
+ identifierType: identifierType === 'alias' ? 'alias' : 'id',
+ action: 'acknowledge',
+ note,
+ user,
+ source,
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/add-note.ts b/packages/pieces/community/jsm-operations/src/lib/actions/add-note.ts
new file mode 100644
index 00000000000..f7db86d8ac0
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/add-note.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { addNoteOutputSchema } from '../output-schemas';
+
+export const addNoteAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'add_note',
+ classification: 'WRITE',
+ displayName: 'Add Note to Alert',
+ description: 'Add a note to an alert.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Adds a text note to a JSM Operations or Opsgenie alert by ID or alias, for status updates or findings. Works with both connection types. Each call adds another note, so retries duplicate it.',
+ idempotent: false,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'The note text. Up to 25,000 characters.',
+ required: true,
+ }),
+ user: Property.ShortText({
+ displayName: 'Added By',
+ description: 'API key connections only: the name shown on the note.',
+ required: false,
+ advanced: true,
+ }),
+ source: Property.ShortText({
+ displayName: 'Source',
+ description: 'API key connections only: where the note came from.',
+ required: false,
+ advanced: true,
+ }),
+ },
+ outputSchema: addNoteOutputSchema,
+ async run(context) {
+ const { alert, identifierType, note, user, source } = context.propsValue;
+ return jsmOps.addNote({
+ auth: context.auth,
+ alert,
+ identifierType: identifierType === 'alias' ? 'alias' : 'id',
+ note,
+ user,
+ source,
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/add-responder.ts b/packages/pieces/community/jsm-operations/src/lib/actions/add-responder.ts
new file mode 100644
index 00000000000..70ea260ada7
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/add-responder.ts
@@ -0,0 +1,44 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { requestResultOutputSchema } from '../output-schemas';
+
+export const addResponderAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'add_responder',
+ classification: 'WRITE',
+ displayName: 'Add Responder to Alert',
+ description: 'Add a team, user, schedule or escalation as a responder.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Adds one responder (team, user, schedule or escalation) to a JSM Operations alert so they are notified. Use Assign Alert to change the owner instead. Needs an Atlassian account connection. Adding an existing responder has no further effect, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ responderType: jsmOpsProps.responderType(),
+ responder: jsmOpsProps.responder(),
+ },
+ outputSchema: requestResultOutputSchema,
+ async run(context) {
+ const { responderType, responder } = context.propsValue;
+ const id = responder?.trim() ?? '';
+ if (id.length === 0) {
+ throw new Error('Pick the responder to add.');
+ }
+ return jsmOps.runAccountAlertRequest({
+ auth: context.auth,
+ feature: 'Add Responder to Alert',
+ alert: context.propsValue.alert,
+ identifierType: context.propsValue.identifierType === 'alias' ? 'alias' : 'id',
+ method: HttpMethod.POST,
+ suffix: 'responders',
+ body: { id, type: responderType },
+ verb: 'add the responder',
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/add-tags.ts b/packages/pieces/community/jsm-operations/src/lib/actions/add-tags.ts
new file mode 100644
index 00000000000..1416c261486
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/add-tags.ts
@@ -0,0 +1,38 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { requestResultOutputSchema } from '../output-schemas';
+
+export const addTagsAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'add_tags',
+ classification: 'WRITE',
+ displayName: 'Add Tags to Alert',
+ description: 'Add one or more tags to an alert.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Adds tags to a JSM Operations alert by ID or alias, keeping its existing tags. Use Remove Tags from Alert to take tags off. Needs an Atlassian account connection. Adding a tag that is already there has no effect, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'Tags to add to the alert.',
+ required: true,
+ }),
+ },
+ outputSchema: requestResultOutputSchema,
+ async run(context) {
+ return jsmOps.changeTags({
+ auth: context.auth,
+ alert: context.propsValue.alert,
+ identifierType: context.propsValue.identifierType === 'alias' ? 'alias' : 'id',
+ tags: context.propsValue.tags,
+ operation: 'add',
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/assign-alert.ts b/packages/pieces/community/jsm-operations/src/lib/actions/assign-alert.ts
new file mode 100644
index 00000000000..5be8ecc5094
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/assign-alert.ts
@@ -0,0 +1,45 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { requestResultOutputSchema } from '../output-schemas';
+
+export const assignAlertAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'assign_alert',
+ classification: 'WRITE',
+ displayName: 'Assign Alert',
+ description: 'Make a user the owner of an alert. Not available on the JSM Free plan.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sets the owner of a JSM Operations alert to one Atlassian user, picked by account. Use Add Responder to Alert to notify more people without changing the owner. Needs an Atlassian account connection and a paid JSM plan (the Free plan rejects assignment). Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ accountId: jsmOpsProps.user({
+ displayName: 'Assignee',
+ description: 'The user who will own the alert. Type to search.',
+ }),
+ },
+ outputSchema: requestResultOutputSchema,
+ async run(context) {
+ const accountId = context.propsValue.accountId?.trim() ?? '';
+ if (accountId.length === 0) {
+ throw new Error('Pick the user to assign the alert to.');
+ }
+ return jsmOps.runAccountAlertRequest({
+ auth: context.auth,
+ feature: 'Assign Alert',
+ alert: context.propsValue.alert,
+ identifierType: context.propsValue.identifierType === 'alias' ? 'alias' : 'id',
+ method: HttpMethod.POST,
+ suffix: 'assign',
+ body: { accountId },
+ verb: 'assign the alert',
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/close-alert.ts b/packages/pieces/community/jsm-operations/src/lib/actions/close-alert.ts
new file mode 100644
index 00000000000..7469ee89177
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/close-alert.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { alertActionOutputSchema } from '../output-schemas';
+
+export const closeAlertAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'close_alert',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Close Alert',
+ description: 'Close an alert once the problem is resolved.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Closes a JSM Operations or Opsgenie alert by ID or alias, optionally adding a note, and waits briefly for the result. Works with both connection types. A closed alert cannot be reopened; closing an already closed alert has no further effect, so it is safe to retry. If the optional note cannot be added, the alert is still closed and note_added is false with the reason in note_error; retrying would add the note again.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'Optional note to add to the alert at the same time.',
+ required: false,
+ }),
+ user: Property.ShortText({
+ displayName: 'Done By',
+ description: 'API key connections only: the name shown for this change.',
+ required: false,
+ advanced: true,
+ }),
+ source: Property.ShortText({
+ displayName: 'Source',
+ description: 'API key connections only: where the change came from.',
+ required: false,
+ advanced: true,
+ }),
+ },
+ outputSchema: alertActionOutputSchema,
+ async run(context) {
+ const { alert, identifierType, note, user, source } = context.propsValue;
+ return jsmOps.sendAlertAction({
+ auth: context.auth,
+ alert,
+ identifierType: identifierType === 'alias' ? 'alias' : 'id',
+ action: 'close',
+ note,
+ user,
+ source,
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/create-alert.ts b/packages/pieces/community/jsm-operations/src/lib/actions/create-alert.ts
new file mode 100644
index 00000000000..e8ea1d73e53
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/create-alert.ts
@@ -0,0 +1,210 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { ApiResponder } from '../common/types';
+import { requestResultOutputSchema } from '../output-schemas';
+
+export const createAlertAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'create_alert',
+ classification: 'WRITE',
+ displayName: 'Create Alert',
+ description: 'Create a new alert and route it to teams, users or schedules.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a JSM Operations (or Opsgenie) alert and waits up to about 10 seconds for it to be processed, returning the new alert ID. Works with both connection types. Set an alias to deduplicate: a second alert with an open alias only raises its count, so retries with the same alias are safe; without an alias each call creates a new alert.',
+ idempotent: false,
+ },
+ props: {
+ message: Property.ShortText({
+ displayName: 'Message',
+ description: 'Short summary of the problem. Up to 130 characters.',
+ placeholder: 'e.g. CPU above 90% on web-01',
+ required: true,
+ }),
+ description: Property.LongText({
+ displayName: 'Description',
+ description: 'Full details of the alert. Up to 15,000 characters.',
+ required: false,
+ }),
+ priority: jsmOpsProps.priority({ required: false, defaultValue: 'P3' }),
+ alias: Property.ShortText({
+ displayName: 'Alias',
+ description: 'Your own unique key for the alert. Open duplicates are merged.',
+ placeholder: 'e.g. web-01-high-cpu',
+ required: false,
+ }),
+ responderTeams: jsmOpsProps.teams({
+ displayName: 'Responder Teams',
+ description: 'Teams to notify. Needs an Atlassian Account connection.',
+ }),
+ responderUsers: jsmOpsProps.users({
+ displayName: 'Responder Users',
+ description: 'Users to notify. Needs an Atlassian Account connection.',
+ }),
+ responderSchedules: jsmOpsProps.schedules({
+ displayName: 'Responder Schedules',
+ description: 'Schedules whose on-call users are notified.',
+ }),
+ responderEscalations: jsmOpsProps.escalations({
+ displayName: 'Responder Escalations',
+ description: 'Escalation policies to start for this alert.',
+ }),
+ responderNames: Property.Array({
+ displayName: 'Responders by Name (API Key Connections)',
+ description: 'For API key connections: responders by team name or user email.',
+ required: false,
+ advanced: true,
+ properties: {
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: true,
+ defaultValue: 'team',
+ options: {
+ options: [
+ { label: 'Team', value: 'team' },
+ { label: 'User (email)', value: 'user' },
+ { label: 'Schedule', value: 'schedule' },
+ { label: 'Escalation', value: 'escalation' },
+ ],
+ },
+ }),
+ name: Property.ShortText({
+ displayName: 'Name or Email',
+ required: true,
+ }),
+ },
+ }),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'Labels for searching and grouping alerts.',
+ required: false,
+ }),
+ entity: Property.ShortText({
+ displayName: 'Entity',
+ description: 'The server, service or app the alert is about.',
+ placeholder: 'e.g. web-01',
+ required: false,
+ advanced: true,
+ }),
+ source: Property.ShortText({
+ displayName: 'Source',
+ description: 'The tool that raised the alert.',
+ placeholder: 'e.g. Activepieces',
+ required: false,
+ advanced: true,
+ }),
+ note: Property.LongText({
+ displayName: 'Note',
+ description: 'A first note to attach to the alert.',
+ required: false,
+ advanced: true,
+ }),
+ extraProperties: Property.Object({
+ displayName: 'Extra Properties',
+ description: 'Custom key-value details shown on the alert.',
+ required: false,
+ advanced: true,
+ }),
+ actions: Property.Array({
+ displayName: 'Custom Actions',
+ description: 'Names of custom alert actions to show on the alert.',
+ required: false,
+ advanced: true,
+ }),
+ user: Property.ShortText({
+ displayName: 'Created By',
+ description: 'API key connections only: who is shown as the creator.',
+ required: false,
+ advanced: true,
+ }),
+ },
+ outputSchema: requestResultOutputSchema,
+ async run(context) {
+ const props = context.propsValue;
+ const route = await jsmOps.routeFor(context.auth);
+ const message = props.message.trim();
+ if (message.length === 0) {
+ throw new Error('Enter an alert message.');
+ }
+ const namedResponders = toNamedResponders(props.responderNames);
+ if (route.kind === 'account' && namedResponders.length > 0) {
+ throw new Error(
+ 'Responders by Name only work with API key connections. Pick the responders from the Teams, Users, Schedules or Escalations lists instead.',
+ );
+ }
+ const responders = [
+ ...toIdResponders({ ids: props.responderTeams, type: 'team' }),
+ ...toIdResponders({ ids: props.responderUsers, type: 'user' }),
+ ...toIdResponders({ ids: props.responderSchedules, type: 'schedule' }),
+ ...toIdResponders({ ids: props.responderEscalations, type: 'escalation' }),
+ ...namedResponders,
+ ];
+ const details = toStringMap(props.extraProperties);
+ const body = {
+ message,
+ ...optional({ key: 'alias', value: props.alias }),
+ ...optional({ key: 'description', value: props.description }),
+ ...optional({ key: 'priority', value: props.priority }),
+ ...optional({ key: 'entity', value: props.entity }),
+ ...optional({ key: 'source', value: props.source }),
+ ...optional({ key: 'note', value: props.note }),
+ ...(route.kind === 'key' ? optional({ key: 'user', value: props.user }) : {}),
+ ...(responders.length > 0 ? { responders } : {}),
+ ...listField({ key: 'tags', value: props.tags }),
+ ...listField({ key: 'actions', value: props.actions }),
+ ...(Object.keys(details).length > 0 ? { [route.kind === 'key' ? 'details' : 'extraProperties']: details } : {}),
+ };
+ return jsmOps.runAsync({ route, method: HttpMethod.POST, path: '/alerts', body, verb: 'create the alert' });
+ },
+});
+
+function toIdResponders({ ids, type }: { ids: unknown; type: string }): ApiResponder[] {
+ return jsmOps.parseStringList(ids).map((id) => ({ id, type }));
+}
+
+function toNamedResponders(rows: unknown): ApiResponder[] {
+ if (!Array.isArray(rows)) {
+ return [];
+ }
+ return rows.flatMap((row) => {
+ if (row === null || typeof row !== 'object' || !('type' in row) || !('name' in row)) {
+ return [];
+ }
+ const type = typeof row.type === 'string' ? row.type : '';
+ const name = typeof row.name === 'string' ? row.name.trim() : '';
+ if (name.length === 0 || !RESPONDER_TYPES.includes(type)) {
+ return [];
+ }
+ return [type === 'user' ? { username: name, type } : { name, type }];
+ });
+}
+
+function toStringMap(value: unknown): Record<string, string> {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ return {};
+ }
+ return Object.fromEntries(
+ Object.entries(value).flatMap(([key, item]) => {
+ if (key.trim().length === 0 || item === undefined || item === null || item === '') {
+ return [];
+ }
+ return [[key, typeof item === 'string' ? item : JSON.stringify(item)]];
+ }),
+ );
+}
+
+function optional({ key, value }: { key: string; value: string | undefined }): Record<string, string> {
+ const trimmed = value?.trim() ?? '';
+ return trimmed.length > 0 ? { [key]: trimmed } : {};
+}
+
+function listField({ key, value }: { key: string; value: unknown }): Record<string, string[]> {
+ const list = jsmOps.parseStringList(value);
+ return list.length > 0 ? { [key]: list } : {};
+}
+
+const RESPONDER_TYPES = ['team', 'user', 'schedule', 'escalation'];
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/custom-api-call.ts b/packages/pieces/community/jsm-operations/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..d17901b00d7
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,84 @@
+import { createAction, IAction, InputPropertyMap } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { JsmAuthValue } from '../common/types';
+
+export const jsmCustomApiCall = {
+ baseUrl,
+ authMapping,
+ withCloudId,
+};
+
+function baseUrl(auth: JsmAuthValue | undefined): string {
+ if (auth === undefined) {
+ return '';
+ }
+ if (jsmOps.isKeyConnection(auth)) {
+ return jsmOps.keyBaseUrl(jsmOps.keyProps(auth));
+ }
+ const cloudId = auth.props.cloudId?.trim() ?? '';
+ return jsmOps.accountBaseUrl(cloudId.length > 0 ? cloudId : '{cloudId}');
+}
+
+async function authMapping(auth: JsmAuthValue): Promise<Record<string, string>> {
+ return jsmOps.authHeaders(auth);
+}
+
+function withCloudId<Props extends InputPropertyMap>(base: IAction<typeof jsmOpsAuth, Props>) {
+ return createAction({
+ auth: jsmOpsAuth,
+ name: 'custom_api_call',
+ classification: 'WRITE',
+ displayName: base.displayName,
+ description: 'Call any JSM Operations endpoint with this connection.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Sends a raw HTTP request to the JSM Operations API with the connection credentials: /jsm/ops/api/{cloudId}/v1 for account connections, the /v2 alert API for API keys. Use only when no dedicated action fits. Whether a retry is safe depends on the method and endpoint.',
+ idempotent: false,
+ },
+ props: base.props,
+ errorHandlingOptions: base.errorHandlingOptions,
+ async run(context) {
+ const auth = context.auth;
+ const url = readUrl(context.propsValue);
+ if (jsmOps.isKeyConnection(auth)) {
+ assertOnConnectionHost({ url, base: baseUrl(auth) });
+ return base.run({ ...context, auth });
+ }
+ const props = await jsmOps.fillCloudId(auth.props);
+ const filled = { ...auth, props };
+ assertOnConnectionHost({ url, base: baseUrl(filled) });
+ return base.run({ ...context, auth: filled });
+ },
+ });
+}
+
+function readUrl(propsValue: unknown): string {
+ if (typeof propsValue !== 'object' || propsValue === null || !('url' in propsValue)) {
+ return '';
+ }
+ const field = propsValue.url;
+ if (typeof field !== 'object' || field === null || !('url' in field)) {
+ return '';
+ }
+ return typeof field.url === 'string' ? field.url.trim() : '';
+}
+
+function assertOnConnectionHost({ url, base }: { url: string; base: string }): void {
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(url) && !url.startsWith('//')) {
+ return;
+ }
+ const allowed = new URL(base);
+ const allowedPath = allowed.pathname.replace(/\/+$/, '');
+ let target: URL;
+ try {
+ target = new URL(url);
+ } catch {
+ throw new Error(`"${url}" is not a valid URL. Use a path such as /alerts, or a full URL under ${base}.`);
+ }
+ const onBase = target.origin === allowed.origin && (target.pathname === allowedPath || target.pathname.startsWith(`${allowedPath}/`));
+ if (!onBase || target.username !== '' || target.password !== '') {
+ throw new Error(`Custom API Call only sends this connection's credentials to ${base}. Use a path such as /alerts, or a full URL under that address.`);
+ }
+}
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/escalate-alert.ts b/packages/pieces/community/jsm-operations/src/lib/actions/escalate-alert.ts
new file mode 100644
index 00000000000..6d2870a5066
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/escalate-alert.ts
@@ -0,0 +1,45 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { requestResultOutputSchema } from '../output-schemas';
+
+export const escalateAlertAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'escalate_alert',
+ classification: 'WRITE',
+ displayName: 'Escalate Alert',
+ description: 'Escalate an alert to the next level of an escalation policy.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Escalates a JSM Operations alert through the chosen escalation policy, notifying its next recipients. Use Add Responder to Alert to notify one specific team or user. Needs an Atlassian account connection. Each call can notify further recipients, so retries are not safe.',
+ idempotent: false,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ escalationId: jsmOpsProps.escalation({
+ displayName: 'Escalation',
+ description: 'The escalation policy to use, listed with its team.',
+ }),
+ },
+ outputSchema: requestResultOutputSchema,
+ async run(context) {
+ const escalationId = context.propsValue.escalationId?.trim() ?? '';
+ if (escalationId.length === 0) {
+ throw new Error('Pick the escalation to use.');
+ }
+ return jsmOps.runAccountAlertRequest({
+ auth: context.auth,
+ feature: 'Escalate Alert',
+ alert: context.propsValue.alert,
+ identifierType: context.propsValue.identifierType === 'alias' ? 'alias' : 'id',
+ method: HttpMethod.POST,
+ suffix: 'escalate',
+ body: { escalationId },
+ verb: 'escalate the alert',
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/find-alerts.ts b/packages/pieces/community/jsm-operations/src/lib/actions/find-alerts.ts
new file mode 100644
index 00000000000..303ba458a82
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/find-alerts.ts
@@ -0,0 +1,110 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { ApiAlertList } from '../common/types';
+import { findAlertsOutputSchema } from '../output-schemas';
+
+export const findAlertsAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'find_alerts',
+ classification: 'SEARCH',
+ displayName: 'Find Alerts',
+ description: 'Search alerts with a JSM Operations search query.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists JSM Operations alerts that match an alert search query (for example status: open AND priority: P1), sorted and paged. Returns zero or more alerts. Use Get Alert when you already know the ID or alias. Needs an Atlassian account connection. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.ShortText({
+ displayName: 'Search Query',
+ description: 'Alert search syntax. Leave empty to list all alerts.',
+ placeholder: 'e.g. status: open AND priority: P1',
+ required: false,
+ }),
+ sort: Property.StaticDropdown({
+ displayName: 'Sort By',
+ required: false,
+ defaultValue: 'createdAt',
+ options: {
+ options: [
+ { label: 'Created at', value: 'createdAt' },
+ { label: 'Last occurred at', value: 'lastOccurredAt' },
+ { label: 'Inserted at', value: 'insertedAt' },
+ { label: 'Priority', value: 'priority' },
+ ],
+ },
+ }),
+ order: Property.StaticDropdown({
+ displayName: 'Order',
+ required: false,
+ defaultValue: 'desc',
+ options: {
+ options: [
+ { label: 'Newest / highest first', value: 'desc' },
+ { label: 'Oldest / lowest first', value: 'asc' },
+ ],
+ },
+ }),
+ limit: Property.Number({
+ displayName: 'Max Results',
+ description: 'How many alerts to return, from 1 to 100.',
+ required: false,
+ defaultValue: 20,
+ display: 'stepper',
+ min: 1,
+ max: 100,
+ step: 1,
+ }),
+ offset: Property.Number({
+ displayName: 'Skip',
+ description: 'How many matching alerts to skip, for paging.',
+ required: false,
+ defaultValue: 0,
+ advanced: true,
+ }),
+ },
+ outputSchema: findAlertsOutputSchema,
+ async run(context) {
+ const route = await jsmOps.requireAccountRoute({ auth: context.auth, feature: 'Find Alerts' });
+ const body = await jsmOps.send<ApiAlertList>({
+ route,
+ method: HttpMethod.GET,
+ path: '/alerts',
+ queryParams: buildFindQuery(context.propsValue),
+ });
+ return (body.values ?? []).map((alert) => jsmOps.toAlertOutput(alert));
+ },
+});
+
+function buildFindQuery({ query, sort, order, limit, offset }: FindInput): Record<string, string> {
+ const size = clamp({ value: limit ?? 20, min: 1, max: 100 });
+ const skip = Math.max(0, Math.floor(offset ?? 0));
+ const trimmed = query?.trim() ?? '';
+ return {
+ ...(trimmed.length > 0 ? { query: trimmed } : {}),
+ sort: SORT_FIELDS.includes(sort ?? '') ? sort ?? 'createdAt' : 'createdAt',
+ order: order === 'asc' ? 'asc' : 'desc',
+ size: String(size),
+ offset: String(skip),
+ };
+}
+
+function clamp({ value, min, max }: { value: number; min: number; max: number }): number {
+ if (!Number.isFinite(value)) {
+ return min;
+ }
+ return Math.min(max, Math.max(min, Math.floor(value)));
+}
+
+const SORT_FIELDS = ['createdAt', 'lastOccurredAt', 'insertedAt', 'priority'];
+
+type FindInput = {
+ query?: string;
+ sort?: string;
+ order?: string;
+ limit?: number;
+ offset?: number;
+};
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/get-alert.ts b/packages/pieces/community/jsm-operations/src/lib/actions/get-alert.ts
new file mode 100644
index 00000000000..e70bf2767da
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/get-alert.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { alertOutputSchema } from '../output-schemas';
+
+export const getAlertAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'get_alert',
+ classification: 'READ',
+ displayName: 'Get Alert',
+ description: 'Get one alert by its ID or alias.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Reads a single JSM Operations alert by its alert ID or by its alias and returns its status, priority, owner, tags and timestamps. Use Find Alerts to search by criteria instead. Needs an Atlassian account connection. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ },
+ outputSchema: alertOutputSchema,
+ async run(context) {
+ const route = await jsmOps.requireAccountRoute({ auth: context.auth, feature: 'Get Alert' });
+ const alert = await jsmOps.getAlert({
+ route,
+ alert: context.propsValue.alert,
+ identifierType: context.propsValue.identifierType === 'alias' ? 'alias' : 'id',
+ });
+ return jsmOps.toAlertOutput(alert);
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/get-on-call.ts b/packages/pieces/community/jsm-operations/src/lib/actions/get-on-call.ts
new file mode 100644
index 00000000000..cf15ee956d4
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/get-on-call.ts
@@ -0,0 +1,91 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { ApiOnCallParticipant, ApiOnCallResponse, OnCallParticipantOutput } from '../common/types';
+import { onCallOutputSchema } from '../output-schemas';
+
+export const getOnCallAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'get_on_call',
+ classification: 'READ',
+ displayName: 'Get Who Is On Call',
+ description: 'Get who is on call for a schedule, now or at a given time.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns the on-call participants of one JSM Operations schedule at the current time or a given date, including users reached through teams or escalations, plus a comma-separated list of on-call user account IDs. Needs an Atlassian account connection. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ scheduleId: jsmOpsProps.schedule({
+ displayName: 'Schedule',
+ description: 'The on-call schedule to check.',
+ }),
+ date: Property.DateTime({
+ displayName: 'At Time',
+ description: 'Leave empty to check who is on call right now.',
+ required: false,
+ }),
+ },
+ outputSchema: onCallOutputSchema,
+ async run(context) {
+ const scheduleId = context.propsValue.scheduleId?.trim() ?? '';
+ if (scheduleId.length === 0) {
+ throw new Error('Pick the schedule to check.');
+ }
+ const date = toIsoDate(context.propsValue.date);
+ const route = await jsmOps.requireAccountRoute({ auth: context.auth, feature: 'Get Who Is On Call' });
+ const body = await jsmOps.send<ApiOnCallResponse>({
+ route,
+ method: HttpMethod.GET,
+ path: `/schedules/${encodeURIComponent(scheduleId)}/on-calls`,
+ queryParams: { flat: 'false', ...(date === null ? {} : { date }) },
+ });
+ const participants = flattenParticipants({ participants: body.onCallParticipants ?? [], parent: null });
+ const userIds = [
+ ...new Set([
+ ...participants.flatMap((participant) => (participant.type === 'user' && participant.id !== null ? [participant.id] : [])),
+ ...(body.onCallUsers ?? []),
+ ]),
+ ];
+ return {
+ schedule_id: scheduleId,
+ date,
+ on_call_user_ids: userIds.join(', '),
+ on_call_user_count: userIds.length,
+ participants,
+ };
+ },
+});
+
+function flattenParticipants({ participants, parent }: FlattenParams): OnCallParticipantOutput[] {
+ return participants.flatMap((participant) => {
+ const row: OnCallParticipantOutput = {
+ id: participant.id ?? null,
+ type: participant.type ?? null,
+ name: participant.name ?? null,
+ parent_id: parent?.id ?? null,
+ parent_type: parent?.type ?? null,
+ forwarded_from_id: participant.forwardedFrom?.id ?? null,
+ };
+ return [row, ...flattenParticipants({ participants: participant.onCallParticipants ?? [], parent: participant })];
+ });
+}
+
+function toIsoDate(value: string | undefined): string | null {
+ if (value === undefined || value.trim().length === 0) {
+ return null;
+ }
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) {
+ throw new Error('At Time must be a valid date and time.');
+ }
+ return parsed.toISOString();
+}
+
+type FlattenParams = {
+ participants: ApiOnCallParticipant[];
+ parent: ApiOnCallParticipant | null;
+};
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/remove-tags.ts b/packages/pieces/community/jsm-operations/src/lib/actions/remove-tags.ts
new file mode 100644
index 00000000000..05a4bbbebd1
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/remove-tags.ts
@@ -0,0 +1,38 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { requestResultOutputSchema } from '../output-schemas';
+
+export const removeTagsAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'remove_tags',
+ classification: 'WRITE',
+ displayName: 'Remove Tags from Alert',
+ description: 'Remove one or more tags from an alert.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Removes the listed tags from a JSM Operations alert by ID or alias; the alert itself is kept. Use Add Tags to Alert to add them back. Needs an Atlassian account connection. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ tags: Property.Array({
+ displayName: 'Tags',
+ description: 'Tags to remove from the alert.',
+ required: true,
+ }),
+ },
+ outputSchema: requestResultOutputSchema,
+ async run(context) {
+ return jsmOps.changeTags({
+ auth: context.auth,
+ alert: context.propsValue.alert,
+ identifierType: context.propsValue.identifierType === 'alias' ? 'alias' : 'id',
+ tags: context.propsValue.tags,
+ operation: 'remove',
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/snooze-alert.ts b/packages/pieces/community/jsm-operations/src/lib/actions/snooze-alert.ts
new file mode 100644
index 00000000000..0151076c7c7
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/snooze-alert.ts
@@ -0,0 +1,49 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { requestResultOutputSchema } from '../output-schemas';
+
+export const snoozeAlertAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'snooze_alert',
+ classification: 'WRITE',
+ displayName: 'Snooze Alert',
+ description: 'Pause notifications for an alert until a set time. Not on JSM Free.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Snoozes a JSM Operations alert until the given end time, pausing its notifications; the alert reopens after that. Needs an Atlassian account connection and a paid JSM plan (the Free plan rejects snoozing). Snoozing again to the same time has the same result, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ endTime: Property.DateTime({
+ displayName: 'Snooze Until',
+ description: 'When notifications should start again. Must be in the future.',
+ required: true,
+ }),
+ },
+ outputSchema: requestResultOutputSchema,
+ async run(context) {
+ const endTime = new Date(context.propsValue.endTime);
+ if (Number.isNaN(endTime.getTime())) {
+ throw new Error('Snooze Until must be a valid date and time.');
+ }
+ if (endTime.getTime() <= Date.now()) {
+ throw new Error('Snooze Until must be in the future.');
+ }
+ return jsmOps.runAccountAlertRequest({
+ auth: context.auth,
+ feature: 'Snooze Alert',
+ alert: context.propsValue.alert,
+ identifierType: context.propsValue.identifierType === 'alias' ? 'alias' : 'id',
+ method: HttpMethod.POST,
+ suffix: 'snooze',
+ body: { endTime: endTime.toISOString() },
+ verb: 'snooze the alert',
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/unacknowledge-alert.ts b/packages/pieces/community/jsm-operations/src/lib/actions/unacknowledge-alert.ts
new file mode 100644
index 00000000000..0c8fb836e23
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/unacknowledge-alert.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { requestResultOutputSchema } from '../output-schemas';
+
+export const unacknowledgeAlertAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'unacknowledge_alert',
+ classification: 'WRITE',
+ displayName: 'Unacknowledge Alert',
+ description: 'Put an acknowledged alert back to open.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Reverts an acknowledged JSM Operations alert to unacknowledged so notifications resume. Use Acknowledge Alert for the opposite. Needs an Atlassian account connection. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ },
+ outputSchema: requestResultOutputSchema,
+ async run(context) {
+ return jsmOps.runAccountAlertRequest({
+ auth: context.auth,
+ feature: 'Unacknowledge Alert',
+ alert: context.propsValue.alert,
+ identifierType: context.propsValue.identifierType === 'alias' ? 'alias' : 'id',
+ method: HttpMethod.POST,
+ suffix: 'unacknowledge',
+ verb: 'unacknowledge the alert',
+ });
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/actions/update-alert.ts b/packages/pieces/community/jsm-operations/src/lib/actions/update-alert.ts
new file mode 100644
index 00000000000..46651dbe525
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/actions/update-alert.ts
@@ -0,0 +1,71 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { jsmOpsProps } from '../common/props';
+import { RequestResult } from '../common/types';
+import { updateAlertOutputSchema } from '../output-schemas';
+
+export const updateAlertAction = createAction({
+ auth: jsmOpsAuth,
+ name: 'update_alert',
+ classification: 'WRITE',
+ displayName: 'Update Alert',
+ description: 'Change the message, description or priority of an alert.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Updates the message, description and/or priority of an existing JSM Operations alert; only the fields you fill in are changed. Needs an Atlassian account connection. Setting the same values again gives the same result, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ alert: jsmOpsProps.alert(),
+ identifierType: jsmOpsProps.identifierType(),
+ message: Property.ShortText({
+ displayName: 'New Message',
+ description: 'Leave empty to keep the current message. Up to 130 characters.',
+ required: false,
+ }),
+ description: Property.LongText({
+ displayName: 'New Description',
+ description: 'Leave empty to keep the current description.',
+ required: false,
+ }),
+ priority: jsmOpsProps.priority({ required: false }),
+ },
+ outputSchema: updateAlertOutputSchema,
+ async run(context) {
+ const { message, description, priority } = context.propsValue;
+ const changes = [
+ { field: 'message', value: message?.trim() ?? '' },
+ { field: 'description', value: description?.trim() ?? '' },
+ { field: 'priority', value: priority ?? '' },
+ ].filter((change) => change.value.length > 0);
+ if (changes.length === 0) {
+ throw new Error('Fill in at least one of New Message, New Description or Priority.');
+ }
+ const route = await jsmOps.requireAccountRoute({ auth: context.auth, feature: 'Update Alert' });
+ const alertId = await jsmOps.resolveAlertId({
+ route,
+ alert: context.propsValue.alert,
+ identifierType: context.propsValue.identifierType === 'alias' ? 'alias' : 'id',
+ });
+ const requests: (RequestResult & { field: string })[] = [];
+ for (const change of changes) {
+ const result = await jsmOps.runAsync({
+ route,
+ method: HttpMethod.PATCH,
+ path: `/alerts/${encodeURIComponent(alertId)}/${change.field}`,
+ body: { [change.field]: change.value },
+ verb: `update the alert ${change.field}`,
+ });
+ requests.push({ field: change.field, ...result, alert_id: result.alert_id ?? alertId });
+ }
+ return {
+ alert_id: alertId,
+ updated_fields: changes.map((change) => change.field).join(', '),
+ processed: requests.every((request) => request.processed),
+ requests,
+ };
+ },
+});
diff --git a/packages/pieces/community/jsm-operations/src/lib/auth.ts b/packages/pieces/community/jsm-operations/src/lib/auth.ts
new file mode 100644
index 00000000000..b0e42d49170
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/auth.ts
@@ -0,0 +1,59 @@
+import { PieceAuth, Property } from '@activepieces/pieces-framework';
+import { jsmOps } from './common/client';
+
+export const jsmAccountAuth = PieceAuth.CustomAuth({
+ displayName: 'Atlassian Account',
+ description: `Use this for every action. It connects with your Atlassian email and an API token.
+
+1. Open [API tokens](https://id.atlassian.com/manage-profile/security/api-tokens) and click **Create API token** (not "with scopes").
+2. Copy the token and paste it below with the email you sign in with.
+3. Enter your site URL, like https://your-company.atlassian.net.
+
+The account needs access to JSM Operations (alerts, teams and schedules) on that site.`,
+ required: true,
+ props: {
+ siteUrl: Property.ShortText({
+ displayName: 'Site URL',
+ description: 'Your Atlassian Cloud site address.',
+ placeholder: 'https://your-company.atlassian.net',
+ required: true,
+ }),
+ email: Property.ShortText({
+ displayName: 'Email',
+ description: 'The email address of the Atlassian account.',
+ placeholder: '[email protected]',
+ required: true,
+ }),
+ apiToken: PieceAuth.SecretText({
+ displayName: 'API Token',
+ description: 'An unscoped API token from id.atlassian.com.',
+ required: true,
+ }),
+ cloudId: Property.ShortText({
+ displayName: 'Cloud ID',
+ description: 'Leave empty to look it up from the site URL.',
+ required: false,
+ }),
+ },
+ validate: async ({ auth }) => jsmOps.validateAccount(auth),
+});
+
+export const jsmKeyAuth = PieceAuth.BasicAuth({
+ displayName: 'Alert API Key (Opsgenie or JSM integration)',
+ description: `Use this to create, acknowledge and close alerts or add notes with an integration API key. Other actions and the trigger need an Atlassian Account connection.
+
+- **JSM Operations:** open **Operations > Integrations**, add an **API** integration, copy its API key, and enter \`jsm\` as the API host.
+- **Opsgenie:** open **Settings > Integrations**, add an **API** integration, and copy its API key. Enter \`us\` as the API host, or \`eu\` if your Opsgenie address contains "eu".`,
+ required: true,
+ username: {
+ displayName: 'API Host',
+ description: 'jsm (JSM integration), us (Opsgenie US) or eu (Opsgenie EU).',
+ },
+ password: {
+ displayName: 'API Key',
+ description: 'The API key of an API integration.',
+ },
+ validate: async ({ auth }) => jsmOps.validateKey(auth),
+});
+
+export const jsmOpsAuth = [jsmAccountAuth, jsmKeyAuth];
diff --git a/packages/pieces/community/jsm-operations/src/lib/common/client.ts b/packages/pieces/community/jsm-operations/src/lib/common/client.ts
new file mode 100644
index 00000000000..9a90861fbfa
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/common/client.ts
@@ -0,0 +1,678 @@
+import { httpClient, HttpError, HttpMethod } from '@activepieces/pieces-common';
+import { AppConnectionType } from '@activepieces/pieces-framework';
+import {
+ AccountAuthProps,
+ AccountRoute,
+ AlertActionResult,
+ AlertIdentifierType,
+ AlertOutput,
+ ApiAlert,
+ ApiAsyncResponse,
+ ApiNote,
+ ApiRequestStatus,
+ JsmAuthValue,
+ KeyAuthProps,
+ KeyRoute,
+ RequestResult,
+ Route,
+} from './types';
+
+export const jsmOps = {
+ isKeyConnection,
+ keyProps,
+ resolveKeyHost,
+ normalizeSiteUrl,
+ resolveCloudId,
+ fillCloudId,
+ accountBaseUrl,
+ keyBaseUrl,
+ authHeaders,
+ routeFor,
+ requireAccountRoute,
+ send,
+ sendToSite,
+ resolveAlertId,
+ getAlert,
+ runAsync,
+ awaitRequest,
+ sendAlertAction,
+ runAccountAlertRequest,
+ changeTags,
+ addNote,
+ toAlertOutput,
+ parseStringList,
+ describeError,
+ validateAccount,
+ validateKey,
+};
+
+export const JSM_ACCOUNT_API_URL = 'https://api.atlassian.com/jsm/ops/api';
+export const KEY_HOSTS = {
+ jsm: 'https://api.atlassian.com/jsm/ops/integration',
+ opsgenieUs: 'https://api.opsgenie.com',
+ opsgenieEu: 'https://api.eu.opsgenie.com',
+};
+export const REQUEST_TIMEOUT_MS = 15_000;
+export const POLL_TIMEOUT_MS = 4_000;
+export const POLL_DELAYS_MS = [500, 1_000, 2_000, 3_000, 4_000];
+
+function isKeyConnection<T extends { type: AppConnectionType }>(auth: T): auth is Extract<T, { type: AppConnectionType.BASIC_AUTH }> {
+ return auth.type === AppConnectionType.BASIC_AUTH;
+}
+
+function keyProps({ username, password }: { username: string; password: string }): KeyAuthProps {
+ return { host: resolveKeyHost(username), apiKey: password.trim() };
+}
+
+function resolveKeyHost(value: string): string {
+ const normalized = value.trim().toLowerCase().replace(/\/+$/, '');
+ const alias = KEY_HOST_ALIASES[normalized];
+ if (alias !== undefined) {
+ return alias;
+ }
+ const withScheme = normalized.startsWith('https://') ? normalized : `https://${normalized}`;
+ const host = Object.values(KEY_HOSTS).find((allowed) => allowed === withScheme);
+ if (host === undefined) {
+ throw new Error('Unknown API host. Edit the connection and enter jsm, us or eu as the API host.');
+ }
+ return host;
+}
+
+function normalizeSiteUrl(raw: string): string {
+ const trimmed = raw.trim().replace(/\/+$/, '');
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
+ let parsed: URL;
+ try {
+ parsed = new URL(withScheme);
+ } catch {
+ throw new Error(`"${raw}" is not a valid Atlassian site URL. Use the form https://your-company.atlassian.net.`);
+ }
+ const host = parsed.hostname.toLowerCase();
+ const allowedHost = ALLOWED_SITE_SUFFIXES.some((suffix) => host.endsWith(suffix) && host.length > suffix.length);
+ if (parsed.protocol !== 'https:' || !allowedHost || parsed.port !== '' || parsed.username !== '' || parsed.password !== '') {
+ throw new Error(`"${raw}" is not an Atlassian Cloud site. Use the form https://your-company.atlassian.net.`);
+ }
+ return `https://${host}`;
+}
+
+async function resolveCloudId(props: AccountAuthProps): Promise<string> {
+ const configured = props.cloudId?.trim();
+ if (configured !== undefined && configured.length > 0) {
+ if (!CLOUD_ID_PATTERN.test(configured)) {
+ throw new Error('The Cloud ID can only contain letters, numbers and dashes. Leave it empty to look it up automatically.');
+ }
+ return configured;
+ }
+ const siteUrl = normalizeSiteUrl(props.siteUrl);
+ let body: { cloudId?: unknown };
+ try {
+ const response = await httpClient.sendRequest<{ cloudId?: unknown }>({
+ method: HttpMethod.GET,
+ url: `${siteUrl}/_edge/tenant_info`,
+ followRedirects: false,
+ timeout: REQUEST_TIMEOUT_MS,
+ });
+ body = response.body;
+ } catch (error) {
+ throw new Error(`Could not look up the Cloud ID for ${siteUrl}: ${describeError(error)}. Check the site URL, or enter the Cloud ID.`);
+ }
+ const cloudId = typeof body?.cloudId === 'string' ? body.cloudId : '';
+ if (!CLOUD_ID_PATTERN.test(cloudId)) {
+ throw new Error(`${siteUrl} did not return a Cloud ID. Check the site URL, or enter the Cloud ID.`);
+ }
+ return cloudId;
+}
+
+async function fillCloudId<P extends AccountAuthProps>(props: P): Promise<P & { cloudId: string }> {
+ const cloudId = await resolveCloudId(props);
+ return { ...props, cloudId };
+}
+
+function accountBaseUrl(cloudId: string): string {
+ return `${JSM_ACCOUNT_API_URL}/${encodeURIComponent(cloudId)}/v1`;
+}
+
+function keyBaseUrl(props: KeyAuthProps): string {
+ return `${resolveKeyHost(props.host)}/v2`;
+}
+
+function authHeaders(auth: JsmAuthValue): Record<string, string> {
+ if (isKeyConnection(auth)) {
+ return { Authorization: `GenieKey ${keyProps(auth).apiKey}` };
+ }
+ const token = Buffer.from(`${auth.props.email.trim()}:${auth.props.apiToken}`).toString('base64');
+ return { Authorization: `Basic ${token}` };
+}
+
+async function routeFor(auth: JsmAuthValue): Promise<Route> {
+ if (isKeyConnection(auth)) {
+ const route: KeyRoute = { kind: 'key', baseUrl: keyBaseUrl(keyProps(auth)), headers: authHeaders(auth) };
+ return route;
+ }
+ const cloudId = await resolveCloudId(auth.props);
+ return {
+ kind: 'account',
+ baseUrl: accountBaseUrl(cloudId),
+ siteUrl: normalizeSiteUrl(auth.props.siteUrl),
+ headers: authHeaders(auth),
+ };
+}
+
+async function requireAccountRoute({ auth, feature }: { auth: JsmAuthValue; feature: string }): Promise<AccountRoute> {
+ if (isKeyConnection(auth)) {
+ throw new Error(
+ `${feature} needs an Atlassian account connection. Alert API keys can only create, acknowledge and close alerts or add notes. Create an "Atlassian Account" connection (site URL, email and API token) and use it for this step.`,
+ );
+ }
+ const route = await routeFor(auth);
+ if (route.kind !== 'account') {
+ throw new Error(`${feature} needs an Atlassian account connection.`);
+ }
+ return route;
+}
+
+async function send<T>({ route, method, path, queryParams, body, timeout }: SendParams): Promise<T> {
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${route.baseUrl}${path}`,
+ headers: { ...route.headers, Accept: 'application/json' },
+ queryParams,
+ body,
+ followRedirects: false,
+ timeout: timeout ?? REQUEST_TIMEOUT_MS,
+ });
+ return response.body;
+ } catch (error) {
+ throw new Error(describeError(error));
+ }
+}
+
+async function sendToSite<T>({ route, path, queryParams }: SiteParams): Promise<T> {
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method: HttpMethod.GET,
+ url: `${route.siteUrl}${path}`,
+ headers: { ...route.headers, Accept: 'application/json' },
+ queryParams,
+ followRedirects: false,
+ timeout: REQUEST_TIMEOUT_MS,
+ });
+ return response.body;
+ } catch (error) {
+ throw new Error(describeError(error));
+ }
+}
+
+async function resolveAlertId({ route, alert, identifierType }: AlertLookup): Promise<string> {
+ const value = requireIdentifier(alert);
+ if (identifierType !== 'alias') {
+ return value;
+ }
+ const found = await send<ApiAlert>({
+ route,
+ method: HttpMethod.GET,
+ path: '/alerts/alias',
+ queryParams: { alias: value },
+ });
+ if (typeof found.id !== 'string' || found.id.length === 0) {
+ throw new Error(`No alert was found with the alias "${value}".`);
+ }
+ return found.id;
+}
+
+async function getAlert({ route, alert, identifierType }: AlertLookup): Promise<ApiAlert> {
+ const value = requireIdentifier(alert);
+ if (identifierType === 'alias') {
+ return send<ApiAlert>({ route, method: HttpMethod.GET, path: '/alerts/alias', queryParams: { alias: value } });
+ }
+ return send<ApiAlert>({ route, method: HttpMethod.GET, path: `/alerts/${encodeURIComponent(value)}` });
+}
+
+async function runAsync({ route, method, path, queryParams, body, verb }: AsyncParams): Promise<RequestResult> {
+ const accepted = await send<ApiAsyncResponse>({ route, method, path, queryParams, body });
+ const requestId = accepted?.requestId;
+ if (typeof requestId !== 'string' || requestId.length === 0) {
+ throw new Error(`JSM Operations accepted the request to ${verb} but did not return a request ID.`);
+ }
+ const result = await awaitRequest({ route, requestId });
+ if (result.processed && result.success === false) {
+ throw new Error(requestFailureMessage({ verb, status: result.status }));
+ }
+ return result;
+}
+
+async function awaitRequest({ route, requestId }: { route: Route; requestId: string }): Promise<RequestResult> {
+ for (const delay of POLL_DELAYS_MS) {
+ await sleep(delay);
+ const status = await fetchRequestStatus({ route, requestId });
+ if (status !== null) {
+ return {
+ request_id: requestId,
+ processed: true,
+ success: status.isSuccess ?? status.success ?? null,
+ action: status.action ?? null,
+ status: status.status ?? null,
+ alert_id: nonEmpty(status.alertId),
+ alias: nonEmpty(status.alias),
+ processed_at: status.processedAt ?? null,
+ };
+ }
+ }
+ return {
+ request_id: requestId,
+ processed: false,
+ success: null,
+ action: null,
+ status: 'Still processing. Look the request up later with its request ID.',
+ alert_id: null,
+ alias: null,
+ processed_at: null,
+ };
+}
+
+async function sendAlertAction({ auth, alert, identifierType, action, note, user, source }: AlertActionParams): Promise<AlertActionResult> {
+ const route = await routeFor(auth);
+ const verb = action === 'acknowledge' ? 'acknowledge the alert' : 'close the alert';
+ const cleanNote = nonEmpty(note);
+ if (route.kind === 'key') {
+ const result = await runAsync({
+ route,
+ method: HttpMethod.POST,
+ path: `/alerts/${encodeURIComponent(requireIdentifier(alert))}/${action}`,
+ queryParams: { identifierType },
+ body: compact({ note: cleanNote, user: nonEmpty(user), source: nonEmpty(source) }),
+ verb,
+ });
+ return { ...result, note_added: cleanNote === null ? null : result.success, note_error: null };
+ }
+ const alertId = await resolveAlertId({ route, alert, identifierType });
+ const result = await runAsync({
+ route,
+ method: HttpMethod.POST,
+ path: `/alerts/${encodeURIComponent(alertId)}/${action}`,
+ verb,
+ });
+ const withId = { ...result, alert_id: result.alert_id ?? alertId };
+ if (cleanNote === null) {
+ return { ...withId, note_added: null, note_error: null };
+ }
+ try {
+ await send<ApiNote>({
+ route,
+ method: HttpMethod.POST,
+ path: `/alerts/${encodeURIComponent(alertId)}/notes`,
+ body: { note: cleanNote },
+ });
+ return { ...withId, note_added: true, note_error: null };
+ } catch (error) {
+ return { ...withId, note_added: false, note_error: `The alert was updated, but the note could not be added: ${describeError(error)}` };
+ }
+}
+
+async function runAccountAlertRequest({ auth, feature, alert, identifierType, method, suffix, body, verb }: AccountAlertRequestParams): Promise<RequestResult> {
+ const route = await requireAccountRoute({ auth, feature });
+ const alertId = await resolveAlertId({ route, alert, identifierType });
+ const result = await runAsync({
+ route,
+ method,
+ path: `/alerts/${encodeURIComponent(alertId)}/${suffix}`,
+ body,
+ verb,
+ });
+ return { ...result, alert_id: result.alert_id ?? alertId };
+}
+
+async function changeTags({ auth, alert, identifierType, tags, operation }: ChangeTagsParams): Promise<RequestResult> {
+ const list = parseStringList(tags);
+ if (list.length === 0) {
+ throw new Error('Enter at least one tag.');
+ }
+ return runAccountAlertRequest({
+ auth,
+ feature: operation === 'add' ? 'Add Tags to Alert' : 'Remove Tags from Alert',
+ alert,
+ identifierType,
+ method: operation === 'add' ? HttpMethod.POST : HttpMethod.DELETE,
+ suffix: 'tags',
+ body: { tags: list },
+ verb: operation === 'add' ? 'add the tags' : 'remove the tags',
+ });
+}
+
+async function addNote({ auth, alert, identifierType, note, user, source }: AddNoteParams): Promise<NoteResult> {
+ const route = await routeFor(auth);
+ const text = nonEmpty(note);
+ if (text === null) {
+ throw new Error('Enter the note text.');
+ }
+ if (route.kind === 'key') {
+ const result = await runAsync({
+ route,
+ method: HttpMethod.POST,
+ path: `/alerts/${encodeURIComponent(requireIdentifier(alert))}/notes`,
+ queryParams: { identifierType },
+ body: compact({ note: text, user: nonEmpty(user), source: nonEmpty(source) }),
+ verb: 'add the note',
+ });
+ return { ...result, note_id: null, note: text };
+ }
+ const alertId = await resolveAlertId({ route, alert, identifierType });
+ const created = await send<ApiNote>({
+ route,
+ method: HttpMethod.POST,
+ path: `/alerts/${encodeURIComponent(alertId)}/notes`,
+ body: { note: text },
+ });
+ return {
+ request_id: null,
+ processed: true,
+ success: true,
+ action: 'AddNote',
+ status: 'Note added',
+ alert_id: alertId,
+ alias: identifierType === 'alias' ? requireIdentifier(alert) : null,
+ processed_at: created?.createdAt ?? null,
+ note_id: nonEmpty(created?.id),
+ note: created?.note ?? text,
+ };
+}
+
+function toAlertOutput(alert: ApiAlert): AlertOutput {
+ return {
+ id: nonEmpty(alert.id),
+ tiny_id: nonEmpty(alert.tinyId),
+ message: alert.message ?? null,
+ description: alert.description ?? null,
+ status: alert.status ?? null,
+ priority: alert.priority ?? null,
+ alias: nonEmpty(alert.alias),
+ entity: nonEmpty(alert.entity),
+ source: nonEmpty(alert.source),
+ owner: nonEmpty(alert.owner),
+ acknowledged: typeof alert.acknowledged === 'boolean' ? alert.acknowledged : null,
+ seen: typeof alert.seen === 'boolean' ? alert.seen : null,
+ snoozed: typeof alert.snoozed === 'boolean' ? alert.snoozed : null,
+ snoozed_until: alert.snoozedUntil ?? null,
+ count: typeof alert.count === 'number' ? alert.count : null,
+ tags: joinList(alert.tags),
+ actions: joinList(alert.actions),
+ responders: joinList((alert.responders ?? []).map((responder) => `${responder.type}:${responder.id ?? responder.name ?? responder.username ?? ''}`)),
+ extra_properties: alert.extraProperties ?? {},
+ integration_name: nonEmpty(alert.integrationName),
+ integration_type: nonEmpty(alert.integrationType),
+ created_at: alert.createdAt ?? null,
+ updated_at: alert.updatedAt ?? null,
+ last_occurred_at: alert.lastOccurredAt ?? alert.lastOccuredAt ?? null,
+ ack_time: alert.ackTime ?? null,
+ close_time: alert.closeTime ?? null,
+ };
+}
+
+function parseStringList(value: unknown): string[] {
+ const list = typeof value === 'string' ? parseJsonList(value) : value;
+ if (!Array.isArray(list)) {
+ return [];
+ }
+ return list
+ .map((item) => (typeof item === 'string' || typeof item === 'number' ? String(item).trim() : ''))
+ .filter((item) => item.length > 0);
+}
+
+function requestFailureMessage({ verb, status }: { verb: string; status: string | null | undefined }): string {
+ const reason = (status ?? 'the request failed').replace(/\.+$/, '');
+ const planHint = /plan does not support/i.test(reason)
+ ? ' This action is not included in your Jira Service Management plan (for example, the Free plan). Upgrade the plan or skip this step.'
+ : '';
+ return `JSM Operations could not ${verb}: ${reason}.${planHint}`;
+}
+
+function describeError(error: unknown): string {
+ if (!(error instanceof HttpError)) {
+ return error instanceof Error ? error.message : String(error);
+ }
+ const status = error.response.status;
+ const detail = readErrorMessage(error.response.body);
+ const base = `JSM Operations error (HTTP ${status})${detail.length > 0 ? `: ${detail}` : ''}`;
+ const hint = STATUS_HINTS[status];
+ return hint === undefined ? base : `${base}. ${hint}`;
+}
+
+async function validateAccount(props: AccountAuthProps): Promise<ValidationResult> {
+ try {
+ const route = await routeFor({ type: AppConnectionType.CUSTOM_AUTH, props });
+ await send<unknown>({ route, method: HttpMethod.GET, path: '/alerts', queryParams: { size: '1' } });
+ return { valid: true };
+ } catch (error) {
+ return { valid: false, error: describeError(error) };
+ }
+}
+
+async function validateKey({ username, password }: { username: string; password: string }): Promise<ValidationResult> {
+ let route: Route;
+ try {
+ route = await routeFor({ type: AppConnectionType.BASIC_AUTH, username, password });
+ } catch (error) {
+ return { valid: false, error: describeError(error) };
+ }
+ try {
+ await httpClient.sendRequest({
+ method: HttpMethod.GET,
+ url: `${route.baseUrl}/alerts/requests/${VALIDATION_REQUEST_ID}`,
+ headers: route.headers,
+ followRedirects: false,
+ timeout: REQUEST_TIMEOUT_MS,
+ });
+ return { valid: true };
+ } catch (error) {
+ const status = error instanceof HttpError ? error.response.status : undefined;
+ if (status === 404 || status === 422 || status === 400) {
+ return { valid: true };
+ }
+ return { valid: false, error: describeError(error) };
+ }
+}
+
+async function fetchRequestStatus({ route, requestId }: { route: Route; requestId: string }): Promise<ApiRequestStatus | null> {
+ let body: WrappedRequestStatus;
+ try {
+ const response = await httpClient.sendRequest<WrappedRequestStatus>({
+ method: HttpMethod.GET,
+ url: `${route.baseUrl}/alerts/requests/${encodeURIComponent(requestId)}`,
+ headers: { ...route.headers, Accept: 'application/json' },
+ followRedirects: false,
+ timeout: POLL_TIMEOUT_MS,
+ });
+ body = response.body;
+ } catch (error) {
+ if (error instanceof HttpError && error.response.status === 404) {
+ return null;
+ }
+ throw new Error(describeError(error));
+ }
+ const status = body?.data ?? body;
+ if (status === undefined || status === null || (status.isSuccess === undefined && status.success === undefined)) {
+ return null;
+ }
+ return status;
+}
+
+function readErrorMessage(body: unknown): string {
+ const parsed = typeof body === 'string' ? parseJson(body) : body;
+ if (typeof parsed === 'string') {
+ return parsed.length > 300 ? `${parsed.slice(0, 300)}…` : parsed;
+ }
+ if (parsed === null || typeof parsed !== 'object') {
+ return '';
+ }
+ const parts: string[] = [];
+ if ('message' in parsed && typeof parsed.message === 'string') {
+ parts.push(parsed.message);
+ }
+ if ('errors' in parsed) {
+ parts.push(...describeErrorList(parsed.errors));
+ }
+ if ('errorMessages' in parsed && Array.isArray(parsed.errorMessages)) {
+ parts.push(...parsed.errorMessages.filter((item): item is string => typeof item === 'string'));
+ }
+ return parts.join('; ');
+}
+
+function describeErrorList(errors: unknown): string[] {
+ if (Array.isArray(errors)) {
+ return errors.flatMap((item) => {
+ if (typeof item === 'string') {
+ return [item];
+ }
+ if (item !== null && typeof item === 'object' && 'title' in item && typeof item.title === 'string') {
+ return [item.title];
+ }
+ return [];
+ });
+ }
+ if (errors !== null && typeof errors === 'object') {
+ return Object.entries(errors).map(([field, message]) => `${field}: ${String(message)}`);
+ }
+ return [];
+}
+
+function parseJson(text: string): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+}
+
+function parseJsonList(text: string): unknown {
+ const trimmed = text.trim();
+ if (trimmed.startsWith('[')) {
+ return parseJson(trimmed);
+ }
+ return trimmed.split(',');
+}
+
+function requireIdentifier(alert: string | undefined): string {
+ const value = alert?.trim() ?? '';
+ if (value.length === 0) {
+ throw new Error('Enter the alert ID or alias.');
+ }
+ return value;
+}
+
+function nonEmpty(value: string | undefined | null): string | null {
+ if (typeof value !== 'string') {
+ return null;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function joinList(values: string[] | undefined): string | null {
+ if (!Array.isArray(values) || values.length === 0) {
+ return null;
+ }
+ return values.join(', ');
+}
+
+function compact(values: Record<string, string | null>): Record<string, string> {
+ return Object.fromEntries(
+ Object.entries(values).flatMap(([key, value]) => (value === null ? [] : [[key, value]])),
+ );
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+const KEY_HOST_ALIASES: Record<string, string> = {
+ jsm: KEY_HOSTS.jsm,
+ us: KEY_HOSTS.opsgenieUs,
+ eu: KEY_HOSTS.opsgenieEu,
+};
+const ALLOWED_SITE_SUFFIXES = ['.atlassian.net', '.jira.com'];
+const CLOUD_ID_PATTERN = /^[A-Za-z0-9-]{8,100}$/;
+const VALIDATION_REQUEST_ID = '00000000-0000-0000-0000-000000000000';
+const STATUS_HINTS: Record<number, string> = {
+ 401: 'Check the connection credentials: the email and API token, or the alert API key.',
+ 403: 'This account or API key is not allowed to do this. Check its JSM Operations permissions.',
+ 404: 'Check that the alert, team or schedule exists and that the connection can see it.',
+ 429: 'JSM Operations is rate-limiting requests. Wait a moment and run the step again.',
+};
+
+type SendParams = {
+ route: Route;
+ method: HttpMethod;
+ path: string;
+ queryParams?: Record<string, string>;
+ body?: unknown;
+ timeout?: number;
+};
+
+type SiteParams = {
+ route: AccountRoute;
+ path: string;
+ queryParams?: Record<string, string>;
+};
+
+type AlertLookup = {
+ route: Route;
+ alert: string | undefined;
+ identifierType: AlertIdentifierType;
+};
+
+type AsyncParams = {
+ route: Route;
+ method: HttpMethod;
+ path: string;
+ queryParams?: Record<string, string>;
+ body?: unknown;
+ verb: string;
+};
+
+type AlertActionParams = {
+ auth: JsmAuthValue;
+ alert: string | undefined;
+ identifierType: AlertIdentifierType;
+ action: 'acknowledge' | 'close';
+ note?: string;
+ user?: string;
+ source?: string;
+};
+
+type AccountAlertRequestParams = {
+ auth: JsmAuthValue;
+ feature: string;
+ alert: string | undefined;
+ identifierType: AlertIdentifierType;
+ method: HttpMethod;
+ suffix: string;
+ body?: unknown;
+ verb: string;
+};
+
+type ChangeTagsParams = {
+ auth: JsmAuthValue;
+ alert: string | undefined;
+ identifierType: AlertIdentifierType;
+ tags: unknown;
+ operation: 'add' | 'remove';
+};
+
+type AddNoteParams = {
+ auth: JsmAuthValue;
+ alert: string | undefined;
+ identifierType: AlertIdentifierType;
+ note: string | undefined;
+ user?: string;
+ source?: string;
+};
+
+type WrappedRequestStatus = ApiRequestStatus & { data?: ApiRequestStatus };
+
+type ValidationResult = { valid: true } | { valid: false; error: string };
+
+export type NoteResult = RequestResult & {
+ note_id: string | null;
+ note: string | null;
+};
diff --git a/packages/pieces/community/jsm-operations/src/lib/common/props.ts b/packages/pieces/community/jsm-operations/src/lib/common/props.ts
new file mode 100644
index 00000000000..709735d9fbb
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/common/props.ts
@@ -0,0 +1,343 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { DropdownState, Property } from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from './client';
+import {
+ AccountRoute,
+ ApiEscalation,
+ ApiJiraUser,
+ ApiPage,
+ ApiSchedule,
+ ApiTeamList,
+ JsmAuthValue,
+ ResponderType,
+} from './types';
+
+export const jsmOpsProps = {
+ alert,
+ identifierType,
+ priority,
+ teams,
+ team,
+ schedule,
+ schedules,
+ escalation,
+ escalations,
+ user,
+ users,
+ responderType,
+ responder,
+};
+
+export const jsmOpsOptions = {
+ listTeams,
+ listSchedules,
+ listEscalations,
+ listUsers,
+ listResponders,
+};
+
+export const PRIORITY_OPTIONS = [
+ { label: 'P1 - Critical', value: 'P1' },
+ { label: 'P2 - High', value: 'P2' },
+ { label: 'P3 - Moderate', value: 'P3' },
+ { label: 'P4 - Low', value: 'P4' },
+ { label: 'P5 - Informational', value: 'P5' },
+];
+
+function alert() {
+ return Property.ShortText({
+ displayName: 'Alert ID or Alias',
+ description: 'The alert ID, or its alias if you pick Alias below.',
+ placeholder: 'e.g. 70413a06-38d6-4c85-92b8-5ebc900d42e2',
+ required: true,
+ });
+}
+
+function identifierType() {
+ return Property.StaticDropdown({
+ displayName: 'Identify Alert By',
+ description: 'Whether the value above is the alert ID or its alias.',
+ required: true,
+ defaultValue: 'id',
+ options: {
+ options: [
+ { label: 'Alert ID', value: 'id' },
+ { label: 'Alias', value: 'alias' },
+ ],
+ },
+ });
+}
+
+function priority({ required, defaultValue }: { required: boolean; defaultValue?: string }) {
+ return Property.StaticDropdown({
+ displayName: 'Priority',
+ description: 'P1 is the most urgent, P5 the least.',
+ required,
+ defaultValue,
+ options: { options: PRIORITY_OPTIONS },
+ });
+}
+
+function teams({ displayName, description }: LabelParams) {
+ return Property.MultiSelectDropdown({
+ auth: jsmOpsAuth,
+ displayName,
+ description,
+ required: false,
+ refreshers: [],
+ options: async ({ auth }) => withAccount({ auth, load: (route) => listTeams({ route }) }),
+ });
+}
+
+function team({ displayName, description, required }: LabelParams & { required: boolean }) {
+ return Property.Dropdown({
+ auth: jsmOpsAuth,
+ displayName,
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) => withAccount({ auth, load: (route) => listTeams({ route }) }),
+ });
+}
+
+function schedule({ displayName, description }: LabelParams) {
+ return Property.Dropdown({
+ auth: jsmOpsAuth,
+ displayName,
+ description,
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) => withAccount({ auth, load: (route) => listSchedules({ route }) }),
+ });
+}
+
+function schedules({ displayName, description }: LabelParams) {
+ return Property.MultiSelectDropdown({
+ auth: jsmOpsAuth,
+ displayName,
+ description,
+ required: false,
+ refreshers: [],
+ options: async ({ auth }) => withAccount({ auth, load: (route) => listSchedules({ route }) }),
+ });
+}
+
+function escalation({ displayName, description }: LabelParams) {
+ return Property.Dropdown({
+ auth: jsmOpsAuth,
+ displayName,
+ description,
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) => withAccount({ auth, load: (route) => listEscalations({ route }) }),
+ });
+}
+
+function escalations({ displayName, description }: LabelParams) {
+ return Property.MultiSelectDropdown({
+ auth: jsmOpsAuth,
+ displayName,
+ description,
+ required: false,
+ refreshers: [],
+ options: async ({ auth }) => withAccount({ auth, load: (route) => listEscalations({ route }) }),
+ });
+}
+
+function user({ displayName, description }: LabelParams) {
+ return Property.Dropdown({
+ auth: jsmOpsAuth,
+ displayName,
+ description,
+ required: true,
+ refreshers: [],
+ refreshOnSearch: true,
+ options: async ({ auth }, { searchValue }) =>
+ withAccount({ auth, load: (route) => listUsers({ route, search: searchValue }) }),
+ });
+}
+
+function users({ displayName, description }: LabelParams) {
+ return Property.MultiSelectDropdown({
+ auth: jsmOpsAuth,
+ displayName,
+ description,
+ required: false,
+ refreshers: [],
+ refreshOnSearch: true,
+ options: async ({ auth }, { searchValue }) =>
+ withAccount({ auth, load: (route) => listUsers({ route, search: searchValue }) }),
+ });
+}
+
+function responderType() {
+ return Property.StaticDropdown({
+ displayName: 'Responder Type',
+ description: 'What kind of responder to add.',
+ required: true,
+ defaultValue: 'team',
+ options: {
+ options: [
+ { label: 'Team', value: 'team' },
+ { label: 'User', value: 'user' },
+ { label: 'Schedule', value: 'schedule' },
+ { label: 'Escalation', value: 'escalation' },
+ ],
+ },
+ });
+}
+
+function responder() {
+ return Property.Dropdown({
+ auth: jsmOpsAuth,
+ displayName: 'Responder',
+ description: 'The team, user, schedule or escalation to add.',
+ required: true,
+ refreshers: ['responderType'],
+ refreshOnSearch: true,
+ options: async ({ auth, responderType }, { searchValue }) => {
+ if (!isResponderType(responderType)) {
+ return { disabled: true, options: [], placeholder: 'Pick a responder type first.' };
+ }
+ return withAccount({ auth, load: (route) => listResponders({ route, type: responderType, search: searchValue }) });
+ },
+ });
+}
+
+async function listTeams({ route }: { route: AccountRoute }): Promise<Option[]> {
+ const body = await jsmOps.send<ApiTeamList>({ route, method: HttpMethod.GET, path: '/teams' });
+ const teams = Array.isArray(body) ? body : body.platformTeams ?? [];
+ return teams.flatMap((item) =>
+ typeof item.teamId === 'string' ? [{ label: item.teamName ?? item.teamId, value: item.teamId }] : [],
+ );
+}
+
+async function listSchedules({ route }: { route: AccountRoute }): Promise<Option[]> {
+ const found: ApiSchedule[] = [];
+ for (let page = 0; page < MAX_PAGES; page++) {
+ const body = await jsmOps.send<ApiPage<ApiSchedule>>({
+ route,
+ method: HttpMethod.GET,
+ path: '/schedules',
+ queryParams: { size: String(SCHEDULE_PAGE_SIZE), offset: String(page * SCHEDULE_PAGE_SIZE) },
+ });
+ const values = body.values ?? [];
+ found.push(...values);
+ if (values.length < SCHEDULE_PAGE_SIZE) {
+ break;
+ }
+ }
+ return found.flatMap((item) =>
+ typeof item.id === 'string'
+ ? [{ label: item.timezone ? `${item.name ?? item.id} (${item.timezone})` : item.name ?? item.id, value: item.id }]
+ : [],
+ );
+}
+
+async function listEscalations({ route }: { route: AccountRoute }): Promise<Option[]> {
+ const teamOptions = await listTeams({ route });
+ const found: Option[] = [];
+ for (let start = 0; start < teamOptions.length; start += ESCALATION_TEAM_BATCH) {
+ const batch = teamOptions.slice(start, start + ESCALATION_TEAM_BATCH);
+ const perTeam = await Promise.all(batch.map((teamOption) => listTeamEscalations({ route, team: teamOption })));
+ found.push(...perTeam.flat());
+ }
+ return found;
+}
+
+async function listTeamEscalations({ route, team }: { route: AccountRoute; team: Option }): Promise<Option[]> {
+ const found: Option[] = [];
+ for (let page = 0; page < MAX_PAGES; page++) {
+ const body = await jsmOps.send<ApiPage<ApiEscalation>>({
+ route,
+ method: HttpMethod.GET,
+ path: `/teams/${encodeURIComponent(team.value)}/escalations`,
+ queryParams: { size: String(ESCALATION_PAGE_SIZE), offset: String(page * ESCALATION_PAGE_SIZE) },
+ });
+ const values = body.values ?? [];
+ for (const item of values) {
+ if (typeof item.id === 'string') {
+ found.push({ label: `${item.name ?? item.id} (${team.label})`, value: item.id });
+ }
+ }
+ if (values.length < ESCALATION_PAGE_SIZE) {
+ break;
+ }
+ }
+ return found;
+}
+
+async function listUsers({ route, search }: { route: AccountRoute; search?: string }): Promise<Option[]> {
+ const query = search?.trim() ?? '';
+ const found =
+ query.length > 0
+ ? await jsmOps.sendToSite<ApiJiraUser[]>({
+ route,
+ path: '/rest/api/3/user/search',
+ queryParams: { query, maxResults: '50' },
+ })
+ : await jsmOps.sendToSite<ApiJiraUser[]>({
+ route,
+ path: '/rest/api/3/users/search',
+ queryParams: { maxResults: '100' },
+ });
+ return (Array.isArray(found) ? found : []).flatMap((item) => {
+ if (typeof item.accountId !== 'string' || item.accountType !== 'atlassian' || item.active === false) {
+ return [];
+ }
+ const name = item.displayName ?? item.accountId;
+ return [{ label: item.emailAddress ? `${name} (${item.emailAddress})` : name, value: item.accountId }];
+ });
+}
+
+async function listResponders({ route, type, search }: { route: AccountRoute; type: ResponderType; search?: string }): Promise<Option[]> {
+ if (type === 'team') {
+ return listTeams({ route });
+ }
+ if (type === 'schedule') {
+ return listSchedules({ route });
+ }
+ if (type === 'escalation') {
+ return listEscalations({ route });
+ }
+ return listUsers({ route, search });
+}
+
+async function withAccount({ auth, load }: WithAccountParams): Promise<DropdownState<string>> {
+ if (auth === undefined) {
+ return { disabled: true, options: [], placeholder: 'Connect your account first.' };
+ }
+ if (jsmOps.isKeyConnection(auth)) {
+ return { disabled: true, options: [], placeholder: 'Needs an Atlassian Account connection, not an API key.' };
+ }
+ try {
+ const route = await jsmOps.requireAccountRoute({ auth, feature: 'This list' });
+ const options = await load(route);
+ return {
+ disabled: false,
+ options,
+ placeholder: options.length === 0 ? 'Nothing found on this site.' : undefined,
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: `Could not load the list: ${jsmOps.describeError(error)}` };
+ }
+}
+
+function isResponderType(value: unknown): value is ResponderType {
+ return value === 'team' || value === 'user' || value === 'schedule' || value === 'escalation';
+}
+
+const MAX_PAGES = 5;
+const SCHEDULE_PAGE_SIZE = 50;
+const ESCALATION_PAGE_SIZE = 100;
+const ESCALATION_TEAM_BATCH = 10;
+
+type Option = { label: string; value: string };
+
+type LabelParams = { displayName: string; description: string };
+
+type WithAccountParams = {
+ auth: JsmAuthValue | undefined;
+ load: (route: AccountRoute) => Promise<Option[]>;
+};
diff --git a/packages/pieces/community/jsm-operations/src/lib/common/types.ts b/packages/pieces/community/jsm-operations/src/lib/common/types.ts
new file mode 100644
index 00000000000..dfe96bbba14
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/common/types.ts
@@ -0,0 +1,208 @@
+import { AppConnectionType } from '@activepieces/pieces-framework';
+
+export type AccountAuthProps = {
+ siteUrl: string;
+ email: string;
+ apiToken: string;
+ cloudId?: string;
+};
+
+export type KeyAuthProps = {
+ host: string;
+ apiKey: string;
+};
+
+export type AccountConnection = {
+ type: AppConnectionType.CUSTOM_AUTH;
+ props: AccountAuthProps;
+};
+
+export type KeyConnection = {
+ type: AppConnectionType.BASIC_AUTH;
+ username: string;
+ password: string;
+};
+
+export type JsmAuthValue = AccountConnection | KeyConnection;
+
+export type AccountRoute = {
+ kind: 'account';
+ baseUrl: string;
+ siteUrl: string;
+ headers: Record<string, string>;
+};
+
+export type KeyRoute = {
+ kind: 'key';
+ baseUrl: string;
+ headers: Record<string, string>;
+};
+
+export type Route = AccountRoute | KeyRoute;
+
+export type AlertIdentifierType = 'id' | 'alias';
+
+export type ResponderType = 'team' | 'user' | 'escalation' | 'schedule';
+
+export type ApiResponder = {
+ id?: string;
+ name?: string;
+ username?: string;
+ type: string;
+};
+
+export type ApiAlert = {
+ id?: string;
+ tinyId?: string;
+ createdAt?: string;
+ updatedAt?: string;
+ message?: string;
+ entity?: string;
+ source?: string;
+ status?: string;
+ alias?: string;
+ tags?: string[];
+ extraProperties?: Record<string, string>;
+ description?: string;
+ acknowledged?: boolean;
+ ackTime?: string;
+ closeTime?: string;
+ count?: number;
+ owner?: string;
+ snoozed?: boolean;
+ snoozedUntil?: string;
+ lastOccuredAt?: string;
+ lastOccurredAt?: string;
+ integrationType?: string;
+ integrationName?: string;
+ priority?: string;
+ responders?: ApiResponder[];
+ actions?: string[];
+ seen?: boolean;
+};
+
+export type ApiAlertList = {
+ values?: ApiAlert[];
+ count?: number;
+};
+
+export type ApiAsyncResponse = {
+ result?: string;
+ requestId?: string;
+ took?: number;
+};
+
+export type ApiRequestStatus = {
+ success?: boolean;
+ isSuccess?: boolean;
+ action?: string;
+ processedAt?: string;
+ integrationId?: string;
+ status?: string;
+ alertId?: string;
+ alias?: string;
+};
+
+export type ApiNote = {
+ id?: string;
+ createdAt?: string;
+ updatedAt?: string;
+ note?: string;
+ owner?: string;
+};
+
+export type ApiTeam = { teamId?: string; teamName?: string };
+
+export type ApiTeamList = ApiTeam[] | { platformTeams?: ApiTeam[] };
+
+export type ApiSchedule = {
+ id?: string;
+ name?: string;
+ timezone?: string;
+ enabled?: boolean;
+};
+
+export type ApiEscalation = {
+ id?: string;
+ name?: string;
+};
+
+export type ApiPage<T> = {
+ values?: T[];
+ links?: { next?: string };
+};
+
+export type ApiJiraUser = {
+ accountId?: string;
+ accountType?: string;
+ displayName?: string;
+ emailAddress?: string;
+ active?: boolean;
+};
+
+export type ApiOnCallParticipant = {
+ id?: string;
+ type?: string;
+ name?: string;
+ forwardedFrom?: { id?: string; type?: string };
+ onCallParticipants?: ApiOnCallParticipant[];
+};
+
+export type ApiOnCallResponse = {
+ onCallParticipants?: ApiOnCallParticipant[];
+ onCallUsers?: string[];
+};
+
+export type AlertOutput = {
+ id: string | null;
+ tiny_id: string | null;
+ message: string | null;
+ description: string | null;
+ status: string | null;
+ priority: string | null;
+ alias: string | null;
+ entity: string | null;
+ source: string | null;
+ owner: string | null;
+ acknowledged: boolean | null;
+ seen: boolean | null;
+ snoozed: boolean | null;
+ snoozed_until: string | null;
+ count: number | null;
+ tags: string | null;
+ actions: string | null;
+ responders: string | null;
+ extra_properties: Record<string, string>;
+ integration_name: string | null;
+ integration_type: string | null;
+ created_at: string | null;
+ updated_at: string | null;
+ last_occurred_at: string | null;
+ ack_time: string | null;
+ close_time: string | null;
+};
+
+export type RequestResult = {
+ request_id: string | null;
+ processed: boolean;
+ success: boolean | null;
+ action: string | null;
+ status: string | null;
+ alert_id: string | null;
+ alias: string | null;
+ processed_at: string | null;
+};
+
+export type AlertActionResult = RequestResult & {
+ note_added: boolean | null;
+ note_error: string | null;
+};
+
+export type OnCallParticipantOutput = {
+ id: string | null;
+ type: string | null;
+ name: string | null;
+ parent_id: string | null;
+ parent_type: string | null;
+ forwarded_from_id: string | null;
+};
diff --git a/packages/pieces/community/jsm-operations/src/lib/output-schemas.ts b/packages/pieces/community/jsm-operations/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..2f143a93077
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/output-schemas.ts
@@ -0,0 +1,120 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+export const alertOutputSchema: OutputSchema = {
+ fields: alertFields(),
+};
+
+export const findAlertsOutputSchema: OutputSchema = {
+ itemLabel: '{message}',
+ fields: [
+ {
+ key: 'alerts',
+ label: 'Alerts',
+ value: '',
+ labelKey: 'message',
+ description: 'One entry per matching alert, in the chosen sort order.',
+ listItems: alertFields(),
+ },
+ ],
+};
+
+export const requestResultOutputSchema: OutputSchema = {
+ fields: requestResultFields(),
+};
+
+export const alertActionOutputSchema: OutputSchema = {
+ fields: [
+ ...requestResultFields(),
+ { key: 'note_added', label: 'Note Added', format: 'boolean', description: 'Empty when no note was given.' },
+ { key: 'note_error', label: 'Note Error', description: 'Why the note could not be added. The alert itself was still updated.' },
+ ],
+};
+
+export const addNoteOutputSchema: OutputSchema = {
+ fields: [
+ ...requestResultFields(),
+ { key: 'note_id', label: 'Note ID', description: 'Empty on API key connections, which process notes asynchronously.' },
+ { key: 'note', label: 'Note' },
+ ],
+};
+
+export const updateAlertOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'alert_id', label: 'Alert ID' },
+ { key: 'updated_fields', label: 'Updated Fields', description: 'Comma-separated list: message, description, priority.' },
+ { key: 'processed', label: 'All Updates Processed', format: 'boolean' },
+ {
+ key: 'requests',
+ label: 'Update Requests',
+ labelKey: 'field',
+ listItems: [{ key: 'field', label: 'Field' }, ...requestResultFields()],
+ },
+ ],
+};
+
+export const onCallOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'schedule_id', label: 'Schedule ID' },
+ { key: 'date', label: 'Checked At', format: 'datetime', description: 'Empty means the current time.' },
+ { key: 'on_call_user_ids', label: 'On-Call User Account IDs', description: 'Comma-separated Atlassian account IDs.' },
+ { key: 'on_call_user_count', label: 'On-Call User Count', format: 'number' },
+ {
+ key: 'participants',
+ label: 'On-Call Participants',
+ labelKey: 'id',
+ description: 'Everyone on call, including users reached through a team or escalation.',
+ listItems: [
+ { key: 'id', label: 'ID' },
+ { key: 'type', label: 'Type', description: 'user, team, escalation or schedule.' },
+ { key: 'name', label: 'Name' },
+ { key: 'parent_id', label: 'Reached Through ID', description: 'The team or escalation this user is on call for.' },
+ { key: 'parent_type', label: 'Reached Through Type' },
+ { key: 'forwarded_from_id', label: 'Forwarded From User ID' },
+ ],
+ },
+ ],
+};
+
+function alertFields(): OutputSchema['fields'] {
+ return [
+ { key: 'id', label: 'Alert ID' },
+ { key: 'tiny_id', label: 'Tiny ID' },
+ { key: 'message', label: 'Message' },
+ { key: 'description', label: 'Description' },
+ { key: 'status', label: 'Status', description: 'open, acked, snoozed, resolved or closed.' },
+ { key: 'priority', label: 'Priority' },
+ { key: 'alias', label: 'Alias' },
+ { key: 'entity', label: 'Entity' },
+ { key: 'source', label: 'Source' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'acknowledged', label: 'Acknowledged', format: 'boolean' },
+ { key: 'seen', label: 'Seen', format: 'boolean' },
+ { key: 'snoozed', label: 'Snoozed', format: 'boolean' },
+ { key: 'snoozed_until', label: 'Snoozed Until', format: 'datetime' },
+ { key: 'count', label: 'Occurrence Count', format: 'number' },
+ { key: 'tags', label: 'Tags', description: 'Comma-separated.' },
+ { key: 'actions', label: 'Custom Actions', description: 'Comma-separated.' },
+ { key: 'responders', label: 'Responders', description: 'Comma-separated type:id pairs.' },
+ { key: 'extra_properties', label: 'Extra Properties', dynamicKey: true },
+ { key: 'integration_name', label: 'Integration Name' },
+ { key: 'integration_type', label: 'Integration Type' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'last_occurred_at', label: 'Last Occurred At', format: 'datetime' },
+ { key: 'ack_time', label: 'Acknowledged At', format: 'datetime' },
+ { key: 'close_time', label: 'Closed At', format: 'datetime' },
+ ];
+}
+
+function requestResultFields(): OutputSchema['fields'] {
+ return [
+ { key: 'alert_id', label: 'Alert ID' },
+ { key: 'alias', label: 'Alias' },
+ { key: 'processed', label: 'Processed', format: 'boolean', description: 'False when the request was still queued after about 10 seconds.' },
+ { key: 'success', label: 'Succeeded', format: 'boolean' },
+ { key: 'status', label: 'Status Message' },
+ { key: 'action', label: 'Action' },
+ { key: 'request_id', label: 'Request ID' },
+ { key: 'processed_at', label: 'Processed At', format: 'datetime' },
+ ];
+}
diff --git a/packages/pieces/community/jsm-operations/src/lib/triggers/new-alert.ts b/packages/pieces/community/jsm-operations/src/lib/triggers/new-alert.ts
new file mode 100644
index 00000000000..bc3fff655c0
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/src/lib/triggers/new-alert.ts
@@ -0,0 +1,145 @@
+import { DedupeStrategy, HttpMethod, Polling, pollingHelper } from '@activepieces/pieces-common';
+import {
+ AppConnectionValueForAuthProperty,
+ createTrigger,
+ Property,
+ StaticPropsValue,
+ TriggerStrategy,
+} from '@activepieces/pieces-framework';
+import { jsmOpsAuth } from '../auth';
+import { jsmOps } from '../common/client';
+import { AlertOutput, ApiAlert, ApiAlertList } from '../common/types';
+import { alertOutputSchema } from '../output-schemas';
+
+export const newAlertTrigger = createTrigger({
+ auth: jsmOpsAuth,
+ name: 'new_alert',
+ classification: 'READ',
+ displayName: 'New Alert',
+ description: 'Triggers when a new alert is created.',
+ aiMetadata: {
+ description:
+ 'Fires once per new JSM Operations alert, checked every few minutes, optionally limited by an alert search query. Each run carries one alert. Needs an Atlassian account connection.',
+ },
+ props: newAlertProps(),
+ outputSchema: alertOutputSchema,
+ sampleData: sampleAlert(),
+ type: TriggerStrategy.POLLING,
+ async test(context) {
+ return pollingHelper.test(polling(), context);
+ },
+ async onEnable(context) {
+ await jsmOps.requireAccountRoute({ auth: context.auth, feature: 'The New Alert trigger' });
+ await pollingHelper.onEnable(polling(), context);
+ },
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling(), context);
+ },
+ async run(context) {
+ return pollingHelper.poll(polling(), context);
+ },
+});
+
+function newAlertProps() {
+ return {
+ query: Property.ShortText({
+ displayName: 'Only Alerts Matching',
+ description: 'Optional alert search query to filter new alerts.',
+ placeholder: 'e.g. priority: P1 AND tag: production',
+ required: false,
+ }),
+ };
+}
+
+function polling(): Polling<AppConnectionValueForAuthProperty<typeof jsmOpsAuth>, StaticPropsValue<NewAlertProps>> {
+ return {
+ strategy: DedupeStrategy.TIMEBASED,
+ items: async ({ auth, propsValue, lastFetchEpochMS }) => {
+ const alerts = await fetchNewAlerts({ auth, filter: propsValue.query, since: lastFetchEpochMS });
+ return alerts.map((alert) => ({
+ epochMilliSeconds: new Date(alert.createdAt ?? 0).getTime(),
+ data: jsmOps.toAlertOutput(alert),
+ }));
+ },
+ };
+}
+
+async function fetchNewAlerts({ auth, filter, since }: FetchParams): Promise<ApiAlert[]> {
+ const route = await jsmOps.requireAccountRoute({ auth, feature: 'The New Alert trigger' });
+ const query = buildPollQuery({ filter, since });
+ const pages = since > 0 ? MAX_PAGES : 1;
+ const size = since > 0 ? PAGE_SIZE : TEST_PAGE_SIZE;
+ const found: ApiAlert[] = [];
+ for (let page = 0; page < pages; page++) {
+ const body = await jsmOps.send<ApiAlertList>({
+ route,
+ method: HttpMethod.GET,
+ path: '/alerts',
+ queryParams: {
+ ...(query.length > 0 ? { query } : {}),
+ sort: 'createdAt',
+ order: since > 0 ? 'asc' : 'desc',
+ size: String(size),
+ offset: String(page * size),
+ },
+ });
+ const values = body.values ?? [];
+ found.push(...values);
+ if (values.length < size) {
+ break;
+ }
+ }
+ return found;
+}
+
+function buildPollQuery({ filter, since }: { filter: string | undefined; since: number }): string {
+ const trimmed = filter?.trim() ?? '';
+ const parts = [
+ ...(since > 0 ? [`createdAt > ${Math.floor(since)}`] : []),
+ ...(trimmed.length > 0 ? [`(${trimmed})`] : []),
+ ];
+ return parts.join(' AND ');
+}
+
+function sampleAlert(): AlertOutput {
+ return {
+ id: '70413a06-38d6-4c85-92b8-5ebc900d42e2',
+ tiny_id: '1791',
+ message: 'CPU above 90% on web-01',
+ description: 'CPU usage has been above 90% for 10 minutes.',
+ status: 'open',
+ priority: 'P2',
+ alias: 'web-01-high-cpu',
+ entity: 'web-01',
+ source: 'Monitoring',
+ owner: null,
+ acknowledged: false,
+ seen: false,
+ snoozed: false,
+ snoozed_until: null,
+ count: 1,
+ tags: 'production, cpu',
+ actions: null,
+ responders: 'team:4513b7ea-3b91-438f-b7e4-e3e54af9147c',
+ extra_properties: { region: 'eu-west-1' },
+ integration_name: 'API',
+ integration_type: 'API',
+ created_at: '2026-09-28T08:15:00.000Z',
+ updated_at: '2026-09-28T08:15:00.000Z',
+ last_occurred_at: '2026-09-28T08:15:00.000Z',
+ ack_time: null,
+ close_time: null,
+ };
+}
+
+const MAX_PAGES = 5;
+const PAGE_SIZE = 100;
+const TEST_PAGE_SIZE = 10;
+
+type NewAlertProps = ReturnType<typeof newAlertProps>;
+
+type FetchParams = {
+ auth: AppConnectionValueForAuthProperty<typeof jsmOpsAuth>;
+ filter: string | undefined;
+ since: number;
+};
diff --git a/packages/pieces/community/jsm-operations/test/jsm-operations.test.ts b/packages/pieces/community/jsm-operations/test/jsm-operations.test.ts
new file mode 100644
index 00000000000..4130eb61187
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/test/jsm-operations.test.ts
@@ -0,0 +1,1171 @@
+import { HttpError, httpClient, HttpMethod } from '@activepieces/pieces-common';
+import {
+ AppConnectionType,
+ AppConnectionValueForAuthProperty,
+ createMockActionContext,
+ createMockPollingTriggerContext,
+ InputPropertyMap,
+ OutputSchema,
+ PropertyContext,
+ StaticPropsValue,
+ TriggerStrategy,
+} from '@activepieces/pieces-framework';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { acknowledgeAlertAction } from '../src/lib/actions/acknowledge-alert';
+import { addNoteAction } from '../src/lib/actions/add-note';
+import { addTagsAction } from '../src/lib/actions/add-tags';
+import { assignAlertAction } from '../src/lib/actions/assign-alert';
+import { closeAlertAction } from '../src/lib/actions/close-alert';
+import { createAlertAction } from '../src/lib/actions/create-alert';
+import { findAlertsAction } from '../src/lib/actions/find-alerts';
+import { getAlertAction } from '../src/lib/actions/get-alert';
+import { getOnCallAction } from '../src/lib/actions/get-on-call';
+import { removeTagsAction } from '../src/lib/actions/remove-tags';
+import { updateAlertAction } from '../src/lib/actions/update-alert';
+import { jsmAccountAuth, jsmKeyAuth, jsmOpsAuth } from '../src/lib/auth';
+import { jsmOps, KEY_HOSTS } from '../src/lib/common/client';
+import { jsmOpsProps } from '../src/lib/common/props';
+import { jsmOperations } from '../src';
+import { newAlertTrigger } from '../src/lib/triggers/new-alert';
+
+const sendRequest = vi.fn();
+
+const CLOUD_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
+const FAKE_ALERT_KEY = 'fake-alert-key';
+const ACCOUNT_BASE = `https://api.atlassian.com/jsm/ops/api/${CLOUD_ID}/v1`;
+const SITE = 'https://acme.atlassian.net';
+
+const ACCOUNT_AUTH: JsmConnection = {
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { siteUrl: 'acme.atlassian.net', email: '[email protected]', apiToken: 'tok', cloudId: CLOUD_ID },
+};
+
+const ACCOUNT_AUTH_NO_CLOUD_ID: JsmConnection = {
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { siteUrl: 'https://acme.atlassian.net/', email: '[email protected]', apiToken: 'tok', cloudId: undefined },
+};
+
+function keyAuth(host: string): JsmConnection {
+ return { type: AppConnectionType.BASIC_AUTH, username: host, password: FAKE_ALERT_KEY };
+}
+
+const API_ALERT = {
+ id: 'alert-1',
+ tinyId: '42',
+ createdAt: '2026-09-28T08:15:00.000Z',
+ updatedAt: '2026-09-28T08:16:00.000Z',
+ message: 'CPU high',
+ entity: 'web-01',
+ source: 'Monitor',
+ status: 'open',
+ alias: 'web-01-cpu',
+ tags: ['prod', 'cpu'],
+ extraProperties: { region: 'eu' },
+ description: 'CPU above 90%',
+ acknowledged: false,
+ count: 3,
+ owner: '',
+ snoozed: false,
+ lastOccuredAt: '2026-09-28T08:15:30.000Z',
+ integrationType: 'API',
+ integrationName: 'Default API',
+ priority: 'P2',
+ responders: [{ id: 'team-1', type: 'team' }],
+ actions: ['Restart'],
+ seen: true,
+};
+
+function mockApi(handler: Handler) {
+ sendRequest.mockImplementation(async (request: Request) => {
+ if (request.url === `${SITE}/_edge/tenant_info`) {
+ return { status: 200, body: { cloudId: CLOUD_ID } };
+ }
+ const reply = handler(request);
+ if (reply === undefined) {
+ throw new Error(`Unexpected request ${request.method} ${request.url}`);
+ }
+ if (reply.status >= 400) {
+ throw new HttpError(request.body, { status: reply.status, responseBody: reply.body });
+ }
+ return { status: reply.status, body: reply.body };
+ });
+}
+
+function requests(): Request[] {
+ return sendRequest.mock.calls.map((call) => call[0]);
+}
+
+function findRequest({ method, url }: { method: string; url: string }): Request {
+ const found = requests().find((request) => request.method === method && request.url === url);
+ if (found === undefined) {
+ throw new Error(`no ${method} ${url} request`);
+ }
+ return found;
+}
+
+function accepted(requestId: string): Reply {
+ return { status: 202, body: { result: 'Request will be processed', requestId, took: 0.01 } };
+}
+
+function processed({ requestId, alertId, success, status }: ProcessedParams): Reply {
+ return {
+ status: 200,
+ body: {
+ action: 'Create',
+ processedAt: '2026-09-28T08:15:01.000Z',
+ isSuccess: success,
+ status,
+ alertId,
+ alias: 'web-01-cpu',
+ requestId,
+ },
+ };
+}
+
+function makeContext<Props extends InputPropertyMap>({ propsValue, auth }: { propsValue: StaticPropsValue<Props>; auth: JsmConnection }) {
+ return { ...createMockActionContext<Props>({ propsValue }), auth };
+}
+
+function makeTriggerContext<Props extends InputPropertyMap>({ propsValue, auth, store }: TriggerContextParams<Props>) {
+ const { files } = createMockActionContext<Props>({ propsValue });
+ return { ...createMockPollingTriggerContext<Props>({ propsValue }), auth, store, files };
+}
+
+function memoryStore(initial: Record<string, unknown> = {}) {
+ const data = new Map<string, unknown>(Object.entries(initial));
+ return {
+ data,
+ put: async <T>(key: string, value: T): Promise<T> => {
+ data.set(key, value);
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => {
+ const value = data.get(key);
+ return value === undefined ? null : readAs<T>(value);
+ },
+ delete: async (key: string): Promise<void> => {
+ data.delete(key);
+ },
+ };
+}
+
+function readAs<T>(value: unknown): T {
+ return JSON.parse(JSON.stringify(value));
+}
+
+function propertyContext(searchValue?: string): PropertyContext {
+ const { server, project, flows, connections } = createMockActionContext({ propsValue: {} });
+ return { server, project, flows, connections, searchValue };
+}
+
+async function settle<T>(promise: Promise<T>): Promise<T> {
+ const guarded: Promise<Settled<T>> = promise.then(
+ (value): Settled<T> => ({ ok: true, value }),
+ (error: unknown): Settled<T> => ({ ok: false, error }),
+ );
+ await vi.runAllTimersAsync();
+ const result = await guarded;
+ if (!result.ok) {
+ throw result.error;
+ }
+ return result.value;
+}
+
+async function settleError(promise: Promise<unknown>): Promise<string> {
+ try {
+ await settle(promise);
+ } catch (error) {
+ return error instanceof Error ? error.message : String(error);
+ }
+ throw new Error('expected the promise to reject');
+}
+
+function fieldKeys(fields: OutputSchema['fields'] | undefined): string[] {
+ return (fields ?? []).map((field) => field.key).sort();
+}
+
+function objectKeys(value: unknown): string[] {
+ if (value === null || typeof value !== 'object') {
+ throw new Error('expected an object');
+ }
+ return Object.keys(value).sort();
+}
+
+function firstItem(value: unknown): unknown {
+ if (!Array.isArray(value) || value.length === 0) {
+ throw new Error('expected a non-empty list');
+ }
+ return value[0];
+}
+
+function validate({ auth, props }: { auth: typeof jsmAccountAuth | typeof jsmKeyAuth; props: Record<string, string> }) {
+ const server = { apiUrl: 'http://localhost:3000', publicUrl: 'http://localhost:4200', mintOidcToken: async () => 'oidc' };
+ if (auth === jsmKeyAuth) {
+ return jsmKeyAuth.validate?.({ auth: { username: props['host'] ?? '', password: props['apiKey'] ?? '' }, server });
+ }
+ return jsmAccountAuth.validate?.({
+ auth: {
+ siteUrl: props['siteUrl'] ?? '',
+ email: props['email'] ?? '',
+ apiToken: props['apiToken'] ?? '',
+ cloudId: props['cloudId'],
+ },
+ server,
+ });
+}
+
+function pollingTrigger() {
+ const trigger = newAlertTrigger;
+ if (trigger.type !== TriggerStrategy.POLLING) {
+ throw new Error('expected a polling trigger');
+ }
+ return trigger;
+}
+
+function participantAt({ result, index }: { result: unknown; index: number }): unknown {
+ if (result === null || typeof result !== 'object' || !('participants' in result) || !Array.isArray(result.participants)) {
+ throw new Error('expected participants');
+ }
+ return result.participants[index];
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation((request) => sendRequest(request));
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe('piece definition', () => {
+ it('loads with one auth per connection type and every action and trigger', () => {
+ expect(jsmOperations.displayName).toBe('Jira Service Management Operations');
+ expect(jsmOperations.description.startsWith('Opsgenie')).toBe(true);
+ expect(Object.keys(jsmOperations.actions())).toHaveLength(16);
+ expect(Object.keys(jsmOperations.triggers())).toEqual(['new_alert']);
+ expect(Object.values(jsmOperations.actions()).filter((action) => action.name !== 'custom_api_call').every((action) => action.outputSchema !== undefined && action.audience === 'both')).toBe(true);
+ });
+});
+
+describe('list inputs', () => {
+ it('accepts arrays, JSON strings and comma-separated text', () => {
+ expect(jsmOps.parseStringList(['a', ' b ', '', 3])).toEqual(['a', 'b', '3']);
+ expect(jsmOps.parseStringList('["prod","cpu"]')).toEqual(['prod', 'cpu']);
+ expect(jsmOps.parseStringList('prod, cpu')).toEqual(['prod', 'cpu']);
+ expect(jsmOps.parseStringList(undefined)).toEqual([]);
+ });
+});
+
+describe('connection routing', () => {
+ it('tells the two connection types apart by connection type', () => {
+ expect(jsmOps.isKeyConnection(keyAuth(KEY_HOSTS.opsgenieEu))).toBe(true);
+ expect(jsmOps.isKeyConnection(keyAuth('eu'))).toBe(true);
+ expect(jsmOps.isKeyConnection(ACCOUNT_AUTH)).toBe(false);
+ expect(jsmOpsAuth).toEqual([jsmAccountAuth, jsmKeyAuth]);
+ });
+
+ it('uses basic auth against the cloud-scoped JSM Operations API for account connections', async () => {
+ const route = await jsmOps.routeFor(ACCOUNT_AUTH);
+ const expected = `Basic ${Buffer.from('[email protected]:tok').toString('base64')}`;
+ expect(route).toEqual({ kind: 'account', baseUrl: ACCOUNT_BASE, siteUrl: SITE, headers: { Authorization: expected } });
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('looks the Cloud ID up from the site when it is empty, without following redirects', async () => {
+ mockApi(() => undefined);
+
+ const route = await jsmOps.routeFor(ACCOUNT_AUTH_NO_CLOUD_ID);
+
+ expect(route.baseUrl).toBe(ACCOUNT_BASE);
+ const lookup = findRequest({ method: 'GET', url: `${SITE}/_edge/tenant_info` });
+ expect(lookup.followRedirects).toBe(false);
+ expect(lookup.timeout).toBeGreaterThan(0);
+ });
+
+ it('rejects site URLs that are not https Atlassian Cloud hosts', () => {
+ expect(jsmOps.normalizeSiteUrl('https://acme.atlassian.net/jira/')).toBe(SITE);
+ expect(() => jsmOps.normalizeSiteUrl('http://acme.atlassian.net')).toThrow(/not an Atlassian Cloud site/);
+ expect(() => jsmOps.normalizeSiteUrl('https://evil.example.com')).toThrow(/not an Atlassian Cloud site/);
+ expect(() => jsmOps.normalizeSiteUrl('https://atlassian.net.evil.com')).toThrow(/not an Atlassian Cloud site/);
+ expect(() => jsmOps.normalizeSiteUrl('https://acme.atlassian.net:8443')).toThrow(/not an Atlassian Cloud site/);
+ });
+
+ it('fails clearly when the site returns no Cloud ID', async () => {
+ sendRequest.mockResolvedValue({ status: 200, body: { cloudId: '' } });
+
+ await expect(jsmOps.routeFor(ACCOUNT_AUTH_NO_CLOUD_ID)).rejects.toThrow(/did not return a Cloud ID/);
+ });
+
+ it.each([
+ [KEY_HOSTS.jsm, 'https://api.atlassian.com/jsm/ops/integration/v2'],
+ [KEY_HOSTS.opsgenieUs, 'https://api.opsgenie.com/v2'],
+ [KEY_HOSTS.opsgenieEu, 'https://api.eu.opsgenie.com/v2'],
+ ])('sends GenieKey auth to the %s alert API', async (host, baseUrl) => {
+ const route = await jsmOps.routeFor(keyAuth(host));
+ expect(route).toEqual({ kind: 'key', baseUrl, headers: { Authorization: `GenieKey ${FAKE_ALERT_KEY}` } });
+ });
+
+ it.each([
+ ['jsm', KEY_HOSTS.jsm],
+ [' US ', KEY_HOSTS.opsgenieUs],
+ ['eu', KEY_HOSTS.opsgenieEu],
+ ['api.eu.opsgenie.com/', KEY_HOSTS.opsgenieEu],
+ ['https://api.atlassian.com/jsm/ops/integration', KEY_HOSTS.jsm],
+ ])('accepts %s as the API host', (value, host) => {
+ expect(jsmOps.resolveKeyHost(value)).toBe(host);
+ });
+
+ it('refuses API hosts outside the allowed list', async () => {
+ await expect(jsmOps.routeFor(keyAuth('https://attacker.example.com'))).rejects.toThrow(/Unknown API host/);
+ await expect(jsmOps.routeFor(keyAuth('http://api.opsgenie.com'))).rejects.toThrow(/Unknown API host/);
+ });
+});
+
+describe('connection validation', () => {
+ it('accepts an account that can list alerts', async () => {
+ mockApi((request) => (request.url === `${ACCOUNT_BASE}/alerts` ? { status: 200, body: { values: [] } } : undefined));
+
+ await expect(
+ validate({ auth: jsmAccountAuth, props: { siteUrl: SITE, email: '[email protected]', apiToken: 'tok', cloudId: CLOUD_ID } }),
+ ).resolves.toEqual({ valid: true });
+ expect(findRequest({ method: 'GET', url: `${ACCOUNT_BASE}/alerts` }).queryParams).toEqual({ size: '1' });
+ });
+
+ it('reports the vendor message when the account is rejected', async () => {
+ mockApi(() => ({ status: 401, body: { code: 401, message: 'Unauthorized' } }));
+
+ const result = await validate({ auth: jsmAccountAuth, props: { siteUrl: SITE, email: '[email protected]', apiToken: 'bad', cloudId: CLOUD_ID } });
+
+ expect(result).toEqual({ valid: false, error: expect.stringContaining('HTTP 401): Unauthorized') });
+ });
+
+ it('accepts an API key when an unknown request ID gives 404 and rejects it on 401', async () => {
+ mockApi(() => ({ status: 404, body: { message: 'Request not found' } }));
+ await expect(validate({ auth: jsmKeyAuth, props: { host: KEY_HOSTS.jsm, apiKey: 'good' } })).resolves.toEqual({ valid: true });
+
+ mockApi(() => ({ status: 401, body: { message: 'Could not authenticate' } }));
+ const result = await validate({ auth: jsmKeyAuth, props: { host: KEY_HOSTS.opsgenieUs, apiKey: 'bad' } });
+ expect(result).toEqual({ valid: false, error: expect.stringContaining('Could not authenticate') });
+ });
+});
+
+describe('Create Alert', () => {
+ const defaults = {
+ description: undefined,
+ priority: 'P3',
+ alias: undefined,
+ responderTeams: undefined,
+ responderUsers: undefined,
+ responderSchedules: undefined,
+ responderEscalations: undefined,
+ responderNames: undefined,
+ tags: undefined,
+ entity: undefined,
+ source: undefined,
+ note: undefined,
+ extraProperties: undefined,
+ actions: undefined,
+ user: undefined,
+ };
+
+ function runCreate({ auth, propsValue }: { auth: JsmConnection; propsValue: Partial<StaticPropsValue<typeof createAlertAction.props>> }) {
+ return createAlertAction.run(
+ makeContext<typeof createAlertAction.props>({ auth, propsValue: { message: 'CPU high', ...defaults, ...propsValue } }),
+ );
+ }
+
+ it('posts the account-route body and returns the processed alert ID', async () => {
+ mockApi((request) => {
+ if (request.method === 'POST' && request.url === `${ACCOUNT_BASE}/alerts`) {
+ return accepted('req-1');
+ }
+ if (request.url === `${ACCOUNT_BASE}/alerts/requests/req-1`) {
+ return processed({ requestId: 'req-1', alertId: 'alert-1', success: true, status: 'Created alert' });
+ }
+ return undefined;
+ });
+
+ const result = await settle(
+ runCreate({
+ auth: ACCOUNT_AUTH,
+ propsValue: {
+ alias: ' web-01-cpu ',
+ priority: 'P1',
+ responderTeams: ['team-1'],
+ responderUsers: ['acc-1'],
+ tags: ['prod', ' ', 'cpu'],
+ extraProperties: { region: 'eu', attempts: 3 },
+ user: 'ignored-on-account-route',
+ },
+ }),
+ );
+
+ expect(findRequest({ method: 'POST', url: `${ACCOUNT_BASE}/alerts` }).body).toEqual({
+ message: 'CPU high',
+ alias: 'web-01-cpu',
+ priority: 'P1',
+ responders: [
+ { id: 'team-1', type: 'team' },
+ { id: 'acc-1', type: 'user' },
+ ],
+ tags: ['prod', 'cpu'],
+ extraProperties: { region: 'eu', attempts: '3' },
+ });
+ expect(result).toEqual({
+ request_id: 'req-1',
+ processed: true,
+ success: true,
+ action: 'Create',
+ status: 'Created alert',
+ alert_id: 'alert-1',
+ alias: 'web-01-cpu',
+ processed_at: '2026-09-28T08:15:01.000Z',
+ });
+ });
+
+ it('uses the Opsgenie shape on API key connections: details, user and names', async () => {
+ mockApi((request) => {
+ if (request.method === 'POST' && request.url === 'https://api.eu.opsgenie.com/v2/alerts') {
+ return accepted('req-2');
+ }
+ if (request.url === 'https://api.eu.opsgenie.com/v2/alerts/requests/req-2') {
+ return { status: 200, body: { data: { success: true, action: 'Create', alertId: 'og-1', status: 'Created alert' }, took: 0.1 } };
+ }
+ return undefined;
+ });
+
+ const result = await settle(
+ runCreate({
+ auth: keyAuth(KEY_HOSTS.opsgenieEu),
+ propsValue: {
+ responderNames: [
+ { type: 'team', name: 'Ops' },
+ { type: 'user', name: '[email protected]' },
+ ],
+ extraProperties: { region: 'eu' },
+ user: 'Activepieces',
+ },
+ }),
+ );
+
+ const create = findRequest({ method: 'POST', url: 'https://api.eu.opsgenie.com/v2/alerts' });
+ expect(create.headers?.['Authorization']).toBe(`GenieKey ${FAKE_ALERT_KEY}`);
+ expect(create.body).toEqual({
+ message: 'CPU high',
+ priority: 'P3',
+ user: 'Activepieces',
+ responders: [
+ { name: 'Ops', type: 'team' },
+ { username: '[email protected]', type: 'user' },
+ ],
+ details: { region: 'eu' },
+ });
+ expect(result).toMatchObject({ alert_id: 'og-1', processed: true, success: true });
+ });
+
+ it('keeps polling while the request is not processed yet, then returns processed false', async () => {
+ mockApi((request) => {
+ if (request.method === 'POST') {
+ return accepted('req-3');
+ }
+ return { status: 404, body: { message: 'Request not found. It might not be processed, yet.' } };
+ });
+
+ const result = await settle(runCreate({ auth: keyAuth(KEY_HOSTS.jsm), propsValue: {} }));
+
+ const polls = requests().filter((request) => request.url.endsWith('/alerts/requests/req-3'));
+ expect(polls).toHaveLength(5);
+ expect(polls.every((request) => request.timeout !== undefined && request.timeout <= 5_000)).toBe(true);
+ expect(result).toMatchObject({ request_id: 'req-3', processed: false, success: null, alert_id: null });
+ });
+
+ it('stays within about 30 seconds of polling', () => {
+ const waits = [500, 1_000, 2_000, 3_000, 4_000].reduce((total, delay) => total + delay, 0);
+ expect(waits + 5 * 4_000).toBeLessThanOrEqual(30_500);
+ });
+
+ it('fails with the vendor status when processing failed', async () => {
+ mockApi((request) => {
+ if (request.method === 'POST') {
+ return accepted('req-4');
+ }
+ return processed({ requestId: 'req-4', alertId: '', success: false, status: 'Responder team does not exist' });
+ });
+
+ const message = await settleError(runCreate({ auth: ACCOUNT_AUTH, propsValue: {} }));
+
+ expect(message).toBe('JSM Operations could not create the alert: Responder team does not exist.');
+ });
+
+ it('explains plan-limited actions instead of showing only the raw vendor text', async () => {
+ mockApi((request) => {
+ if (request.method === 'POST') {
+ return accepted('req-plan');
+ }
+ return processed({
+ requestId: 'req-plan',
+ alertId: '',
+ success: false,
+ status: 'Your account plan does not support alert assign action..',
+ });
+ });
+
+ const message = await settleError(runCreate({ auth: ACCOUNT_AUTH, propsValue: {} }));
+
+ expect(message).toContain('Your account plan does not support alert assign action.');
+ expect(message).not.toContain('action...');
+ expect(message).toContain('not included in your Jira Service Management plan');
+ });
+
+ it('surfaces validation errors from the API', async () => {
+ mockApi(() => ({ status: 422, body: { errors: [{ title: 'message should not exceed 130 characters', code: 'x' }] } }));
+
+ const message = await settleError(runCreate({ auth: ACCOUNT_AUTH, propsValue: {} }));
+
+ expect(message).toContain('HTTP 422): message should not exceed 130 characters');
+ });
+
+ it('rejects name-based responders on account connections', async () => {
+ const message = await settleError(
+ runCreate({ auth: ACCOUNT_AUTH, propsValue: { responderNames: [{ type: 'team', name: 'Ops' }] } }),
+ );
+
+ expect(message).toMatch(/only work with API key connections/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('key-route alert actions', () => {
+ it('acknowledges by alias with identifierType on the API key route', async () => {
+ mockApi((request) => {
+ if (request.method === 'POST') {
+ return accepted('req-a');
+ }
+ return { status: 200, body: { data: { success: true, action: 'Acknowledge', alertId: 'og-9', status: 'Acknowledged' } } };
+ });
+
+ const result = await settle(
+ acknowledgeAlertAction.run(
+ makeContext<typeof acknowledgeAlertAction.props>({
+ auth: keyAuth(KEY_HOSTS.jsm),
+ propsValue: { alert: 'web-01-cpu', identifierType: 'alias', note: 'On it', user: 'Bot', source: undefined },
+ }),
+ ),
+ );
+
+ const ack = findRequest({ method: 'POST', url: 'https://api.atlassian.com/jsm/ops/integration/v2/alerts/web-01-cpu/acknowledge' });
+ expect(ack.queryParams).toEqual({ identifierType: 'alias' });
+ expect(ack.body).toEqual({ note: 'On it', user: 'Bot' });
+ expect(ack.headers?.['Authorization']).toBe(`GenieKey ${FAKE_ALERT_KEY}`);
+ expect(result).toMatchObject({ processed: true, success: true, alert_id: 'og-9', note_added: true, note_error: null });
+ });
+
+ it('closes on the account route by resolving the alias, then adds the note', async () => {
+ mockApi((request) => {
+ if (request.url === `${ACCOUNT_BASE}/alerts/alias`) {
+ return { status: 200, body: API_ALERT };
+ }
+ if (request.url === `${ACCOUNT_BASE}/alerts/alert-1/close`) {
+ return accepted('req-c');
+ }
+ if (request.url === `${ACCOUNT_BASE}/alerts/requests/req-c`) {
+ return processed({ requestId: 'req-c', alertId: 'alert-1', success: true, status: 'Closed' });
+ }
+ if (request.url === `${ACCOUNT_BASE}/alerts/alert-1/notes`) {
+ return { status: 200, body: { id: 'note-1', note: 'Fixed' } };
+ }
+ return undefined;
+ });
+
+ const result = await settle(
+ closeAlertAction.run(
+ makeContext<typeof closeAlertAction.props>({
+ auth: ACCOUNT_AUTH,
+ propsValue: { alert: 'web-01-cpu', identifierType: 'alias', note: 'Fixed', user: undefined, source: undefined },
+ }),
+ ),
+ );
+
+ expect(findRequest({ method: 'GET', url: `${ACCOUNT_BASE}/alerts/alias` }).queryParams).toEqual({ alias: 'web-01-cpu' });
+ expect(findRequest({ method: 'POST', url: `${ACCOUNT_BASE}/alerts/alert-1/close` }).body).toBeUndefined();
+ expect(findRequest({ method: 'POST', url: `${ACCOUNT_BASE}/alerts/alert-1/notes` }).body).toEqual({ note: 'Fixed' });
+ expect(result).toMatchObject({ alert_id: 'alert-1', success: true, note_added: true, note_error: null });
+ expect(objectKeys(result)).toEqual(fieldKeys(closeAlertAction.outputSchema?.fields));
+ });
+
+ it('still reports the close when the follow-up note fails, instead of failing the step', async () => {
+ mockApi((request) => {
+ if (request.url === `${ACCOUNT_BASE}/alerts/alert-1/close`) {
+ return accepted('req-c');
+ }
+ if (request.url === `${ACCOUNT_BASE}/alerts/requests/req-c`) {
+ return processed({ requestId: 'req-c', alertId: 'alert-1', success: true, status: 'Closed' });
+ }
+ if (request.url === `${ACCOUNT_BASE}/alerts/alert-1/notes`) {
+ return { status: 500, body: { message: 'Internal error' } };
+ }
+ return undefined;
+ });
+
+ const result = await settle(
+ closeAlertAction.run(
+ makeContext<typeof closeAlertAction.props>({
+ auth: ACCOUNT_AUTH,
+ propsValue: { alert: 'alert-1', identifierType: 'id', note: 'Fixed', user: undefined, source: undefined },
+ }),
+ ),
+ );
+
+ expect(result).toMatchObject({ alert_id: 'alert-1', success: true, note_added: false });
+ expect(result).toHaveProperty('note_error', expect.stringContaining('The alert was updated, but the note could not be added'));
+ });
+
+ it('leaves the note fields empty when no note is given', async () => {
+ mockApi((request) => {
+ if (request.url === `${ACCOUNT_BASE}/alerts/alert-1/acknowledge`) {
+ return accepted('req-a');
+ }
+ if (request.url === `${ACCOUNT_BASE}/alerts/requests/req-a`) {
+ return processed({ requestId: 'req-a', alertId: 'alert-1', success: true, status: 'Acknowledged' });
+ }
+ return undefined;
+ });
+
+ const result = await settle(
+ acknowledgeAlertAction.run(
+ makeContext<typeof acknowledgeAlertAction.props>({
+ auth: ACCOUNT_AUTH,
+ propsValue: { alert: 'alert-1', identifierType: 'id', note: undefined, user: undefined, source: undefined },
+ }),
+ ),
+ );
+
+ expect(result).toMatchObject({ success: true, note_added: null, note_error: null });
+ expect(requests().some((request) => request.url.endsWith('/notes'))).toBe(false);
+ });
+
+ it('adds a note synchronously on the account route and asynchronously with a key', async () => {
+ mockApi((request) => {
+ if (request.url === `${ACCOUNT_BASE}/alerts/alert-1/notes`) {
+ return { status: 200, body: { id: 'note-1', note: 'Checked logs', createdAt: '2026-09-28T09:00:00Z' } };
+ }
+ if (request.url === 'https://api.opsgenie.com/v2/alerts/alert-1/notes') {
+ return accepted('req-n');
+ }
+ if (request.url === 'https://api.opsgenie.com/v2/alerts/requests/req-n') {
+ return { status: 200, body: { data: { success: true, action: 'AddNote', alertId: 'alert-1' } } };
+ }
+ return undefined;
+ });
+ const propsValue = { alert: 'alert-1', identifierType: 'id', note: 'Checked logs', user: undefined, source: undefined };
+
+ const account = await settle(
+ addNoteAction.run(makeContext<typeof addNoteAction.props>({ auth: ACCOUNT_AUTH, propsValue })),
+ );
+ const key = await settle(
+ addNoteAction.run(makeContext<typeof addNoteAction.props>({ auth: keyAuth(KEY_HOSTS.opsgenieUs), propsValue })),
+ );
+
+ expect(account).toMatchObject({ note_id: 'note-1', request_id: null, processed: true, alert_id: 'alert-1' });
+ expect(key).toMatchObject({ note_id: null, request_id: 'req-n', processed: true, alert_id: 'alert-1' });
+ expect(findRequest({ method: 'POST', url: 'https://api.opsgenie.com/v2/alerts/alert-1/notes' }).queryParams).toEqual({ identifierType: 'id' });
+ expect(objectKeys(account)).toEqual(fieldKeys(addNoteAction.outputSchema?.fields));
+ expect(objectKeys(key)).toEqual(fieldKeys(addNoteAction.outputSchema?.fields));
+ });
+});
+
+describe('account-only actions', () => {
+ it.each([
+ ['Get Alert', () => getAlertAction.run(makeContext<typeof getAlertAction.props>({ auth: keyAuth(KEY_HOSTS.jsm), propsValue: { alert: 'a', identifierType: 'id' } }))],
+ [
+ 'Find Alerts',
+ () =>
+ findAlertsAction.run(
+ makeContext<typeof findAlertsAction.props>({
+ auth: keyAuth(KEY_HOSTS.opsgenieUs),
+ propsValue: { query: undefined, sort: undefined, order: undefined, limit: undefined, offset: undefined },
+ }),
+ ),
+ ],
+ [
+ 'Add Tags to Alert',
+ () => addTagsAction.run(makeContext<typeof addTagsAction.props>({ auth: keyAuth(KEY_HOSTS.jsm), propsValue: { alert: 'a', identifierType: 'id', tags: ['x'] } })),
+ ],
+ [
+ 'Get Who Is On Call',
+ () => getOnCallAction.run(makeContext<typeof getOnCallAction.props>({ auth: keyAuth(KEY_HOSTS.jsm), propsValue: { scheduleId: 's', date: undefined } })),
+ ],
+ ])('%s refuses an API key connection with a clear message', async (feature, run) => {
+ const message = await settleError(run());
+
+ expect(message).toContain(`${feature} needs an Atlassian account connection`);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('gets an alert by alias and flattens it to the output schema keys', async () => {
+ mockApi((request) => (request.url === `${ACCOUNT_BASE}/alerts/alias` ? { status: 200, body: API_ALERT } : undefined));
+
+ const result = await getAlertAction.run(
+ makeContext<typeof getAlertAction.props>({ auth: ACCOUNT_AUTH, propsValue: { alert: 'web-01-cpu', identifierType: 'alias' } }),
+ );
+
+ expect(result).toMatchObject({
+ id: 'alert-1',
+ tags: 'prod, cpu',
+ responders: 'team:team-1',
+ owner: null,
+ last_occurred_at: '2026-09-28T08:15:30.000Z',
+ extra_properties: { region: 'eu' },
+ });
+ expect(objectKeys(result)).toEqual(fieldKeys(getAlertAction.outputSchema?.fields));
+ });
+
+ it('builds the Find Alerts query and clamps the page size', async () => {
+ mockApi((request) => (request.url === `${ACCOUNT_BASE}/alerts` ? { status: 200, body: { values: [API_ALERT], count: 1 } } : undefined));
+
+ const result = await findAlertsAction.run(
+ makeContext<typeof findAlertsAction.props>({
+ auth: ACCOUNT_AUTH,
+ propsValue: { query: ' status: open ', sort: 'priority', order: 'asc', limit: 500, offset: 20 },
+ }),
+ );
+
+ expect(findRequest({ method: 'GET', url: `${ACCOUNT_BASE}/alerts` }).queryParams).toEqual({
+ query: 'status: open',
+ sort: 'priority',
+ order: 'asc',
+ size: '100',
+ offset: '20',
+ });
+ const schema = findAlertsAction.outputSchema;
+ expect(schema?.fields[0].value).toBe('');
+ expect(objectKeys(firstItem(result))).toEqual(fieldKeys(schema?.fields[0].listItems));
+ });
+
+ it('omits an empty query and falls back to safe defaults', async () => {
+ mockApi(() => ({ status: 200, body: { values: [] } }));
+
+ await findAlertsAction.run(
+ makeContext<typeof findAlertsAction.props>({
+ auth: ACCOUNT_AUTH,
+ propsValue: { query: ' ', sort: 'bogus', order: undefined, limit: 0, offset: -5 },
+ }),
+ );
+
+ expect(requests()[0].queryParams).toEqual({ sort: 'createdAt', order: 'desc', size: '1', offset: '0' });
+ });
+
+ it('removes tags with a DELETE body and assigns by account ID', async () => {
+ mockApi((request) => {
+ if (request.url.endsWith('/requests/req-t')) {
+ return processed({ requestId: 'req-t', alertId: 'alert-1', success: true, status: 'ok' });
+ }
+ return accepted('req-t');
+ });
+
+ await settle(
+ removeTagsAction.run(
+ makeContext<typeof removeTagsAction.props>({ auth: ACCOUNT_AUTH, propsValue: { alert: 'alert-1', identifierType: 'id', tags: ['prod', 'cpu'] } }),
+ ),
+ );
+ await settle(
+ assignAlertAction.run(
+ makeContext<typeof assignAlertAction.props>({ auth: ACCOUNT_AUTH, propsValue: { alert: 'alert-1', identifierType: 'id', accountId: 'acc-7' } }),
+ ),
+ );
+
+ expect(findRequest({ method: 'DELETE', url: `${ACCOUNT_BASE}/alerts/alert-1/tags` }).body).toEqual({ tags: ['prod', 'cpu'] });
+ expect(findRequest({ method: 'POST', url: `${ACCOUNT_BASE}/alerts/alert-1/assign` }).body).toEqual({ accountId: 'acc-7' });
+ });
+
+ it('updates only the filled fields with one PATCH each', async () => {
+ mockApi((request) => {
+ if (request.method === 'PATCH') {
+ return accepted(`req-${request.url.split('/').pop()}`);
+ }
+ const requestId = request.url.split('/').pop() ?? '';
+ return processed({ requestId, alertId: 'alert-1', success: true, status: 'Updated' });
+ });
+
+ const result = await settle(
+ updateAlertAction.run(
+ makeContext<typeof updateAlertAction.props>({
+ auth: ACCOUNT_AUTH,
+ propsValue: { alert: 'alert-1', identifierType: 'id', message: 'New msg', description: undefined, priority: 'P1' },
+ }),
+ ),
+ );
+
+ expect(findRequest({ method: 'PATCH', url: `${ACCOUNT_BASE}/alerts/alert-1/message` }).body).toEqual({ message: 'New msg' });
+ expect(findRequest({ method: 'PATCH', url: `${ACCOUNT_BASE}/alerts/alert-1/priority` }).body).toEqual({ priority: 'P1' });
+ expect(requests().some((request) => request.url.endsWith('/description'))).toBe(false);
+ expect(result).toMatchObject({ alert_id: 'alert-1', updated_fields: 'message, priority', processed: true });
+ expect(objectKeys(result)).toEqual(fieldKeys(updateAlertAction.outputSchema?.fields));
+ });
+
+ it('flattens on-call participants and collects user IDs', async () => {
+ mockApi((request) =>
+ request.url === `${ACCOUNT_BASE}/schedules/sched-1/on-calls`
+ ? {
+ status: 200,
+ body: {
+ onCallParticipants: [
+ { id: 'team-1', type: 'team' },
+ { id: 'acc-1', type: 'user' },
+ { id: 'esc-1', type: 'escalation', onCallParticipants: [{ id: 'acc-2', type: 'user', forwardedFrom: { id: 'acc-3', type: 'user' } }] },
+ ],
+ },
+ }
+ : undefined,
+ );
+
+ const result = await getOnCallAction.run(
+ makeContext<typeof getOnCallAction.props>({ auth: ACCOUNT_AUTH, propsValue: { scheduleId: 'sched-1', date: '2026-09-28T10:00:00Z' } }),
+ );
+
+ expect(findRequest({ method: 'GET', url: `${ACCOUNT_BASE}/schedules/sched-1/on-calls` }).queryParams).toEqual({
+ flat: 'false',
+ date: '2026-09-28T10:00:00.000Z',
+ });
+ expect(result).toMatchObject({ on_call_user_ids: 'acc-1, acc-2', on_call_user_count: 2 });
+ expect(participantAt({ result, index: 3 })).toEqual({
+ id: 'acc-2',
+ type: 'user',
+ name: null,
+ parent_id: 'esc-1',
+ parent_type: 'escalation',
+ forwarded_from_id: 'acc-3',
+ });
+ expect(objectKeys(result)).toEqual(fieldKeys(getOnCallAction.outputSchema?.fields));
+ });
+});
+
+describe('classification', () => {
+ it('tags Close Alert as destructive because a closed alert cannot be reopened', () => {
+ expect(closeAlertAction.classification).toBe('DESTRUCTIVE');
+ });
+});
+
+describe('Custom API Call', () => {
+ const customApiCallAction = jsmOperations.actions()['custom_api_call'];
+
+ const propsValue = {
+ url: { url: '/alerts/count' },
+ method: HttpMethod.GET,
+ headers: {},
+ queryParams: {},
+ body_type: 'none',
+ body: undefined,
+ response_is_binary: false,
+ failsafe: false,
+ timeout: 10,
+ followRedirects: false,
+ };
+
+ it('is tagged for humans as an arbitrary write', () => {
+ expect(customApiCallAction).toMatchObject({ classification: 'WRITE', audience: 'human', aiMetadata: { idempotent: false } });
+ });
+
+ it('resolves the Cloud ID before calling a relative path on an account connection', async () => {
+ mockApi(() => ({ status: 200, body: { count: 3 } }));
+
+ await customApiCallAction.run(makeContext<typeof customApiCallAction.props>({ auth: ACCOUNT_AUTH_NO_CLOUD_ID, propsValue }));
+
+ const call = requests().find((request) => request.url.includes('/alerts/count'));
+ expect(call?.url).toBe(`${ACCOUNT_BASE}/alerts/count`);
+ expect(call?.headers?.['Authorization']).toMatch(/^Basic /);
+ });
+
+ it('calls the key host with the GenieKey header', async () => {
+ mockApi(() => ({ status: 200, body: { data: { count: 3 } } }));
+
+ await customApiCallAction.run(makeContext<typeof customApiCallAction.props>({ auth: keyAuth(KEY_HOSTS.opsgenieUs), propsValue }));
+
+ expect(requests()[0].url).toBe('https://api.opsgenie.com/v2/alerts/count');
+ expect(requests()[0].headers?.['Authorization']).toBe(`GenieKey ${FAKE_ALERT_KEY}`);
+ });
+
+ it('accepts a full URL under the connection base URL', async () => {
+ mockApi(() => ({ status: 200, body: { count: 3 } }));
+
+ await customApiCallAction.run(
+ makeContext<typeof customApiCallAction.props>({ auth: ACCOUNT_AUTH, propsValue: { ...propsValue, url: { url: `${ACCOUNT_BASE}/alerts/count` } } }),
+ );
+
+ expect(requests()[0].url).toBe(`${ACCOUNT_BASE}/alerts/count`);
+ });
+
+ it.each([
+ ['another host', 'https://attacker.example/collect'],
+ ['a lookalike host', 'https://api.atlassian.com.attacker.example/jsm/ops/api/x/v1/alerts'],
+ ['plain http', `http://api.atlassian.com/jsm/ops/api/${CLOUD_ID}/v1/alerts`],
+ ['another Atlassian API', 'https://api.atlassian.com/ex/jira/x/rest/api/3/myself'],
+ ['another cloud ID', 'https://api.atlassian.com/jsm/ops/api/other-cloud/v1/alerts'],
+ ['a path that climbs out of the base', `${ACCOUNT_BASE}/../../other/v1/alerts`],
+ ['embedded credentials', `https://user:[email protected]/jsm/ops/api/${CLOUD_ID}/v1/alerts`],
+ ['a protocol-relative URL', '//attacker.example/collect'],
+ ])('refuses %s without sending the account credentials', async (_label, url) => {
+ mockApi(() => ({ status: 200, body: {} }));
+
+ await expect(
+ customApiCallAction.run(makeContext<typeof customApiCallAction.props>({ auth: ACCOUNT_AUTH, propsValue: { ...propsValue, url: { url } } })),
+ ).rejects.toThrow(/credentials|not a valid URL/);
+ expect(requests()).toHaveLength(0);
+ });
+
+ it('keeps an API key on the host picked for the connection', async () => {
+ mockApi(() => ({ status: 200, body: {} }));
+
+ await expect(
+ customApiCallAction.run(
+ makeContext<typeof customApiCallAction.props>({ auth: keyAuth(KEY_HOSTS.opsgenieEu), propsValue: { ...propsValue, url: { url: 'https://api.opsgenie.com/v2/alerts' } } }),
+ ),
+ ).rejects.toThrow(`only sends this connection's credentials to ${KEY_HOSTS.opsgenieEu}/v2`);
+ expect(requests()).toHaveLength(0);
+ });
+});
+
+describe('New Alert trigger', () => {
+ const props = { query: 'priority: P1' };
+
+ it('polls oldest-first for alerts created after the last poll and returns only new ones', async () => {
+ mockApi((request) =>
+ request.url === `${ACCOUNT_BASE}/alerts`
+ ? {
+ status: 200,
+ body: {
+ values: [
+ { ...API_ALERT, id: 'old', createdAt: '2026-09-28T08:00:00.000Z' },
+ { ...API_ALERT, id: 'new', createdAt: '2026-09-28T08:20:00.000Z' },
+ ],
+ },
+ }
+ : undefined,
+ );
+ const since = Date.parse('2026-09-28T08:10:00.000Z');
+ const store = memoryStore({ lastPoll: since });
+
+ const items = await pollingTrigger().run(makeTriggerContext<typeof newAlertTrigger.props>({ auth: ACCOUNT_AUTH, propsValue: props, store }));
+
+ expect(requests()[0].queryParams).toEqual({
+ query: `createdAt > ${since} AND (priority: P1)`,
+ sort: 'createdAt',
+ order: 'asc',
+ size: '100',
+ offset: '0',
+ });
+ expect(items).toHaveLength(1);
+ expect(firstItem(items)).toMatchObject({ id: 'new' });
+ expect(store.data.get('lastPoll')).toBe(Date.parse('2026-09-28T08:20:00.000Z'));
+ expect(objectKeys(firstItem(items))).toEqual(fieldKeys(newAlertTrigger.outputSchema?.fields));
+ });
+
+ it('pages up to five full pages and then stops', async () => {
+ const page = Array.from({ length: 100 }, (_, index) => ({ ...API_ALERT, id: `a${index}`, createdAt: new Date(Date.parse('2026-09-28T09:00:00Z') + index).toISOString() }));
+ mockApi(() => ({ status: 200, body: { values: page } }));
+
+ await pollingTrigger().run(
+ makeTriggerContext<typeof newAlertTrigger.props>({ auth: ACCOUNT_AUTH, propsValue: { query: undefined }, store: memoryStore({ lastPoll: 1 }) }),
+ );
+
+ expect(requests().map((request) => request.queryParams?.['offset'])).toEqual(['0', '100', '200', '300', '400']);
+ expect(requests()[0].queryParams?.['query']).toBe('createdAt > 1');
+ });
+
+ it('tests with the newest alerts and no time filter', async () => {
+ mockApi(() => ({ status: 200, body: { values: [API_ALERT] } }));
+
+ const items = await pollingTrigger().test(
+ makeTriggerContext<typeof newAlertTrigger.props>({ auth: ACCOUNT_AUTH, propsValue: { query: undefined }, store: memoryStore() }),
+ );
+
+ expect(requests()[0].queryParams).toEqual({ sort: 'createdAt', order: 'desc', size: '10', offset: '0' });
+ expect(items).toHaveLength(1);
+ });
+
+ it('refuses to enable on an API key connection', async () => {
+ const store = memoryStore();
+
+ await expect(
+ pollingTrigger().onEnable(makeTriggerContext<typeof newAlertTrigger.props>({ auth: keyAuth(KEY_HOSTS.jsm), propsValue: props, store })),
+ ).rejects.toThrow(/The New Alert trigger needs an Atlassian account connection/);
+ expect(store.data.has('lastPoll')).toBe(false);
+ });
+
+ it('stores the checkpoint when enabled on an account connection', async () => {
+ const store = memoryStore();
+
+ await pollingTrigger().onEnable(makeTriggerContext<typeof newAlertTrigger.props>({ auth: ACCOUNT_AUTH, propsValue: props, store }));
+
+ expect(typeof store.data.get('lastPoll')).toBe('number');
+ });
+});
+
+describe('dropdowns', () => {
+ it('lists teams by name', async () => {
+ mockApi((request) =>
+ request.url === `${ACCOUNT_BASE}/teams` ? { status: 200, body: [{ teamId: 't1', teamName: 'Ops' }] } : undefined,
+ );
+
+ const state = await jsmOpsProps.teams({ displayName: 'Teams', description: 'd' }).options({ auth: ACCOUNT_AUTH }, propertyContext());
+
+ expect(state).toEqual({ disabled: false, options: [{ label: 'Ops', value: 't1' }], placeholder: undefined });
+ });
+
+ it('lists escalations across teams, labelled with the team', async () => {
+ mockApi((request) => {
+ if (request.url === `${ACCOUNT_BASE}/teams`) {
+ return { status: 200, body: { platformTeams: [{ teamId: 't1', teamName: 'Ops' }, { teamId: 't2', teamName: 'DB' }] } };
+ }
+ if (request.url === `${ACCOUNT_BASE}/teams/t1/escalations`) {
+ return { status: 200, body: { values: [{ id: 'e1', name: 'Ops_escalation' }] } };
+ }
+ if (request.url === `${ACCOUNT_BASE}/teams/t2/escalations`) {
+ return { status: 200, body: { values: [] } };
+ }
+ return undefined;
+ });
+
+ const state = await jsmOpsProps.escalation({ displayName: 'Escalation', description: 'd' }).options({ auth: ACCOUNT_AUTH }, propertyContext());
+
+ expect(state.options).toEqual([{ label: 'Ops_escalation (Ops)', value: 'e1' }]);
+ });
+
+ it('lists escalations from every team and pages each team past 100', async () => {
+ const teams = Array.from({ length: 30 }, (_, index) => ({ teamId: `t${index}`, teamName: `Team ${index}` }));
+ const full = Array.from({ length: 100 }, (_, index) => ({ id: `e${index}`, name: `E${index}` }));
+ mockApi((request) => {
+ if (request.url === `${ACCOUNT_BASE}/teams`) {
+ return { status: 200, body: teams };
+ }
+ if (request.url === `${ACCOUNT_BASE}/teams/t0/escalations`) {
+ return { status: 200, body: { values: request.queryParams?.['offset'] === '0' ? full : [{ id: 'e-last', name: 'Last' }] } };
+ }
+ if (request.url === `${ACCOUNT_BASE}/teams/t29/escalations`) {
+ return { status: 200, body: { values: [{ id: 'e-t29', name: 'Night' }] } };
+ }
+ return { status: 200, body: { values: [] } };
+ });
+
+ const state = await jsmOpsProps.escalation({ displayName: 'Escalation', description: 'd' }).options({ auth: ACCOUNT_AUTH }, propertyContext());
+
+ expect(state.options).toHaveLength(102);
+ expect(state.options).toContainEqual({ label: 'Last (Team 0)', value: 'e-last' });
+ expect(state.options).toContainEqual({ label: 'Night (Team 29)', value: 'e-t29' });
+ expect(requests().filter((request) => request.url === `${ACCOUNT_BASE}/teams/t0/escalations`).map((request) => request.queryParams?.['offset'])).toEqual(['0', '100']);
+ });
+
+ it('pages schedules and shows the time zone', async () => {
+ const full = Array.from({ length: 50 }, (_, index) => ({ id: `s${index}`, name: `S${index}`, timezone: 'UTC' }));
+ mockApi((request) =>
+ request.queryParams?.['offset'] === '0' ? { status: 200, body: { values: full } } : { status: 200, body: { values: [{ id: 'last', name: 'Last' }] } },
+ );
+
+ const state = await jsmOpsProps.schedule({ displayName: 'Schedule', description: 'd' }).options({ auth: ACCOUNT_AUTH }, propertyContext());
+
+ expect(state.options).toHaveLength(51);
+ expect(state.options[0]).toEqual({ label: 'S0 (UTC)', value: 's0' });
+ expect(requests().map((request) => request.queryParams?.['offset'])).toEqual(['0', '50']);
+ });
+
+ it('searches Jira users on the site and keeps only active people', async () => {
+ mockApi((request) =>
+ request.url === `${SITE}/rest/api/3/user/search`
+ ? {
+ status: 200,
+ body: [
+ { accountId: 'acc-1', accountType: 'atlassian', displayName: 'Jane', emailAddress: '[email protected]', active: true },
+ { accountId: 'bot', accountType: 'app', displayName: 'Bot', active: true },
+ { accountId: 'gone', accountType: 'atlassian', displayName: 'Gone', active: false },
+ ],
+ }
+ : undefined,
+ );
+
+ const state = await jsmOpsProps.user({ displayName: 'User', description: 'd' }).options({ auth: ACCOUNT_AUTH }, propertyContext('jan'));
+
+ expect(state.options).toEqual([{ label: 'Jane ([email protected])', value: 'acc-1' }]);
+ const search = findRequest({ method: 'GET', url: `${SITE}/rest/api/3/user/search` });
+ expect(search.queryParams).toEqual({ query: 'jan', maxResults: '50' });
+ expect(search.followRedirects).toBe(false);
+ });
+
+ it('lists responders by the chosen type', async () => {
+ mockApi((request) =>
+ request.url === `${ACCOUNT_BASE}/teams` ? { status: 200, body: { platformTeams: [{ teamId: 't1', teamName: 'Ops' }] } } : undefined,
+ );
+ const dropdown = jsmOpsProps.responder();
+
+ const teamsState = await dropdown.options({ auth: ACCOUNT_AUTH, responderType: 'team' }, propertyContext());
+ const emptyState = await dropdown.options({ auth: ACCOUNT_AUTH, responderType: undefined }, propertyContext());
+
+ expect(teamsState.options).toEqual([{ label: 'Ops', value: 't1' }]);
+ expect(emptyState).toMatchObject({ disabled: true, placeholder: 'Pick a responder type first.' });
+ });
+
+ it('is disabled with a hint on API key connections and before connecting', async () => {
+ const dropdown = jsmOpsProps.teams({ displayName: 'Teams', description: 'd' });
+
+ const keyState = await dropdown.options({ auth: keyAuth(KEY_HOSTS.jsm) }, propertyContext());
+ const noAuth = await dropdown.options({}, propertyContext());
+
+ expect(keyState).toMatchObject({ disabled: true, placeholder: expect.stringContaining('Atlassian Account connection') });
+ expect(noAuth).toMatchObject({ disabled: true });
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('shows the API error in the placeholder instead of throwing', async () => {
+ mockApi(() => ({ status: 403, body: { errors: [{ title: 'Forbidden', code: 'x' }] } }));
+
+ const state = await jsmOpsProps.teams({ displayName: 'Teams', description: 'd' }).options({ auth: ACCOUNT_AUTH }, propertyContext());
+
+ expect(state).toMatchObject({ disabled: true, placeholder: expect.stringContaining('HTTP 403): Forbidden') });
+ });
+});
+
+describe('output schemas', () => {
+ it('matches what the write actions return', async () => {
+ mockApi((request) => {
+ if (request.method === 'POST') {
+ return accepted('req-s');
+ }
+ return processed({ requestId: 'req-s', alertId: 'alert-1', success: true, status: 'ok' });
+ });
+
+ const result = await settle(
+ addTagsAction.run(makeContext<typeof addTagsAction.props>({ auth: ACCOUNT_AUTH, propsValue: { alert: 'alert-1', identifierType: 'id', tags: ['x'] } })),
+ );
+
+ expect(objectKeys(result)).toEqual(fieldKeys(addTagsAction.outputSchema?.fields));
+ expect(fieldKeys(createAlertAction.outputSchema?.fields)).toEqual(objectKeys(result));
+ });
+});
+
+type JsmConnection = AppConnectionValueForAuthProperty<typeof jsmOpsAuth>;
+
+type Request = {
+ method: string;
+ url: string;
+ headers?: Record<string, string>;
+ queryParams?: Record<string, string>;
+ body?: unknown;
+ timeout?: number;
+ followRedirects?: boolean;
+};
+
+type Reply = { status: number; body: unknown };
+
+type Handler = (request: Request) => Reply | undefined;
+
+type ProcessedParams = { requestId: string; alertId: string; success: boolean; status: string };
+
+type Settled<T> = { ok: true; value: T } | { ok: false; error: unknown };
+
+type TriggerContextParams<Props extends InputPropertyMap> = {
+ propsValue: StaticPropsValue<Props>;
+ auth: JsmConnection;
+ store: ReturnType<typeof memoryStore>;
+};
diff --git a/packages/pieces/community/jsm-operations/tsconfig.json b/packages/pieces/community/jsm-operations/tsconfig.json
new file mode 100644
index 00000000000..71bc5814f5d
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "extends": "../../../../tsconfig.base.json",
+ "compilerOptions": {
+ "module": "commonjs",
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "noImplicitOverride": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "files": [],
+ "include": [],
+ "references": [{ "path": "./tsconfig.lib.json" }]
+}
diff --git a/packages/pieces/community/jsm-operations/tsconfig.lib.json b/packages/pieces/community/jsm-operations/tsconfig.lib.json
new file mode 100644
index 00000000000..a648eb45d7f
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/tsconfig.lib.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": ".",
+ "baseUrl": ".",
+ "paths": {},
+ "outDir": "./dist",
+ "declaration": true,
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
+}
diff --git a/packages/pieces/community/jsm-operations/vitest.config.ts b/packages/pieces/community/jsm-operations/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/jsm-operations/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'),
+ },
+ },
+})
diff --git a/tsconfig.base.json b/tsconfig.base.json
index 15bdabf294b..148b2d26e13 100644
--- a/tsconfig.base.json
+++ b/tsconfig.base.json
@@ -712,6 +712,9 @@
"@activepieces/piece-jotform": [
"packages/pieces/community/jotform/src/index.ts"
],
+ "@activepieces/piece-jsm-operations": [
+ "packages/pieces/community/jsm-operations/src/index.ts"
+ ],
"@activepieces/piece-json": [
"packages/pieces/community/json/src/index.ts"
],