Metadata-Version: 2.4
Name: digital-employee-core
Version: 0.1.20
Requires-Python: <3.14,>=3.12
Description-Content-Type: text/markdown
Requires-Dist: email-validator>=2.3.0
Requires-Dist: glaip-sdk[local,memory,pipeline,privacy,skills]<0.11.0,>=0.10.1
Requires-Dist: omegaconf>=2.3.0
Requires-Dist: pydantic<3,>=2
Requires-Dist: requests>=2.32.0
Provides-Extra: dev
Requires-Dist: black>=25.1.0; extra == "dev"
Requires-Dist: coverage>=7.11.0; extra == "dev"
Requires-Dist: faker>=30.3.0; extra == "dev"
Requires-Dist: flake8>=7.3.0; extra == "dev"
Requires-Dist: gl-runner-sdk<0.15,>=0.14; extra == "dev"
Requires-Dist: pre-commit>=4.2.0; extra == "dev"
Requires-Dist: pytest>=8.4.2; extra == "dev"
Requires-Dist: pytest-asyncio>=1.2.0; extra == "dev"
Requires-Dist: pytest-xdist>=3.8.0; extra == "dev"
Requires-Dist: python-dotenv>=1.0.0; extra == "dev"
Requires-Dist: ruff>=0.14.0; extra == "dev"
Provides-Extra: gl-runner
Requires-Dist: gl-runner-sdk<0.15,>=0.14; extra == "gl-runner"

# Digital Employee Core

A Python library for building and managing AI-powered digital employees with support for tools, MCPs (Model Context Protocol), and flexible configuration management.

## Documentation

