Metadata-Version: 2.4
Name: synapse-sdk
Version: 2026.1.74
Summary: synapse sdk
Author-email: datamaker <developer@datamaker.io>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.0.0
Requires-Dist: requests>=2.28.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: aiohttp>=3.8.0
Requires-Dist: pyyaml>=6.0.0
Requires-Dist: pyjwt>=2.10.1
Requires-Dist: websocket-client>=1.6.0
Requires-Dist: websockets>=12.0
Requires-Dist: typer>=0.15.0
Requires-Dist: rich>=14.0.0
Requires-Dist: questionary>=2.1.0
Requires-Dist: jinja2>=3.1.0
Requires-Dist: pillow>=10.0.0
Requires-Dist: tqdm>=4.65.0
Requires-Dist: universal-pathlib>=0.3.7
Requires-Dist: s3fs>=2024.0.0
Requires-Dist: gcsfs>=2024.0.0
Requires-Dist: sshfs>=2024.0.0
Provides-Extra: all
Requires-Dist: ray[all]==2.50.0; extra == "all"
Requires-Dist: mcp>=1.25.0; extra == "all"
Requires-Dist: openpyxl>=3.1.0; extra == "all"
Requires-Dist: setuptools<82; extra == "all"
Requires-Dist: hyperopt==0.2.5; extra == "all"
Requires-Dist: optuna; extra == "all"
Provides-Extra: test
Requires-Dist: pytest>=7.0.0; extra == "test"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "test"
Requires-Dist: pytest-cov>=4.0.0; extra == "test"
Requires-Dist: pytest-mock>=3.10.0; extra == "test"
Requires-Dist: pytest-timeout>=2.1.0; extra == "test"
Requires-Dist: pytest-xdist>=3.0.0; extra == "test"
Requires-Dist: pytest-html>=3.1.0; extra == "test"
Requires-Dist: pytest-json-report>=1.5.0; extra == "test"
Requires-Dist: requests-mock>=1.10.0; extra == "test"
Requires-Dist: responses>=0.25.0; extra == "test"
Requires-Dist: respx>=0.20.0; extra == "test"
Provides-Extra: dev
Requires-Dist: pre-commit; extra == "dev"
Requires-Dist: ruff>=0.8.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: pydoc-markdown>=4.8.0; extra == "docs"
Dynamic: license-file

# Synapse SDK v2

