> For the complete documentation index, see [llms.txt](https://docs.eximee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow/platform-services/operacje-na-procesach.md).

# Process operations and data access

Interface `api.process.v1` provides mechanisms for interacting with the Eximee platform's process engine (BPM). It enables asynchronous control of process flow (by sending messages) and dynamic management of permissions for cases in the user's case list.

### API

```typescript
interface ProcessApi {
    v1: {
        /* Sends messages to the process, 
         * optionally, process variables can be passed.
         */
        correlateMessage(messageName: string, processVariables?: { [key: string]: string });

        /* Sets the list of groups 
         * that have access to the process instance in the case list
         */
        setAccessGroups(groupNames: string[]);

        /* Starts a new process based on the process definition key.
         * Optionally, a business key and process variables can be passed. 
         * Returns the process instance ID.
         */
        startProcess(definitionKey: string, data?: StartProcessOptions): string;

        /* Allows you to reference another process by its instance ID. 
         * Enables operations to be performed on that process, 
         * such as sending messages or setting access groups.
         */
        byInstanceId(processInstanceId): ProcessApi.v1;

        /* Returns information about the process, 
         * such as its key, name, instance ID, and business key.
         */
        getProcessInfo(): ProcessInfo;
        /* Returns information about the current user task, 
         * such as its key, name, and ID.
         */
        getUserTaskInfo(): UserTaskInfo;

        // Returns the list of incidents for the process instance (the current one or the one specified by byInstanceId)
        getIncidents(): Incident[];

        // Retries the external task; retries specifies the number of retries (default: 1)
        retryExternalTask(externalTaskId: string, retries?: number): void;
    }
}

interface StartProcessOptions {
    // Optional business key for the new process instance
    businessKey?: string;

    // Optional process variables for the new process instance
    variables?: { [key: string]: string };
}

interface ProcessInfo {
    // Returns the process instance ID
    id(): string;

    // Returns the process definition key
    definitionKey(): string;

    // Returns the process name, if set
    name(): string | null;

    // Returns the process business key, if set
    businessKey(): string | null;
}

interface UserTaskInfo {
    // Returns the user task ID
    id(): string;

    // Returns the user task definition key
    definitionKey(): string;

    // Returns the user task name
    name(): string;
}

interface Incident {
    // Returns the incident ID
    id(): string;

    // Returns the incident type: "failedJob", "failedExternalTask", or a custom type
    incidentType(): string;

    // Returns the ID of the item affected by the incident: the external task (for "failedExternalTask") or the job (for "failedJob")
    configuration(): string | null;

    // Returns the error message
    incidentMessage(): string | null;

    // Returns the date and time when the incident occurred in the format yyyy-MM-dd'T'HH:mm:ss.SSSZ, e.g. 2026-01-23T14:42:45.000+0200
    incidentTimestamp(): string;

    // Returns the process definition ID
    processDefinitionId(): string | null;

    // Returns the process instance ID
    processInstanceId(): string | null;

    // Returns the ID of the execution (path) in the process instance
    executionId(): string | null;

    // Returns the process step where the incident is visible
    activityId(): string | null;

    // Returns the process step where the error actually occurred
    failedActivityId(): string | null;

    // Returns the ID of the incident that directly caused this incident
    causeIncidentId(): string;

    // Returns the ID of the root incident; if it is equal to id(), this incident is the root incident
    rootCauseIncidentId(): string;

    // Returns the job definition ID (for "failedJob")
    jobDefinitionId(): string | null;

    // Returns the tenant ID, if multi-tenancy is used
    tenantId(): string | null;

    // Returns a note manually added to the incident
    annotation(): string | null;
}
```

### Execution context

The API is available from the `api.process.v1` object and operates in the context of the current process.\
Process ID:

* For forms launched by the platform as part of a process, this is populated **automatically**.
* For resumed processes (e.g., via the endpoint `#/process`), the process instance ID must be provided.
* For script tasks — **required unconditionally**.

***

### Reference to another process

| Method                            | Description                                                                                                                                        |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `byInstanceId(processInstanceId)` | Changes the call context to the specified process instance. Returns an object that allows process methods to be called (e.g., `correlateMessage`). |

{% hint style="danger" %}
**Security warning:** Referencing an external process instance can cause errors. Always make sure that the provided `processInstanceId` comes from a **trusted source** (e.g., from a secure registry or an internal variable).
{% endhint %}

The API for this use case is available at:

```typescript
api.process.v1.byInstanceId(processInstanceId: string)
```

where `processInstanceId` is the ID of the process instance you want to reference.

{% hint style="warning" %}
**Note:** The `setAccessGroups()` **function does not support** being called with `api.process.v1.byInstanceId`.
{% endhint %}

{% hint style="info" %}
**Availability:** The API is available only in:

* scripts,
* script validators,
* script tasks.
  {% endhint %}

## Usage examples

### 1. `correlateMessage()`

| Method                                              | Description                                                                                                           |
| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `correlateMessage(messageName, [processVariables])` | Sends a message named `messageName`. Optionally, it accepts a key-value map representing process variables to update. |

**Sending a message named `MESSAGE_NAME`**

```typescript
function callService(context) {
  api.process.v1.correlateMessage("MESSAGE_NAME");
}
```

**Sending a message and setting a process variable**

```typescript
function callService(context) {
  api.process.v1.correlateMessage("MESSAGE_NAME", { "zmienna": "wartość" });
}
```

**Sending a message to a specific process**

```typescript
function callService(context) {
  const processInstanceId = "...";
  api.process.v1.byInstanceId(processInstanceId).correlateMessage("MESSAGE_NAME");
}
```

**Sending a message to a specific process with multiple variables**

```typescript
function callService(context) {
  const processInstanceId = "...";
  api.process.v1.byInstanceId(processInstanceId).correlateMessage("MESSAGE_NAME", { 
    "zmiennaA": "wartość1",
    "zmiennaB": "wartość2",
    "zmiennaC": "wartość3"
  });
}
```

### 2. `setAccessGroups()`

| Method                                    | Description                                                                    |
| ----------------------------------------- | ------------------------------------------------------------------------------ |
| `permissions.setAccessGroups(groupNames)` | Sets the list of groups that can access the process instance in the case list. |

**How it works**

The method **grants additional access** to view the case (process instance) in the case list.

* The group must already have permission to access the list: `feature_process_list` (case list) or `feature_case_list` (all cases list).
* The method **overwrites all previously assigned groups**.

{% hint style="warning" %}
If the group `GROUP_TEST`, which previously had access, is followed by the code below, access will be granted to **only the groups specified** in the method (`GROUP_1` and `GROUP_2`).
{% endhint %}

**Usage example**

```typescript
function callService(context) {
  api.process.v1.setAccessGroups(["GROUP_1", "GROUP_2"]);
}
```

To reset the access groups, overwrite the existing values with an empty list.

```typescript
function callService(context) {
    // ...
    api.process.v1.setAccessGroups([])
    // ...
}
```

***

### Starting a new process

The API also allows you to start a new process. When using this functionality, account for the possibility that scripts may be called multiple times and ensure that the operation is idempotent.

| Method                                | Description                                                                                                                                              |
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `startProcess(definitionKey, [data])` | Starts a new process based on the process definition key. You can optionally pass a business key and process variables. Returns the process instance ID. |

Take care not to start multiple process instances as a result of a script being called more than once (for example, when a user refreshes the page, a script is attached multiple times, or the script is attached to an event that may be triggered repeatedly).

```typescript
function callService(context) {
    // ...
    api.process.v1.startProcess(definitionKey: string, data: {businessKey?: string, variables: { [key: string]: string }})
    // ...
}
```

**Usage examples**

Starting a process with a business key and process variables:

```typescript
function callService(context) {
  const processInstanceId = api.process.v1.startProcess("proces_demo", {
    businessKey: "demo_123",
    variables: {
      "zmiennaA": "wartość1",
      "zmiennaB": "wartość2"
    }
  });
}
```

Starting a process without additional parameters:

```typescript
function callService(context) {
  const processInstanceId = api.process.v1.startProcess("proces_demo");
}
```

### Refusal to start with another case's number

The process started by `startProcess` is a separate case, not a subprocess of the case from which the script was called. If the specified `businessKey` is already assigned to another case, including the case that called the script, the platform refuses to start the process and raises an exception with the code `businessKeyAlreadyExists` — see [Case number uniqueness](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/proces-biznesowy/unikalnosc-numeru-sprawy.md).

You can read the refusal code in the `catch` block using `e.javaException.getCode()`:

```typescript
try {
  api.process.v1.startProcess("proces_demo", { businessKey: "demo_123" });
} catch (e) {
  if (!e.javaException || String(e.javaException.getCode()) !== "businessKeyAlreadyExists") {
    throw e;
  }
  // case with number demo_123 already exists
}
```

### Retrieving process information

The API lets you retrieve information about the current process, such as its key, name, instance ID, and business key.

| Method             | Description                                                                                  |
| ------------------ | -------------------------------------------------------------------------------------------- |
| `getProcessInfo()` | Returns information about the process, such as its key, name, instance ID, and business key. |

**Usage examples**

```typescript
function callService(context) {
    const processInfo = api.process.v1.getProcessInfo();
    Logger.info("Get process info: {}", processInfo);

    return [{
        'processId': processInfo.id(),
        'processDefinitionKey': processInfo.definitionKey(),
        'processName': processInfo.name(),
        'processBusinessKey': processInfo.businessKey()
    }];
}
```

### Retrieving user task information

The API also lets you retrieve information about the current user task, such as its key, name, and ID.

| Method              | Description                                                                     |
| ------------------- | ------------------------------------------------------------------------------- |
| `getUserTaskInfo()` | Returns information about the current user task, such as its key, name, and ID. |

```typescript
function callService(context) {
    const userTaskInfo = api.process.v1.getUserTaskInfo();
    Logger.info("Get user task info: {}", userTaskInfo);

    return [{
        'userTaskId': userTaskInfo.id(),
        'userTaskDefinitionKey': userTaskInfo.definitionKey(),
        'userTaskName': userTaskInfo.name()
    }];
}
```

***

#### Retrieving process incidents

The method `getIncidents()` returns a list of incidents for a process instance. An incident occurs when the process engine cannot execute a process step, for example, when an asynchronous task or external task has exhausted its retries. If the instance has no incidents, the method returns an empty list.

* `api.process.v1.getIncidents()` — returns incidents for the current process instance.
* `api.process.v1.byInstanceId(processInstanceId).getIncidents()` — returns incidents for the specified process instance.

The structure of the returned object is described in the `Incident` interface in the [API](#api) section and corresponds to the `IncidentDto` object in the [EximeeBPMS REST API](https://docs.eximeebpms.org/rest/1.0/#tag/Incident/operation/getIncidents). Syntax hints in the script editor include the method call, but do not suggest methods of the returned objects.

{% hint style="info" %}
The method `configuration()` returns the ID of the element associated with the incident: for the `failedExternalTask` type, this is the ID of the external task that you pass to the `retryExternalTask()`method. For the `failedJob` type, this is the job ID—retrying jobs is not currently available in the API.
{% endhint %}

**Usage examples**

Returning the number of incidents for the current process instance:

```typescript
function callService(context) {
    const incidents = api.process.v1.getIncidents();

    return [{
        'incidentsCount': incidents.length
    }];
}
```

Returning the number of incidents for the process whose ID was passed to the script as the input parameter `processInstanceId`:

```typescript
function callService(context) {
    const processInstanceId = context.getFirstParameter('processInstanceId');
    const incidents = api.process.v1.byInstanceId(processInstanceId).getIncidents();

    incidents.forEach(incident => {
        Logger.info("Incident {} ({}) on activity {}: {}",
            incident.id(), incident.incidentType(), incident.failedActivityId(), incident.incidentMessage());
    });

    return [{
        'incidentsCount': incidents.length
    }];
}
```

***

#### Retrying an external task

Method `retryExternalTask(externalTaskId, retries)` sets the number of retries for an external task, causing the process engine to retry its execution and resolve the associated incident.

* `externalTaskId` — the external task ID. For an incident of type `failedExternalTask` it is returned by the `configuration()`.
* `retries` — the number of retries. This parameter is optional; the default value is `1`. The value must be greater than or equal to 1; specifying a lower value results in an error.

{% hint style="warning" %}
Before retrying, make sure the cause of the error has been resolved (for example, the external service is available again). Otherwise, the external task will fail again and the incident will be raised again.
{% endhint %}

**Usage examples**

Retry all external tasks with incidents in the specified process instance:

```typescript
function callService(context) {
    const processInstanceId = context.getFirstParameter('processInstanceId');
    const incidents = api.process.v1.byInstanceId(processInstanceId).getIncidents();

    incidents
        .filter(incident => incident.incidentType() === 'failedExternalTask')
        .forEach(incident => api.process.v1.retryExternalTask(incident.configuration()));
}
```

Retry an external task with three execution attempts:

```typescript
function callService(context) {
    const externalTaskId = "...";
    api.process.v1.retryExternalTask(externalTaskId, 3);
}
```

{% hint style="info" %}
**See also:** For important information, see the [**Case List Configuration**](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/interfejs-uzytkownika/eximee-dashboard/konfiguracja/lista-spraw.md) and [**Eximee Dashboard Permissions**](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/interfejs-uzytkownika/eximee-dashboard/konfiguracja/uprawnienia.md).
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow/platform-services/operacje-na-procesach.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