For comprehensive developer documentation and guides, please refer to the [Digital Employee Developer Documentation](https://gdplabs.gitbook.io/catapa/developer-documentation/digital-employee) on GitBook.

## Prerequisites

### IDE Recommendation

We recommend using one of the following IDEs for developing with this library:

**Option 1: PyCharm**
- Professional Python IDE with comprehensive features
- **Download**: [https://www.jetbrains.com/pycharm/](https://www.jetbrains.com/pycharm/)
- Editions: Professional (paid) or Community (free)

**Option 2: Visual Studio Code (and its forks)**
- Lightweight, extensible editor with Python support
- **VSCode**: [https://code.visualstudio.com/](https://code.visualstudio.com/)
- **Cursor** (AI-powered fork): [https://www.cursor.com/](https://www.cursor.com/)
- **Windsurf** (AI-enhanced fork): [https://codeium.com/windsurf](https://codeium.com/windsurf)
- Install the Python extension for full Python support

### Python Installation

This project supports Python 3.12 and 3.13.

**Installation Instructions:**

- **Linux/WSL**:
  ```bash
  # Ubuntu/Debian
  sudo apt update
  sudo apt install python3.12 python3.12-venv python3.12-dev

  # Fedora
  sudo dnf install python3.12
  ```

- **macOS**:
  ```bash
  # Using Homebrew
  brew install python@3.12
  ```

- **Windows**:
  - Download from [python.org](https://www.python.org/downloads/)
  - Or use [pyenv-win](https://github.com/pyenv-win/pyenv-win) for version management

### Package Manager (uv)

This project uses **uv** as its package manager for fast and reliable dependency management.

**Installation Instructions:**

- **Linux/macOS**:
  ```bash
  curl -LsSf https://astral.sh/uv/install.sh | sh
  ```

- **Windows (PowerShell)**:
  ```powershell
  powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
  ```

- **Alternative (using pip)**:
  ```bash
  pip install uv
  ```

- **Verify Installation**:
  ```bash
  uv --version
  ```

For more information about uv, visit: [https://docs.astral.sh/uv/](https://docs.astral.sh/uv/)

## Setup

### Automated Setup (Recommended)

For a complete automated setup that installs all prerequisites and configures the project, run:

```bash
./setup.sh
```

This script will:
1. Detect your operating system
2. Install Python 3.12 (if not already installed)
3. Install uv package manager (if not already installed)
4. Check/install gcloud CLI (optional, for private packages)
5. Install project dependencies via `make install`
6. Create a `.env` file template

**Note:** The script may require sudo privileges for installing system packages. After running the script, edit the `.env` file with your API credentials (see below).

### Manual Setup

Alternatively, you can set up the project manually:

#### 1. Install Dependencies

```bash
make install
```

#### 2. Configure Environment

Copy the example environment file and add your credentials:

```bash
cp .env.example .env
```

Edit `.env` with your configuration:

```bash
# Required
AIP_API_URL=https://your-ai-platform-url.com
AIP_API_KEY=your-api-key
```

**How to Obtain API Credentials:**

To get the `AIP_API_URL` and `AIP_API_KEY` values, contact **Squad 4 (Claudia)** team:
- **Email**: `koi-claudia@gdplabs.id`

## Tool-Specific Requirements

### E2B Sandbox Tool

This tool requires an `api_key` parameter to be provided. You can either:
- Pass the API key directly as a parameter when using the tool, or
- Set the `E2B_API_KEY` environment variable (the tool will use this automatically if no parameter is provided)

## Configuration Management

### Understanding MCP Configuration Placeholders

The library uses YAML configuration templates (`digital_employee_core/config_templates/mcp_configs.yaml` and `tool_configs.yaml`) that contain **placeholder keys** in dollar-brace format (e.g., `${GOOGLE_CALENDAR_MCP_URL}`). These placeholders need to be replaced with actual values at runtime.

**How Placeholders Work:**

1. **Configuration Template** (in `mcp_configs.yaml`):
```yaml
digital_employee_google_calendar_mcp:
  config:
    url: ${GOOGLE_CALENDAR_MCP_URL}
    allowed_tools: ${GOOGLE_CALENDAR_MCP_ALLOWED_TOOLS:[]}
  authentication:
    type: api-key
    key: X-API-Key
    value: ${GOOGLE_MCP_X_API_KEY}
```

2. **Supply Values** using `DigitalEmployeeConfiguration`:

```python
from digital_employee_core import DigitalEmployeeConfig

configurations = [
    DigitalEmployeeConfig(
        key="GOOGLE_CALENDAR_MCP_URL",
        value="https://api.example.com/calendar/mcp"
    ),
    DigitalEmployeeConfig(
        key="GOOGLE_MCP_X_API_KEY",
        value="your-secret-api-key"
    ),
]
```

3. **Pass to Digital Employee**:

```python
from digital_employee_core import DigitalEmployee
from digital_employee_core.connectors.mcps import google_calendar_mcp

de = DigitalEmployee(
    identity=identity,
    mcps=[google_calendar_mcp],
    configs=configurations  # Placeholder values will be replaced automatically
)

de.deploy()
```

### Available Placeholder Keys

For a complete and up-to-date list of available placeholder keys, refer to the configuration template files:

- **MCP Configurations**: [`digital_employee_core/config_templates/mcp_configs.yaml`](digital_employee_core/config_templates/mcp_configs.yaml)
- **Tool Configurations**: [`digital_employee_core/config_templates/tool_configs.yaml`](digital_employee_core/config_templates/tool_configs.yaml)

Look for keys in the `${PLACEHOLDER_NAME}` format within these files. Common categories include:
- **Google MCPs**: Calendar, Docs, Drive, Mail, Sheets (+ shared `GOOGLE_MCP_X_API_KEY`)
- **GitHub MCP**: URL and API key configurations
- **SQL Tool MCP**: Database connection and authentication settings

### Configuration Priority

Configurations can be supplied in three ways:

1. **At Initialization** (applied during `deploy()`):
```python
de = DigitalEmployee(
    identity=identity,
    mcps=[google_calendar_mcp],
    configurations=configurations
)
```

2. **At Runtime** (applied per `run()` call):
```python
response = de.run(
    message="Check my calendar",
    configurations=runtime_configurations
)
```

3. **Combined** (initialization configs + runtime configs are merged):
```python
# Initialization configs for persistent settings
de = DigitalEmployee(
    identity=identity,
    configurations=base_configurations
)
de.deploy()

# Runtime configs for per-request overrides
response = de.run(
    message="Send email",
    configurations=request_specific_configurations
)
```

## GL Connectors

Mark an MCP as a GL Connector so GL Runner can offer a connection for it, then read the list from the Digital Employee instead of writing it by hand.

```python
from digital_employee_core import as_gl_connector
from glaip_sdk import MCP

my_github = as_gl_connector(
    MCP(name="my_github", transport="http", config={"url": "https://example.com/github/mcp"}),
    name="github",
    required=True,
)

# After building a Digital Employee that uses my_github
digital_employee.get_gl_connectors()
# [{"name": "github", "required": True}]
```

The MCP and the connector have separate names. `my_github` stays as the MCP's name, which agents use to reference it. `name="github"` is the connector name: the GL Connectors integration that GL Runner offers the user a connection for. Several MCPs can share one connector name, and `get_gl_connectors()` lists connector names, not MCP names.

`as_gl_connector` returns a copy, so the MCP you pass is unchanged. The marker is stored in `MCP.metadata` as `{"gl_connector": {"name": "github", "required": True}}`. Pass only `required` to change an MCP that is already marked.

`get_gl_connectors()` reads each pipeline step's agent, its sub-agents, and MCPs added by escalation. A connector used by several MCPs appears once, and it is required if any of them marks it so. Unmarked MCPs, MCPs referenced only by name, and custom pipeline steps without an agent are left out.

Marking changes nothing at run time. A marked MCP authenticates exactly as it did before.

Library MCPs such as `google_mail_mcp` carry no marker, so they are not listed. You can mark one by hand, but it keeps its static key, so GL Runner offers a connection that the run ignores.

## Run Examples

### Basic Example

```bash
uv run python examples/basic_example.py
```

### Subclass Example

```bash
uv run python examples/subclass_example.py
```

## Deploy to GL Runner

The optional `gl-runner` extra deploys an app to GL Runner as a `digital_employee` runnable:

```bash
pip install "digital-employee-core[gl-runner]"
```

```python
from digital_employee_core.gl_runner import deploy_to_gl_runner

deploy_to_gl_runner(
    key="my-app",
    entrypoint=main,  # module-level function in my_app/; deployed as "my_app/main.py:main"
    digital_employee=digital_employee,  # e.g. DigitalEmployeeBuilder()...build(); sends its identity, configs and GL Connectors
    sandbox={"enabled": True, "timeout_seconds": 600},  # optional; run in a GL Runner sandbox
    extra_packages=["my_app_core"],  # optional; installed packages the worker lacks, shipped in the bundle
    env={"MY_MODEL_API_KEY": os.environ["MY_MODEL_API_KEY"]},  # optional; read from context["config"]["env"]
    smoke_message="Hello",  # optional post-deploy run that must succeed
    activation_timeout=960,  # optional; seconds to wait for activation, e.g. while requirements.txt builds
)
```

To check what would be deployed first, pass `dry_run=True`. The bundle is staged in `.local/bundle` and
the existing configurations are read, but nothing is deployed. The returned runnable holds what a real deploy
would send, and its `deploy()` sends it:

```python
runnable = deploy_to_gl_runner(key="my-app", entrypoint=main, digital_employee=digital_employee, dry_run=True)
print(runnable.entrypoint, runnable.bundle_path, sorted(runnable.config))
runnable.deploy()  # when it looks right
```

`runnable.config["configurations"]` and `runnable.config["env"]` hold the existing values decrypted, so do
not print or log them. `smoke_message`, `activation_timeout` and `activation_poll_interval` cannot be combined
with `dry_run`; pass the activation options to `runnable.deploy()` instead.

- The app must use a flat layout: the package is a direct child of the app folder.
- The Digital Employee's `configs` are sent as user-editable runtime configurations, every value
  encrypted (`config_value(..., encrypted=True)`). GL Runner returns them redacted, so users can replace a
  value but not read it back. Values must be JSON-serializable.
  `gl_connectors_de_token`, `gl_connectors_user_token` and `gl_connectors_base_url` (any case) are
  left out, since GL Runner supplies them on every run.
- The runnable's connectors are the Digital Employee's `get_gl_connectors()` (see [GL Connectors](#gl-connectors)).
  Each deploy replaces the runnable's connector list, so a connector the Digital Employee no longer uses is removed.
- Every deploy enables GL Runner's run artifacts (`run_artifacts: {"enabled": true}`) and external
  human-in-the-loop decisions (`hitl: {"external": true}`). Neither changes a run until the app uses it:
  it writes an artifact, or awaits `context["__gl_hitl_wait"]`.
- On redeploy, configuration values already on the runnable (which users may have edited) are kept, and
  resent encrypted.
- `sandbox` sets GL Runner's `sandbox` block (`enabled`, plus optional `backend` `opensandbox`/`e2b`
  and `timeout_seconds`). GL Runner stops sandboxed runs after 30 seconds by default, so set
  `timeout_seconds` for agent runs. With `sandbox=None` a redeploy keeps the runnable's current
  block; pass `{"enabled": False}` to turn sandboxing off.
- `smoke_message` triggers one run after the deploy and raises unless it succeeds. The deploy waits
  120 seconds for it, plus the sandbox's `timeout_seconds` when the sandbox is enabled, and raises
  `TimeoutError` past that. Only the run ID and status are logged, never the run result.
- To install extra packages in the sandbox, ship a `requirements.txt` in the app package, beside the
  entrypoint (`my_app/requirements.txt`). It is copied to the bundle root, where GL Runner reads it,
  validates each line and builds the packages into a sandbox template during the deploy (see GL Runner's
  [Sandbox Custom Dependencies](https://gdplabs.gitbook.io/sdk/gl-runner/tutorials/sandbox-custom-dependencies)).
  That needs the sandbox enabled, given here or kept from the server; otherwise the deploy is refused.
  A first build can take up to 15 minutes, so raise `activation_timeout` (the gl-runner-sdk default is 120
  seconds), e.g. to 960. A `requirements.txt` in the app folder is not bundled.
- `env` sets GL Runner's `config.env`, for values the entrypoint reads from `context["config"]["env"]`,
  such as a secret the app does not take as a config yet. Values must be strings and are sent encrypted.
  The env is owned by the deploy: a given env replaces the runnable's, `{}` clears it, and with `env=None`
  a redeploy keeps the runnable's current env.
- `extra_packages` lists top-level import names of packages installed here but not on the GL Runner
  worker, such as a sibling `*-core` package installed from a local path. Each is copied from where it is
  installed into the bundle root, next to the app package. Their own dependencies are not copied.
- Schedules are not managed by this function; existing schedules on the runnable are left as they are.
- `base_url`/`api_key` default to `GL_RUNNER_BASE_URL`/`GL_RUNNER_API_KEY`.

### Run Metadata

When GLChat calls the runnable, it sends run metadata (`user_id`, `email`, `tenant_id`, `conversation_id`,
`message_id`, `chatbot_id`, `delegation_token`, ...) in `payload["metadata"]`. Pass it to `invoke()`:

```python
from digital_employee_core.integrations import extract_chat_history, extract_message


async def main(payload: dict, context: dict) -> dict:
    input_data = payload["input"]
    result = await digital_employee.invoke(
        extract_message(input_data),
        chat_history=extract_chat_history(input_data),
        metadata=payload.get("metadata"),
    )
    return {"output": result["agent_response"]}
```

Return only `result["agent_response"]`. The full result is the pipeline state: it also holds
`run_kwargs["metadata"]`, which has the token, and it is not JSON-serializable when the token is a `SecretStr`.

- The metadata is put in `run_kwargs` (`state["run_kwargs"]["metadata"]`) and forwarded to the agent. Tools read it
  from their LangGraph config: `config["metadata"]`.
- DE Core does not log it or add it to the LLM prompt. The caller's dict is not changed.
- aip-agents copies the run metadata into the metadata of each streamed event. `invoke()` removes it from the
  events it sends to `event_emitter`. It removes a field only when the value matches the run metadata, so an
  event keeps its own fields, such as `agent_name` or `kind`, when your metadata uses the same key.
- Read the token with `read_delegation_token(config)`. `delegation_token` is a `pydantic.SecretStr` when the
  run stays in process (`local=True`, or `local=False` and no pipeline agent has an id), so it shows as
  `**********` in reprs and traces. LangGraph checkpoint metadata copies plain strings and skips a `SecretStr`, so
  the token is left out on that path. When `local=False` and a pipeline agent is deployed, it is a plain string,
  because the AIP run API serializes the metadata to JSON. The helper returns the raw string for both, or `None`:

  ```python
  from langchain_core.runnables import RunnableConfig
  from langchain_core.tools import BaseTool

  from digital_employee_core.integrations import read_delegation_token


  class MyTool(BaseTool):
      def _run(self, query: str, config: RunnableConfig = None) -> str:
          token = read_delegation_token(config)
          ...
  ```

- If `memory_user_id` is not given, `metadata["user_id"]` is used as the memory user. It has no effect when
  memory is disabled. aip-agents also puts `memory_user_id` into `config["metadata"]`, so tools see it.
- If `enable_pii` is not given, a boolean `metadata["enable_pii"]` turns PII masking on or off for the run.
  A non-boolean value is ignored.
- Some keys that tools get on the AIP path are not sent on this path: `bound_agent_id`, `bound_account_id`,
  `agent_name` and `run_type` (added by the AIP backend), and `agent` (sent by GLChat only to AIP agents).
  A tool that reads them gets no value here.

## Run Tests

```bash
# Run unit tests (excludes integration tests)
make test

# Run with verbose output
uv run pytest -v

# Run with coverage report
make coverage

# Run with coverage HTML report
make coverage FORMAT=html
# Open htmlcov/index.html in browser

# Run specific test file
uv run pytest tests/digital_employee/test_core.py
```