> To be merged into [synapse-sdk](https://github.com/datamaker-kr/synapse-sdk) after development

## Table of Contents

- [Installation](#installation)
- [Migration Guide](#migration-guide)
  - [Plugin Utils](#plugin-utils)
  - [Plugin Types](#plugin-types)
  - [Pre-Annotation Actions](#pre-annotation-actions)
  - [Plugin Discovery](#plugin-discovery)
  - [Storage Utils](#storage-utils)
  - [Dataset Converters](#dataset-converters)
- [API Reference](#api-reference)
  - [get_plugin_actions](#get_plugin_actions)
  - [get_action_method](#get_action_method)
  - [get_action_config](#get_action_config)
  - [read_requirements](#read_requirements)
  - [run_plugin](#run_plugin)
  - [PluginDiscovery](#plugindiscovery)
  - [Storage](#storage)
- [Action Base Classes](#action-base-classes)
  - [BaseTrainAction](#basetrainaction)
  - [BaseExportAction](#baseexportaction)
  - [BaseUploadAction](#baseuploadaction)
- [Agent Client Streaming](#agent-client-streaming)

---

## Installation

```bash
pip install synapse-sdk
```

---

## Migration Guide

### Plugin Utils

**Old (synapse-sdk v1):**
```python
from synapse_sdk.plugins.utils import get_action_class, get_plugin_actions, read_requirements

# Get run method by loading the action class
action_method = get_action_class(config['category'], action).method
```

**New (synapse-sdk v2):**
```python
from synapse_sdk.plugins.utils import get_action_method, get_plugin_actions, read_requirements

# Get run method directly from config (no class loading needed)
action_method = get_action_method(config, action)
```

### Plugin Types

**Old:**
```python
from synapse_sdk.plugins.enums import PluginCategory
from synapse_sdk.plugins.base import RunMethod
```

**New:**
```python
from synapse_sdk.plugins.enums import PluginCategory, RunMethod
```

**Provider renames:**
- `file_system` -> `local` (alias `file_system` still works)
- `FileSystemStorage` -> `LocalStorage`
- `GCPStorage` -> `GCSStorage`

### Pre-Annotation Actions

**Old (synapse-sdk v1):**
```python
from synapse_sdk.plugins.categories.pre_annotation.actions.to_task import ToTaskAction

class AnnotationToTask:
    def convert_data_from_file(...):
        ...

    def convert_data_from_inference(...):
        ...

action = ToTaskAction(run=run_instance, params=params)
result = action.start()
```

**New (synapse-sdk v2):**
```python
from synapse_sdk.plugins.actions.to_task import ToTaskAction

class ToTask(ToTaskAction):
    action_name = 'to_task'

    def convert_data_from_file(...):
        ...

    def convert_data_from_inference(...):
        ...
```

Update `config.yaml` to use `to_task` and point the entrypoint to your `ToTask` subclass.

### Dataset Converters

**Old (synapse-sdk v1):**
```python
from synapse_sdk.utils.converters import get_converter, FromDMToYOLOConverter
```

**New (synapse-sdk v2):**
```python
from synapse_sdk.utils.converters import get_converter, FromDMToYOLOConverter

# Factory function for all format conversions
converter = get_converter('dm_v2', 'yolo', root_dir='/data/dm_dataset', is_categorized=True)
converter.convert()
converter.save_to_folder('/data/yolo_output')

# Supported format pairs:
# - DM (v1/v2) ↔ YOLO
# - DM (v1/v2) ↔ COCO
# - DM (v1/v2) ↔ Pascal VOC
```

**Breaking change**: Direct imports from `synapse_sdk.utils.converters` no longer work. Use `synapse_sdk.utils.converters` instead. For backward compatibility, re-exports are available through `synapse_sdk.plugins.datasets`.

**API changes**:
- Parameter `is_categorized_dataset` renamed to `is_categorized`
- `root_dir` is now a `Path` object (but str still accepted)
- Added `DatasetFormat` enum for type-safe format specification

**Example: Convert DM v2 to YOLO with splits**:
```python
from synapse_sdk.utils.converters import get_converter

converter = get_converter(
    source='dm_v2',
    target='yolo',
    root_dir='/data/dm_dataset',
    is_categorized=True,  # has train/valid/test splits
)

# Perform conversion
result = converter.convert()

# Save to output directory
converter.save_to_folder('/data/yolo_output')
```

**Example: Convert YOLO to DM v2**:
```python
converter = get_converter(
    source='yolo',
    target='dm_v2',
    root_dir='/data/yolo_dataset',
    is_categorized=False,
)
converter.convert()
converter.save_to_folder('/data/dm_output')
```

---

## API Reference

### get_plugin_actions

Extract action names from plugin configuration.

```python
from synapse_sdk.plugins.utils import get_plugin_actions

# From dict
actions = get_plugin_actions({'actions': {'train': {}, 'export': {}}})
# Returns: ['train', 'export']

# From PluginConfig
actions = get_plugin_actions(plugin_config)

# From path
actions = get_plugin_actions('/path/to/plugin')  # reads config.yaml
```

### get_action_method

Get the execution method (job/task/serve_application) for an action.

```python
from synapse_sdk.plugins.utils import get_action_method
from synapse_sdk.plugins.enums import RunMethod

method = get_action_method(config, 'train')
if method == RunMethod.JOB:
    # Create job record, run async
    pass
elif method == RunMethod.TASK:
    # Run as Ray task
    pass
```

### get_action_config

Get full configuration for a specific action.

```python
from synapse_sdk.plugins.utils import get_action_config

config = get_action_config(plugin_config, 'train')
# Returns: {'name': 'train', 'method': 'job', 'entrypoint': '...', ...}
```

### read_requirements

Parse a requirements.txt file.

```python
from synapse_sdk.plugins.utils import read_requirements

reqs = read_requirements('/path/to/requirements.txt')
# Returns: ['numpy>=1.20', 'torch>=2.0'] or None if file doesn't exist
```

### run_plugin

Execute plugin actions with automatic discovery.

```python
from synapse_sdk.plugins.runner import run_plugin

# Auto-discover from Python module path
result = run_plugin('plugins.yolov8', 'train', {'epochs': 10})

# Auto-discover from config.yaml path
result = run_plugin('/path/to/plugin', 'train', {'epochs': 10})

# Execution modes
result = run_plugin('plugin', 'train', params, mode='local')  # Current process (default)
result = run_plugin('plugin', 'train', params, mode='task')   # Ray Actor (fast startup)
job_id = run_plugin('plugin', 'train', params, mode='job')    # Ray Job API (async)

# Explicit action class (skips discovery)
result = run_plugin('yolov8', 'train', {'epochs': 10}, action_cls=TrainAction)
```

**Option 1: Define actions with `@action` decorator (recommended for Python modules):**

```python
# plugins/yolov8.py
from synapse_sdk.plugins.decorators import action
from pydantic import BaseModel

class TrainParams(BaseModel):
    epochs: int = 10
    batch_size: int = 32

@action(name='train', description='Train YOLOv8 model', params=TrainParams)
def train(params: TrainParams, ctx):
    # Training logic here
    return {'accuracy': 0.95}

@action(name='infer')
def infer(params, ctx):
    # Inference logic
    return {'predictions': [...]}

# Run it:
# run_plugin('plugins.yolov8', 'train', {'epochs': 20})
```

**Option 2: Define actions with `BaseAction` class:**

```python
# plugins/yolov8.py
from synapse_sdk.plugins.action import BaseAction
from pydantic import BaseModel

class TrainParams(BaseModel):
    epochs: int = 10

class TrainAction(BaseAction[TrainParams]):
    action_name = 'train'
    params_model = TrainParams

    def execute(self):
        # self.params contains validated TrainParams
        # self.ctx contains RuntimeContext (logger, env, job_id)
        return {'accuracy': 0.95}

# Run it:
# run_plugin('plugins.yolov8', 'train', {'epochs': 20})
```

**Option 3: Define actions with `config.yaml` (recommended for packaged plugins):**

```yaml
# plugin/config.yaml
name: YOLOv8 Plugin
code: yolov8
version: 1.0.0
category: neural_net
description: YOLOv8 object detection plugin

actions:
  train:
    entrypoint: plugin.train.TrainAction   # or plugin.train:TrainAction
    method: job
    description: Train YOLOv8 model

  infer:
    entrypoint: plugin.inference.InferAction
    method: task
    description: Run inference

  export:
    entrypoint: plugin.export.export_model
    method: task
```

```python
# Run from config path:
run_plugin('/path/to/plugin', 'train', {'epochs': 20})
```

**Entrypoint formats:**
- Dot notation: `plugin.train.TrainAction` (module.submodule.ClassName)
- Colon notation: `plugin.train:TrainAction` (module.submodule:ClassName)

### PluginDiscovery

Comprehensive plugin introspection.

```python
from synapse_sdk.plugins.discovery import PluginDiscovery

# Load from config.yaml
discovery = PluginDiscovery.from_path('/path/to/plugin')

# Or introspect a Python module
discovery = PluginDiscovery.from_module(my_module)

# Available methods
discovery.list_actions()           # ['train', 'export']
discovery.has_action('train')      # True
discovery.get_action_method('train')  # RunMethod.JOB
discovery.get_action_config('train')  # ActionConfig instance
discovery.get_action_class('train')   # Loads class from entrypoint
```

### Storage

Storage utilities for working with different storage backends.

**Installation for cloud providers:**
```bash
pip install synapse-sdk[all]    # Includes S3, GCS, SFTP support + Ray
```

**Available providers:**
- `local` / `file_system` - Local filesystem
- `s3` / `amazon_s3` / `minio` - S3-compatible storage
- `gcs` / `gs` / `gcp` - Google Cloud Storage
- `sftp` - SFTP servers
- `http` / `https` - HTTP file servers

**Basic usage:**
```python
from synapse_sdk.utils.storage import (
    get_storage,
    get_pathlib,
    get_path_file_count,
    get_path_total_size,
)

# Get storage instance
storage = get_storage({
    'provider': 'local',
    'configuration': {'location': '/data'}
})

# Upload a file
url = storage.upload(Path('/tmp/file.txt'), 'uploads/file.txt')

# Check existence
exists = storage.exists('uploads/file.txt')

# Get pathlib object for path operations
path = get_pathlib(config, '/uploads')
for file in path.rglob('*.txt'):
    print(file)

# Get file count and total size
count = get_path_file_count(config, '/uploads')
size = get_path_total_size(config, '/uploads')
```

**Provider configurations:**

```python
# Local filesystem
{'provider': 'local', 'configuration': {'location': '/data'}}

# S3/MinIO
{'provider': 's3', 'configuration': {
    'bucket_name': 'my-bucket',
    'access_key': 'AKIAIOSFODNN7EXAMPLE',
    'secret_key': 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
    'region_name': 'us-east-1',
    'endpoint_url': 'http://minio:9000',  # optional, for MinIO
}}

# Google Cloud Storage
{'provider': 'gcs', 'configuration': {
    'bucket_name': 'my-bucket',
    'credentials': '/path/to/service-account.json',
}}

# SFTP
{'provider': 'sftp', 'configuration': {
    'host': 'sftp.example.com',
    'username': 'user',
    'password': 'secret',  # or 'private_key': '/path/to/id_rsa'
    'root_path': '/data',
}}

# HTTP
{'provider': 'http', 'configuration': {
    'base_url': 'https://files.example.com/uploads/',
    'timeout': 60,
}}
```

---

## Changes from v1

### Breaking Changes

These changes **require code updates** when migrating from v1:

| v1 | v2 | Migration |
|----|----|----|
| `get_action_class(category, action)` | `get_action_method(config, action)` | Pass config dict instead of category string |
| `action_class.method` | `get_action_method(config, action)` | Method is now read from config, not class attribute |
| `@register_action` decorator | Removed | Define actions in `config.yaml` or use `PluginDiscovery.from_module()` |
| `_REGISTERED_ACTIONS` global | Removed | Use `PluginDiscovery` for action introspection |
| `get_storage('s3://...')` URL strings | Dict-only config | Use `get_storage({'provider': 's3', 'configuration': {...}})` |
| `from ... import FileSystemStorage` | `from ... import LocalStorage` | Class renamed |
| `from ... import GCPStorage` | `from ... import GCSStorage` | Class renamed |
| Subclassing `BaseStorage` ABC | Implement `StorageProtocol` | Use structural typing (duck typing) instead of inheritance |

### Non-Breaking Changes

These changes are **backwards compatible** - existing code continues to work:

| Feature | Notes |
|---------|-------|
| Provider alias `file_system` | Still works, maps to `LocalStorage` |
| Provider aliases `gcp`, `gs` | Still work, map to `GCSStorage` |
| `get_plugin_actions()` | Same API |
| `read_requirements()` | Same API |
| `get_pathlib()` | Same API |
| `get_path_file_count()` | Same API |
| `get_path_total_size()` | Same API |

### New Features in v2

| Feature | Description |
|---------|-------------|
| `PluginDiscovery` | Discover actions from config files or Python modules |
| `PluginDiscovery.from_module()` | Auto-discover `@action` decorators and `BaseAction` subclasses |
| `StorageProtocol` | Protocol-based interface for custom storage implementations |
| `HTTPStorage` provider | New provider for HTTP file servers |
| Plugin Upload utilities | `archive_and_upload()`, `build_and_upload()`, `download_and_upload()` |
| File utilities | `calculate_checksum()`, `create_archive()`, `create_archive_from_git()` |
| `AsyncAgentClient` | Async client with WebSocket/HTTP streaming for job logs |
| `tail_job_logs()` | Stream job logs with protocol auto-selection |
| `BaseTrainAction` | Training base class with dataset/model helpers |
| `BaseExportAction` | Export base class with filtered results helper |
| `BaseUploadAction` | Upload base class with step-based workflow and rollback |
| `i18n` module | Internationalization support for log messages |
| CLI `--lang` option | Language selection for `synapse plugin run` command |

---

## Internationalization (i18n)

Log messages can be displayed in multiple languages. Currently supported: English (`en`) and Korean (`ko`).

### CLI Usage

```bash
# Run with Korean log messages
synapse plugin run train --lang=ko --params '{"epochs": 10}'

# Short form
synapse plugin run train -l ko

# Works with all execution modes
synapse plugin run train --mode local --lang=ko
synapse plugin run train --mode task --lang=ko
synapse plugin run train --mode job --lang=ko
```

### Programmatic Usage

**Using Executors:**
```python
from synapse_sdk.plugins.executors.local import LocalExecutor
from synapse_sdk.plugins.executors.ray.task import RayActorExecutor
from synapse_sdk.plugins.executors.ray.jobs_api import RayJobsApiExecutor

# LocalExecutor with Korean
executor = LocalExecutor(env={'DEBUG': 'true'}, language='ko')
result = executor.execute(TrainAction, {'epochs': 10})

# RayActorExecutor with Korean
executor = RayActorExecutor(
    working_dir='/path/to/plugin',
    num_gpus=1,
    language='ko',
)

# RayJobsApiExecutor with Korean
executor = RayJobsApiExecutor(
    dashboard_address='http://localhost:8265',
    working_dir='/path/to/plugin',
    language='ko',
)
```

**Custom i18n Messages in Plugins:**

Plugin developers can provide multi-language messages using `LocalizedMessage` or dict format:

```python
from synapse_sdk.i18n import LocalizedMessage

# Using LocalizedMessage
msg = LocalizedMessage({
    'en': 'Processing {count} files',
    'ko': '{count}개의 파일을 처리 중',
})

# Log with i18n support
self.ctx.log_message(
    LogMessageCode.CUSTOM_MESSAGE,
    message={'en': 'Custom message', 'ko': '사용자 정의 메시지'},
    level=LogLevel.INFO,
)
```

---

## Action Base Classes

Category-specific base classes that provide helper methods and progress tracking for common workflows.

### BaseTrainAction

For training workflows with dataset/model helpers.

```python
from synapse_sdk.plugins import BaseTrainAction
from pydantic import BaseModel

class TrainParams(BaseModel):
    dataset: int
    epochs: int = 10

class MyTrainAction(BaseTrainAction[TrainParams]):
    action_name = 'train'
    params_model = TrainParams

    def execute(self) -> dict:
        # Helper methods use self.client (from RuntimeContext)
        dataset = self.get_dataset()  # Uses params.dataset
        self.set_progress(1, 3, self.progress.DATASET)

        model_path = self._train(dataset)
        self.set_progress(2, 3, self.progress.TRAIN)

        model = self.create_model(model_path, name='my-model')
        self.set_progress(3, 3, self.progress.MODEL_UPLOAD)

        return {'model_id': model['id']}
```

**Progress categories:** `DATASET`, `TRAIN`, `MODEL_UPLOAD`

**Helper methods:**
- `get_dataset()` - Fetch dataset using `params.dataset`
- `create_model(path, **kwargs)` - Upload trained model
- `get_model(model_id)` - Retrieve existing model

### BaseExportAction

For export workflows with filtered data retrieval.

```python
from typing import Any

from synapse_sdk.plugins import BaseExportAction
from pydantic import BaseModel

class ExportParams(BaseModel):
    filter: dict
    output_path: str

class MyExportAction(BaseExportAction[ExportParams]):
    action_name = 'export'
    params_model = ExportParams

    def get_filtered_results(self, filters: dict) -> tuple[Any, int]:
        # Override for your target type
        return self.client.get_assignments(filters)

    def execute(self) -> dict:
        results, count = self.get_filtered_results(self.params.filter)
        self.set_progress(0, count, self.progress.DATASET_CONVERSION)

        for i, item in enumerate(results, 1):
            # Process and export item
            self.set_progress(i, count, self.progress.DATASET_CONVERSION)

        return {'exported': count}
```
