diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index b9e69c0f54..c81d27f90f 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -2125,6 +2125,9 @@ AUTOMATION_MAX_CONCURRENT = int(AUTOMATION_MAX_CONCURRENT) if AUTOMATION_MAX_CON AUTOMATION_AUTH_TOKEN_EXPIRES_IN = os.getenv('AUTOMATION_AUTH_TOKEN_EXPIRES_IN', '1h') +# Seconds a code automation may compute per run, not counting time waiting on tools. +AUTOMATION_CODE_TIMEOUT = int(os.getenv('AUTOMATION_CODE_TIMEOUT', '30')) + ENABLE_COMMENTS = os.getenv('ENABLE_COMMENTS', 'False').lower() == 'true' ENABLE_NOTIFICATIONS = os.getenv('ENABLE_NOTIFICATIONS', 'True').lower() == 'true' @@ -3288,6 +3291,7 @@ DEFAULT_CONFIG = { 'automations.min_interval': AUTOMATION_MIN_INTERVAL, 'automations.max_concurrent': AUTOMATION_MAX_CONCURRENT, 'automations.auth_token_expires_in': AUTOMATION_AUTH_TOKEN_EXPIRES_IN, + 'automations.code_timeout': AUTOMATION_CODE_TIMEOUT, 'notes.enable': ENABLE_NOTES, 'comments.enable': ENABLE_COMMENTS, 'notifications.enable': ENABLE_NOTIFICATIONS, diff --git a/backend/open_webui/migrations/versions/68fed817af47_automation_triggers_and_actions.py b/backend/open_webui/migrations/versions/68fed817af47_automation_triggers_and_actions.py new file mode 100644 index 0000000000..4acc3ea5fd --- /dev/null +++ b/backend/open_webui/migrations/versions/68fed817af47_automation_triggers_and_actions.py @@ -0,0 +1,87 @@ +"""automation triggers and actions + +Revision ID: 68fed817af47 +Revises: c4e1a7f9b2d3 +Create Date: 2026-11-30 18:52:40 + +Moves automation data from the flat {prompt, model_id, rrule, machine|terminal, target, webhook} +to {triggers: [...], action: {...}}, adds the `state` column a code action keeps between runs, and +adds `automation_run.output`: what a code run printed and returned. +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import context, op + +revision: str = '68fed817af47' +down_revision: str | None = 'c4e1a7f9b2d3' +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +automation = sa.table('automation', sa.column('id', sa.Text()), sa.column('data', sa.JSON())) + + +def to_new(data: dict) -> dict: + if 'action' in data: + return data + triggers = [] + if data.get('rrule'): + triggers.append({'type': 'schedule', 'rrule': data['rrule']}) + if data.get('webhook'): + triggers.append({'type': 'webhook', **data['webhook']}) + return { + 'triggers': triggers, + 'action': { + 'type': 'prompt', + 'prompt': data.get('prompt', ''), + 'model_id': data.get('model_id', ''), + 'machine': data.get('machine') or data.get('terminal'), + 'target': data.get('target'), + }, + } + + +def to_old(data: dict) -> dict | None: + """The flat shape, or None for a code action, which the old shape can't hold.""" + action = data.get('action') + if action is None: + return data + if action.get('type') != 'prompt': + return None + triggers = data.get('triggers') or [] + rrule = next((t['rrule'] for t in triggers if t.get('type') == 'schedule'), '') + webhook = next(({k: v for k, v in t.items() if k != 'type'} for t in triggers if t.get('type') == 'webhook'), None) + return { + 'prompt': action.get('prompt', ''), + 'model_id': action.get('model_id', ''), + 'rrule': rrule, + 'machine': action.get('machine'), + 'target': action.get('target'), + 'webhook': webhook, + } + + +def upgrade() -> None: + op.add_column('automation', sa.Column('state', sa.JSON(), nullable=True)) + op.add_column('automation_run', sa.Column('output', sa.Text(), nullable=True)) + if context.is_offline_mode(): + return + conn = op.get_bind() + for row in conn.execute(sa.select(automation.c.id, automation.c.data)).all(): + conn.execute(sa.update(automation).where(automation.c.id == row.id).values(data=to_new(row.data or {}))) + + +def downgrade() -> None: + if not context.is_offline_mode(): + conn = op.get_bind() + for row in conn.execute(sa.select(automation.c.id, automation.c.data)).all(): + old = to_old(row.data or {}) + if old is None: + conn.execute(sa.text('DELETE FROM automation_run WHERE automation_id = :id'), {'id': row.id}) + conn.execute(sa.delete(automation).where(automation.c.id == row.id)) + else: + conn.execute(sa.update(automation).where(automation.c.id == row.id).values(data=old)) + op.drop_column('automation_run', 'output') + op.drop_column('automation', 'state') diff --git a/backend/open_webui/models/automations.py b/backend/open_webui/models/automations.py index 89ea00cee6..5d0d4bdf11 100644 --- a/backend/open_webui/models/automations.py +++ b/backend/open_webui/models/automations.py @@ -1,7 +1,7 @@ import logging import secrets import time -from typing import Literal, Optional +from typing import Annotated, Any, Literal, Optional, Union from uuid import uuid4 from open_webui.models.notifications import emit_changes @@ -9,7 +9,7 @@ from open_webui.models.access_grants import AccessGrant, AccessGrantResponse, Ac from open_webui.models.users import UserResponse from open_webui.internal.db import Base, get_async_db_context from open_webui.utils.misc import json_text_variants -from pydantic import BaseModel, ConfigDict, model_validator +from pydantic import BaseModel, ConfigDict, Field from sqlalchemy import JSON, BigInteger, Boolean, Column, Index, String, Text, cast, delete, func, or_, select, update from sqlalchemy.ext.asyncio import AsyncSession @@ -26,7 +26,8 @@ class Automation(Base): user_id = Column(Text, nullable=False) folder_id = Column(Text, nullable=True) name = Column(Text, nullable=False) - data = Column(JSON, nullable=False) # {prompt, model_id, rrule} + data = Column(JSON, nullable=False) # {triggers, action} + state = Column(JSON, nullable=True) # a code action's state between runs meta = Column(JSON, nullable=True) is_active = Column(Boolean, nullable=False, default=True) last_run_at = Column(BigInteger, nullable=True) @@ -49,6 +50,7 @@ class AutomationRun(Base): chat_id = Column(Text, nullable=True) status = Column(Text, nullable=False) # success | error error = Column(Text, nullable=True) + output = Column(Text, nullable=True) # what a code run printed, then what it returned created_at = Column(BigInteger, nullable=False) __table_args__ = ( @@ -95,51 +97,85 @@ def keep_target_refs(target: Optional[dict], previous: Optional[dict]) -> Option return target +class AutomationSchedule(BaseModel): + type: Literal['schedule'] = 'schedule' + rrule: str + + class AutomationWebhook(BaseModel): + type: Literal['webhook'] = 'webhook' token: Optional[str] = None # server-owned allow_get: bool = False +AutomationTrigger = Annotated[Union[AutomationSchedule, AutomationWebhook], Field(discriminator='type')] + + +class AutomationPromptAction(BaseModel): + type: Literal['prompt'] = 'prompt' + prompt: str + model_id: str + machine: Optional[AutomationMachineConfig] = None + target: Optional[AutomationTarget] = None + + +class AutomationTool(BaseModel): + """A tool a code action calls, resolved in the chat that created it.""" + + namespace: str + name: str + source: dict + + +class AutomationCodeAction(BaseModel): + """Python run without a model on every trigger; a prompt it sends goes to `target` with `model_id`.""" + + type: Literal['code'] = 'code' + code: str + args: Optional[Any] = None + model_id: str + machine: Optional[AutomationMachineConfig] = None + target: Optional[AutomationTarget] = None + tools: list[AutomationTool] = [] # server-owned + + +AutomationAction = Annotated[Union[AutomationPromptAction, AutomationCodeAction], Field(discriminator='type')] + + +class AutomationData(BaseModel): + triggers: list[AutomationTrigger] = [] # none: run manually only + action: AutomationAction + + +class AutomationCodeResult(BaseModel): + """What a code action returns. Returning nothing keeps the state and runs no prompt.""" + + model_config = ConfigDict(extra='forbid') + + state: Optional[Any] = None + done: bool = False # turn the automation off + next_run_at: Optional[str] = None # "20m", "in 2 hours" or an RFC 3339 time: replaces the next scheduled run once + prompt: Optional[str] = Field(None, pattern=r'\S') # run this with the action's model and target + + def has_webhook(data: Optional[dict]) -> bool: - return bool((data or {}).get('webhook')) + return any(t['type'] == 'webhook' for t in (data or {}).get('triggers', [])) def hide_webhook_token(data: dict) -> dict: - if not (data.get('webhook') or {}).get('token'): + if not has_webhook(data): return data - return {**data, 'webhook': {**data['webhook'], 'token': None}} + return {**data, 'triggers': [{**t, 'token': None} if t['type'] == 'webhook' else t for t in data['triggers']]} def new_webhook_token() -> str: return secrets.token_urlsafe(32) -def keep_webhook_token(webhook: Optional[dict], previous: Optional[dict]) -> Optional[dict]: - if not webhook: - return None +def keep_webhook_token(webhook: dict, previous: Optional[dict]) -> dict: return {**webhook, 'token': (previous or {}).get('token') or new_webhook_token()} -class AutomationData(BaseModel): - prompt: str - model_id: str - rrule: str = '' # empty: no schedule - machine: Optional[AutomationMachineConfig] = None - target: Optional[AutomationTarget] = None - webhook: Optional[AutomationWebhook] = None - - @model_validator(mode='before') - @classmethod - def _former_machine_key(cls, data): - # Automations saved before Terminals became Machines keep their settings under `terminal`. - if isinstance(data, dict) and 'terminal' in data: - data = {**data} - legacy = data.pop('terminal') - if not data.get('machine'): - data['machine'] = legacy - return data - - class AutomationModel(BaseModel): model_config = ConfigDict(from_attributes=True) @@ -152,6 +188,7 @@ class AutomationModel(BaseModel): is_active: bool last_run_at: Optional[int] = None next_run_at: Optional[int] = None + state: Optional[Any] = None created_at: int updated_at: int @@ -165,6 +202,7 @@ class AutomationRunModel(BaseModel): chat_id: Optional[str] = None status: str error: Optional[str] = None + output: Optional[str] = None created_at: int @@ -204,7 +242,7 @@ class AutomationTable: async with get_async_db_context(db) as db: now = int(time.time_ns()) data = form.data.model_dump() - data['webhook'] = keep_webhook_token(data.get('webhook'), None) + data['triggers'] = [keep_webhook_token(t, None) if t['type'] == 'webhook' else t for t in data['triggers']] row = Automation( id=str(uuid4()), user_id=user_id, @@ -324,9 +362,18 @@ class AutomationTable: return None row.name = form.name row.folder_id = form.folder_id + previous = row.data or {} + previous_webhook = next((t for t in previous.get('triggers', []) if t['type'] == 'webhook'), None) data = form.data.model_dump() - data['target'] = keep_target_refs(data.get('target'), (row.data or {}).get('target')) - data['webhook'] = keep_webhook_token(data.get('webhook'), (row.data or {}).get('webhook')) + data['triggers'] = [ + keep_webhook_token(t, previous_webhook) if t['type'] == 'webhook' else t for t in data['triggers'] + ] + data['action']['target'] = keep_target_refs( + data['action'].get('target'), (previous.get('action') or {}).get('target') + ) + # Old state may not fit new code. + if data['action'].get('code') != (previous.get('action') or {}).get('code'): + row.state = None row.data = data row.meta = form.meta if form.is_active is not None: @@ -343,17 +390,37 @@ class AutomationTable: if not row: return data = dict(row.data or {}) - data['target'] = {**(data.get('target') or {'type': 'chat'}), key: value} + action = dict(data.get('action') or {}) + action['target'] = {**(action.get('target') or {'type': 'chat'}), key: value} + data['action'] = action row.data = data await db.commit() + async def update_state_by_id( + self, id: str, state: Any, next_run_at: Optional[int] = None, is_active: bool = True + ) -> None: + """Save a code run's state, and when it asked for them, its next run or that it stops. Not an edit.""" + async with get_async_db_context() as db: + row = await db.get(Automation, id, with_for_update=True) + if not row: + return + row.state = state + if not is_active: + row.is_active = False + row.next_run_at = None + elif next_run_at is not None: + row.next_run_at = next_run_at + await db.commit() + async def regenerate_webhook_token(self, id: str, db: Optional[AsyncSession] = None) -> Optional[AutomationModel]: async with get_async_db_context(db) as db: row = await db.get(Automation, id, with_for_update=True) if not row or not has_webhook(row.data): return None data = dict(row.data or {}) - data['webhook'] = {**data['webhook'], 'token': new_webhook_token()} + data['triggers'] = [ + {**t, 'token': new_webhook_token()} if t['type'] == 'webhook' else t for t in data['triggers'] + ] row.data = data row.updated_at = int(time.time_ns()) await db.commit() @@ -440,7 +507,7 @@ class AutomationTable: result = await db.execute(stmt) rows = result.scalars().all() - from open_webui.utils.automations import next_run_ns + from open_webui.utils.automations import schedule_next_run from open_webui.utils.recurrence import RecurrenceEvaluationTimeout # Batch-fetch user timezones so rescheduling respects each @@ -456,7 +523,7 @@ class AutomationTable: claimed = [] for row in rows: try: - next_run_at = await next_run_ns(row.data.get('rrule', ''), tz=timezone_by_user_id.get(row.user_id)) + next_run_at = await schedule_next_run(row.data, tz=timezone_by_user_id.get(row.user_id)) except RecurrenceEvaluationTimeout: log.warning('Skipping automation %s: recurrence evaluation timed out', row.id) continue @@ -480,6 +547,8 @@ class AutomationRunTable: chat_id: Optional[str] = None, error: Optional[str] = None, *, + output: Optional[str] = None, + notify: bool = True, request=None, event_actor=None, db: Optional[AsyncSession] = None, @@ -491,13 +560,14 @@ class AutomationRunTable: chat_id=chat_id, status=status, error=error, + output=output, created_at=int(time.time_ns()), ) db.add(row) await db.flush() event = None recipients = set() - if status == 'error': + if status == 'error' and notify: from open_webui.events import EVENTS, build_event, publish_event from open_webui.utils.inbox import consume_event from open_webui.models.notifications import emit_changes diff --git a/backend/open_webui/routers/auths.py b/backend/open_webui/routers/auths.py index 5cf8aaef77..a7cf67c68c 100644 --- a/backend/open_webui/routers/auths.py +++ b/backend/open_webui/routers/auths.py @@ -131,6 +131,7 @@ ADMIN_CONFIG_KEYS = { 'AUTOMATION_MAX_COUNT': 'automations.max_count', 'AUTOMATION_MIN_INTERVAL': 'automations.min_interval', 'AUTOMATION_MAX_CONCURRENT': 'automations.max_concurrent', + 'AUTOMATION_CODE_TIMEOUT': 'automations.code_timeout', 'ENABLE_AUTOMATIONS': 'automations.enable', 'ENABLE_AUTOMATION_WEBHOOKS': 'automations.webhooks.enable', 'ENABLE_CHANNELS': 'channels.enable', @@ -1187,6 +1188,7 @@ class AdminConfig(MfaConfigForm): AUTOMATION_MAX_COUNT: int | str | None = None AUTOMATION_MIN_INTERVAL: int | str | None = None AUTOMATION_MAX_CONCURRENT: int | None = Field(default=None, gt=0) + AUTOMATION_CODE_TIMEOUT: int | None = Field(default=None, gt=0) ENABLE_AUTOMATIONS: bool ENABLE_AUTOMATION_WEBHOOKS: bool = True ENABLE_CHANNELS: bool @@ -1271,6 +1273,9 @@ async def update_admin_config(request: Request, form_data: AdminConfig, user=Dep updates['automations.min_interval'] = ( int(form_data.AUTOMATION_MIN_INTERVAL) if form_data.AUTOMATION_MIN_INTERVAL else '' ) + # Code runs always need a limit, so an empty field keeps the current one. + if form_data.AUTOMATION_CODE_TIMEOUT is None: + updates.pop('automations.code_timeout', None) if 'AUTOMATION_MAX_CONCURRENT' not in form_data.model_fields_set: updates.pop('automations.max_concurrent', None) diff --git a/backend/open_webui/routers/automations.py b/backend/open_webui/routers/automations.py index 1e74e23bf0..bce651ebe1 100644 --- a/backend/open_webui/routers/automations.py +++ b/backend/open_webui/routers/automations.py @@ -33,6 +33,7 @@ from open_webui.utils.auth import get_admin_user, get_verified_user from open_webui.utils.agents.discovery import get_models as get_agent_models from open_webui.utils.automations import ( execute_automation, + get_automation_tools, rrule_interval_seconds, schedule_next_run, schedule_next_runs, @@ -80,15 +81,19 @@ async def can_use_automation_webhooks(user) -> bool: async def check_automation_triggers(form_data: AutomationForm, user, db, is_create: bool = False): - data = form_data.data - if data.webhook and not await can_use_automation_webhooks(user): + webhooks = [t for t in form_data.data.triggers if t.type == 'webhook'] + if len(webhooks) > 1: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='An automation has at most one webhook.') + if webhooks and not await can_use_automation_webhooks(user): raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.UNAUTHORIZED) - if data.rrule: + schedules = [t.rrule for t in form_data.data.triggers if t.type == 'schedule'] + for rrule in schedules: try: - await validate_rrule(data.rrule, tz=user.timezone) + await validate_rrule(rrule, tz=user.timezone) except ValueError as e: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) - await check_automation_limits(None, user, data.rrule or None, db, is_create=is_create) + for i, rrule in enumerate(schedules or [None]): + await check_automation_limits(None, user, rrule, db, is_create=is_create and i == 0) def check_automation_access(automation, user): @@ -161,7 +166,7 @@ async def check_automation_folder_access(folder_id: Optional[str], user, db: Asy async def check_automation_channel_access(form_data: AutomationForm, user, db: AsyncSession): - target = form_data.data.target + target = form_data.data.action.target if not target or target.type != 'channel': return @@ -308,7 +313,7 @@ async def get_automation_models( automation = None metadata = {'machine_id': machine_id} if automation: - metadata.update(model_id=automation.data.get('model_id'), automation_id=automation.id) + metadata.update(model_id=automation.data['action']['model_id'], automation_id=automation.id) return await get_agent_models(request, user, metadata, cwd=cwd) @@ -325,11 +330,18 @@ async def create_new_automation( await check_automations_permission(request, user) await check_automation_folder_access(form_data.folder_id, user, db) await check_automation_channel_access(form_data, user, db) - await validate_automation_machine(request, user, form_data.data.model_dump()) + action = form_data.data.action + await validate_automation_machine(request, user, action.model_dump()) # The first run creates the ongoing chat or thread; a form can't point at one. - if form_data.data.target: - form_data.data.target.chat_id = None - form_data.data.target.thread_id = None + if action.target: + action.target.chat_id = None + action.target.thread_id = None + if action.type == 'code': + # Saving code the owner wrote approves the tools it calls. + try: + action.tools = await get_automation_tools(action.code, None, [], request, user) + except (ValueError, SyntaxError) as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) await check_automation_triggers(form_data, user, db, is_create=True) tz = user.timezone @@ -377,24 +389,38 @@ async def update_automation_by_id( if automation.user_id == user.id: await check_automation_folder_access(form_data.folder_id, user, db) await check_automation_channel_access(form_data, user, db) - await validate_automation_machine(request, user, form_data.data.model_dump(), id) + action = form_data.data.action + await validate_automation_machine(request, user, action.model_dump(), id) + if action.type == 'code': + # Saving code the owner wrote approves the tools it calls. + try: + action.tools = await get_automation_tools( + action.code, None, automation.data['action'].get('tools', []), request, user + ) + except (ValueError, SyntaxError) as e: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) await check_automation_triggers(form_data, user, db) else: # Runs use the owner's account, so others only change when it runs: the name, - # the schedule and whether it's on. Everything else stays as the owner set it. + # the schedules and whether it's on. Everything else stays as the owner set it. + schedules = [t for t in form_data.data.triggers if t.type == 'schedule'] form_data = AutomationForm( name=form_data.name, folder_id=automation.folder_id, - data=AutomationData(**{**automation.data, 'rrule': form_data.data.rrule}), + data=AutomationData( + triggers=[*schedules, *(t for t in automation.data['triggers'] if t['type'] == 'webhook')], + action=automation.data['action'], + ), meta=automation.meta, is_active=form_data.is_active, ) - if form_data.data.rrule: + owner_tz = await get_owner_timezone(automation, user) + for schedule in schedules: try: - await validate_rrule(form_data.data.rrule, tz=await get_owner_timezone(automation, user)) + await validate_rrule(schedule.rrule, tz=owner_tz) except ValueError as e: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) - await check_automation_limits(None, user, form_data.data.rrule or None, db) + await check_automation_limits(None, user, schedule.rrule, db) next_run_at = await schedule_next_run(form_data.data.model_dump(), tz=await get_owner_timezone(automation, user)) updated = await Automations.update_by_id(id, form_data, next_run_at, db=db) @@ -444,8 +470,11 @@ class AutomationRunForm(BaseModel): def check_variables(automation: AutomationModel, variables: Optional[dict]): + action = automation.data['action'] + if action['type'] != 'prompt': + return try: - fill_variables(automation.data['prompt'], variables) + fill_variables(action['prompt'], variables) except PromptVariableError as e: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) @@ -524,7 +553,7 @@ async def read_hook_variables(request: Request) -> dict: async def trigger_automation_webhook(request: Request, id: str, token: str): """Public: the token in the URL is the credential.""" automation = await Automations.get_by_id(id) - webhook = (automation.data.get('webhook') or {}) if automation else {} + webhook = next((t for t in automation.data['triggers'] if t['type'] == 'webhook'), {}) if automation else {} config = await Config.get_many('automations.enable', 'automations.webhooks.enable') if ( not automation @@ -548,7 +577,7 @@ async def trigger_automation_webhook(request: Request, id: str, token: str): variables = await read_hook_variables(request) check_variables(automation, variables) automation = await Automations.update_last_run_at(automation.id) - asyncio.create_task(execute_automation(request.app, automation, variables)) + asyncio.create_task(execute_automation(request.app, automation, variables, trigger='webhook')) await publish_event( request, EVENTS.AUTOMATION_RUN_STARTED, diff --git a/backend/open_webui/routers/calendar.py b/backend/open_webui/routers/calendar.py index e2cf485c58..c26960bbd8 100644 --- a/backend/open_webui/routers/calendar.py +++ b/backend/open_webui/routers/calendar.py @@ -26,7 +26,7 @@ from open_webui.models.users import UserModel from open_webui.utils.access_control import filter_allowed_access_grants, has_permission, validate_access_grants from open_webui.utils.auth import get_verified_user from open_webui.utils.calendar import expand_recurring_event -from open_webui.utils.recurrence import schedule_start_ns +from open_webui.utils.recurrence import next_run_ns, schedule_start_ns from pydantic import BaseModel log = logging.getLogger(__name__) @@ -200,46 +200,45 @@ async def get_events( # Future runs: expand RRULEs for active automations only active_automations = await Automations.get_active_by_user(user.id) for auto in active_automations: - rrule_str = auto.data.get('rrule', '') if auto.data else '' - if not rrule_str: - continue + schedules = [t['rrule'] for t in auto.data['triggers'] if t['type'] == 'schedule'] + for i, rrule_str in enumerate(schedules): + start_at = await next_run_ns(rrule_str, tz=user.timezone) or 0 + upper_rrule = rrule_str.upper() + if 'COUNT=' in upper_rrule and 'DTSTART' in upper_rrule: + # COUNT runs from DTSTART, anchoring on the next run would restart it + try: + start_at = schedule_start_ns(rrule_str, user.timezone) + except ValueError: + pass - start_at = auto.next_run_at or 0 - upper_rrule = rrule_str.upper() - if 'COUNT=' in upper_rrule and 'DTSTART' in upper_rrule: - # COUNT runs from DTSTART, anchoring on the next run would restart it - try: - start_at = schedule_start_ns(rrule_str, user.timezone) - except ValueError: - pass + action = auto.data['action'] + virtual = { + 'id': f'auto_{auto.id}_{i}', + 'calendar_id': SCHEDULED_TASKS_CALENDAR_ID, + 'user_id': user.id, + 'title': auto.name, + 'description': action.get('prompt') or action.get('code') or '', + 'start_at': start_at, + 'end_at': None, + 'all_day': False, + 'rrule': rrule_str, + 'color': None, + 'location': None, + 'data': None, + 'meta': {'automation_id': auto.id}, + 'is_cancelled': False, + 'attendees': [], + 'created_at': auto.created_at, + 'updated_at': auto.updated_at, + 'user': None, + } - virtual = { - 'id': f'auto_{auto.id}', - 'calendar_id': SCHEDULED_TASKS_CALENDAR_ID, - 'user_id': user.id, - 'title': auto.name, - 'description': auto.data.get('prompt', '') if auto.data else '', - 'start_at': start_at, - 'end_at': None, - 'all_day': False, - 'rrule': rrule_str, - 'color': None, - 'location': None, - 'data': None, - 'meta': {'automation_id': auto.id}, - 'is_cancelled': False, - 'attendees': [], - 'created_at': auto.created_at, - 'updated_at': auto.updated_at, - 'user': None, - } - - # Only expand into the future — past runs are handled below - now_ns = int(time.time_ns()) - rrule_start = max(start_ns, now_ns) - instances = expand_recurring_event(virtual, rrule_start, end_ns, tz=user.timezone) - for inst in instances: - expanded.append(CalendarEventUserResponse(**inst)) + # Only expand into the future — past runs are handled below + now_ns = int(time.time_ns()) + rrule_start = max(start_ns, now_ns) + instances = expand_recurring_event(virtual, rrule_start, end_ns, tz=user.timezone) + for inst in instances: + expanded.append(CalendarEventUserResponse(**inst)) # Past runs: single range query joined with automation runs_with_auto = await AutomationRuns.get_runs_by_user_range(user.id, start_ns, end_ns) diff --git a/backend/open_webui/tools/builtin.py b/backend/open_webui/tools/builtin.py index 41bdd06fe9..0d784f68dc 100644 --- a/backend/open_webui/tools/builtin.py +++ b/backend/open_webui/tools/builtin.py @@ -10,12 +10,13 @@ import asyncio import logging import ntpath import time -from typing import Literal, Optional +from typing import Annotated, Any, Literal, Optional, Union from urllib.parse import unquote from fastapi import HTTPException, Request -from open_webui.utils.machines import automation_machine_of, is_machine_ref, machine_id_of, strip_machine_prefix +from open_webui.models.automations import AutomationSchedule +from open_webui.utils.machines import is_machine_ref, machine_id_of, strip_machine_prefix from open_webui.env import ( KNOWLEDGE_GREP_MAX_MATCHES, VIEW_FILE_DEFAULT_MAX_CHARS, @@ -4272,7 +4273,7 @@ async def search_tools( from typing import Literal -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, TypeAdapter VALID_TASK_STATUSES = {'pending', 'in_progress', 'completed', 'cancelled'} @@ -4425,36 +4426,93 @@ async def _validate_owned_automation_folder(user_id: str, folder_id: Optional[st return folder.id +class AutomationPromptForm(BaseModel): + type: Literal['prompt'] = 'prompt' + prompt: str = Field(..., description='What the current model is asked on every run.') + new_chat: bool = Field(True, description='True starts a new chat each run; false continues this chat.') + + +class AutomationCodeForm(BaseModel): + type: Literal['code'] = 'code' + code: str = Field( + ..., + description=( + 'Python run without a model on every trigger, in a sandbox: no generators (yield), and only some of the standard ' + 'library (json, re, datetime and hashlib work). Call tools from this chat as ' + '`await call_tool("namespace.name", {arguments})` with a literal path: the namespace is the MCP server id, ' + 'the tool id, "machine" for the machine\'s tools, or "builtin" for fetch_url, e.g. "gmail.search_emails". Receives `state` (the state the ' + 'last run returned, first None), `args`, `now`, `trigger` ({"type": "schedule" | "webhook" | "manual"}) and ' + '`event` (a webhook\'s body). Return nothing to stay quiet, or {"state", "done", "next_run_at", "prompt"}: ' + '`prompt` runs with the current model, `done` turns the automation off, `next_run_at` ("20m", ' + '"in 2 hours" or an RFC 3339 time) replaces the next scheduled run once.' + ), + ) + args: Optional[Any] = Field(None, description='JSON passed to every run as `args`.') + new_chat: bool = Field(False, description='True sends each prompt to a new chat; false sends them to this chat.') + + +AutomationActionForm = Annotated[Union[AutomationPromptForm, AutomationCodeForm], Field(discriminator='type')] + + +async def _automation_action(action, metadata: dict, user_id: str, saved_tools: list[dict]) -> dict: + """The stored action for a form from this chat: its model and machine, and where sent prompts go.""" + from open_webui.utils.automations import get_automation_tools + + action = TypeAdapter(AutomationActionForm).validate_python( + action.model_dump() if isinstance(action, BaseModel) else action + ) + model_id = metadata.get('model_id') or ( + metadata.get('model', {}).get('id') if isinstance(metadata.get('model'), dict) else None + ) + if not model_id: + raise ValueError('Could not detect current model') + current_chat_id = metadata.get('chat_id') or '' + target = None + if current_chat_id.startswith('channel:'): + target = {'type': 'channel', 'channel_id': current_chat_id.removeprefix('channel:'), 'new_thread': action.new_chat} + elif not action.new_chat: + # Continue the chat it was asked from, when that chat is the user's own saved chat. + chat = ( + await Chats.get_chat_by_id_and_user_id(current_chat_id, user_id) + if current_chat_id and not current_chat_id.startswith('local:') + else None + ) + target = {'new_chat': False, 'chat_id': chat.id if chat else None} + data = {**action.model_dump(exclude={'new_chat'}), 'model_id': model_id, 'target': target} + if action.type == 'code': + data['machine'] = {'server_id': metadata['machine_id']} if metadata.get('machine_id') else None + data['tools'] = await get_automation_tools(action.code, metadata.get('tools'), saved_tools) + return data + + async def create_automation( name: str, - prompt: str, - rrule: str = '', + action: AutomationActionForm, + triggers: Optional[list[AutomationSchedule]] = None, folder_id: Optional[str] = None, - new_chat: bool = True, __request__: Request = None, __user__: dict = None, __metadata__: dict = None, ) -> str: """ - Create an automation that runs a prompt manually or on a recurring or one-time schedule. - The automation will use the current chat model. + Create an automation: what it does (action) and when it runs (triggers). + Use this when the user asks to schedule, remind, repeat, watch or check back on something, instead of waiting or polling. - For scheduled runs, provide a valid iCalendar RRULE string. Common examples: + A prompt action asks the current model on every run. A code action checks something without a model and sends a prompt + only when there is something to act on; it runs once now as a preview, which sets the first state. + Example code: found = await call_tool("gmail.search_emails", {"query": "from:landlord"})\nseen = (state or {}).get("seen", [])\nnew = [m for m in found if m["id"] not in seen]\nresult = {"state": {"seen": [m["id"] for m in found]}}\nif new:\n result["prompt"] = "New email from the landlord: " + new[0]["subject"]\nreturn result + + Triggers are schedules with iCalendar RRULE strings. Omit them for manual runs only. Examples: - Every day at 9am: "DTSTART:20250101T090000\nRRULE:FREQ=DAILY" - Every Monday at 8am: "DTSTART:20250106T080000\nRRULE:FREQ=WEEKLY;BYDAY=MO" - - Every hour: "RRULE:FREQ=HOURLY;INTERVAL=1" - Every 30 minutes: "RRULE:FREQ=MINUTELY;INTERVAL=30" - Once at a specific time: "DTSTART:20250415T140000\nRRULE:FREQ=DAILY;COUNT=1" - - First day of every month: "DTSTART:20250101T090000\nRRULE:FREQ=MONTHLY;BYMONTHDAY=1" - - The DTSTART time should reflect the desired execution time. Use COUNT=1 for one-time automations. :param name: A short descriptive name for the automation - :param prompt: The prompt/instructions to execute on each run - :param rrule: An iCalendar RRULE string defining the schedule. Omit for manual runs only. + :param action: What it does: a prompt or code + :param triggers: When it runs :param folder_id: Optional owner-owned folder ID for generated chats - :param new_chat: True starts each run in a new chat. False continues this chat on every run (in a channel, one thread), so each run sees the earlier ones. - :return: JSON with the created automation details including id, next scheduled runs + :return: JSON with the created automation, its next runs, and for code its preview result """ if __request__ is None: return JSONCodec.dumps({'error': 'Request context not available'}) @@ -4463,81 +4521,70 @@ async def create_automation( return JSONCodec.dumps({'error': 'User context not available'}) try: - from open_webui.models.automations import AutomationData, AutomationForm, Automations, AutomationTarget + from open_webui.models.automations import AutomationData, AutomationForm, Automations from open_webui.models.users import Users from open_webui.routers.automations import check_automation_limits - from open_webui.utils.automations import schedule_next_run, schedule_next_runs, validate_rrule + from open_webui.utils.automations import ( + execute_automation_code, + schedule_next_run, + schedule_next_runs, + validate_rrule, + ) user_id = __user__.get('id') user = await Users.get_user_by_id(user_id) if not user: return JSONCodec.dumps({'error': 'User not found'}) - # Fall back to model dict ID since __metadata__ may predate model_id assignment metadata = __metadata__ or {} - model_id = metadata.get('model_id') or ( - metadata.get('model', {}).get('id') if isinstance(metadata.get('model'), dict) else None - ) - if not model_id: - return JSONCodec.dumps({'error': 'Could not detect current model'}) try: folder_id = await _validate_owned_automation_folder(user_id, folder_id) except ValueError as e: return JSONCodec.dumps({'error': str(e)}) - if rrule: + # Tool calls may pass plain JSON; read both shapes as the forms above. + triggers = [ + (t.model_dump() if isinstance(t, BaseModel) else AutomationSchedule.model_validate(t).model_dump()) + for t in triggers or [] + ] + for i, trigger in enumerate(triggers): try: - await validate_rrule(rrule, tz=user.timezone) + await validate_rrule(trigger['rrule'], tz=user.timezone) + await check_automation_limits(__request__, user, trigger['rrule'], None, is_create=i == 0) except ValueError as e: return JSONCodec.dumps({'error': f'Invalid schedule: {e}'}) + except HTTPException as e: + return JSONCodec.dumps({'error': e.detail}) - try: - await check_automation_limits(__request__, user, rrule, None, is_create=True) - except HTTPException as e: - return JSONCodec.dumps({'error': e.detail}) + action = await _automation_action(action, metadata, user_id, []) - current_chat_id = metadata.get('chat_id') or '' - if current_chat_id.startswith('channel:'): - target = AutomationTarget( - type='channel', channel_id=current_chat_id.removeprefix('channel:'), new_thread=new_chat - ) - elif not new_chat: - # Continue the chat it was asked from, when that chat is the user's own saved chat. - chat = ( - await Chats.get_chat_by_id_and_user_id(current_chat_id, user_id) - if current_chat_id and not current_chat_id.startswith('local:') - else None - ) - target = AutomationTarget(new_chat=False, chat_id=chat.id if chat else None) - else: - target = None - - tz = user.timezone form = AutomationForm( - name=name, - folder_id=folder_id, - data=AutomationData( - prompt=prompt, - model_id=model_id, - rrule=rrule, - target=target, - ), - is_active=True, + name=name, folder_id=folder_id, data=AutomationData(triggers=triggers, action=action), is_active=True ) - + tz = user.timezone automation = await Automations.insert(user_id, form, await schedule_next_run(form.data.model_dump(), tz=tz)) + preview = None + if action['type'] == 'code': + try: + preview = await execute_automation_code(__request__, user, automation, 'manual') + except Exception as e: + await Automations.delete(automation.id) + return JSONCodec.dumps({'error': f'The code failed its first run, so nothing was saved: {e}'}) + await Automations.update_state_by_id(automation.id, preview.state if preview else None) + return JSONCodec.dumps( { 'status': 'success', 'id': automation.id, 'name': automation.name, 'folder_id': automation.folder_id, - 'model_id': model_id, - 'target': automation.data.get('target'), + 'triggers': automation.data['triggers'], + 'action': {k: v for k, v in automation.data['action'].items() if k != 'tools'}, 'is_active': automation.is_active, 'next_runs': await schedule_next_runs(automation.data, tz=tz), + **({'preview': preview.model_dump() if preview else None} if action['type'] == 'code' else {}), }, ensure_ascii=False, ) @@ -4547,24 +4594,26 @@ async def create_automation( async def update_automation( - automation_id: str, + automation_id: Optional[str] = None, name: Optional[str] = None, - prompt: Optional[str] = None, - rrule: Optional[str] = None, - model_id: Optional[str] = None, + action: Optional[AutomationActionForm] = None, + triggers: Optional[list[AutomationSchedule]] = None, folder_id: Optional[str] = '', + next_run_at: Optional[str] = None, __request__: Request = None, __user__: dict = None, + __metadata__: dict = None, ) -> str: """ Update an existing automation. Only the provided fields are changed; omitted fields stay the same. + In a run of an automation, omit automation_id to update that automation, and use next_run_at to decide when it runs next. - :param automation_id: The ID of the automation to update + :param automation_id: The ID of the automation to update; defaults to the automation this run belongs to :param name: New name for the automation (optional) - :param prompt: New prompt/instructions (optional) - :param rrule: New iCalendar RRULE string. Omit to keep the schedule or pass an empty string to remove it. - :param model_id: New model ID to use (optional); blank values are ignored + :param action: New prompt or code (optional). The model, machine and destination stay unless new_chat is given; code is re-checked against this chat's tools. + :param triggers: New schedules (optional); a webhook set in the editor is kept. Pass [] to remove the schedules. :param folder_id: New owner-owned folder ID (optional); omit or pass blank to keep unchanged, pass null to clear + :param next_run_at: When it runs next, once, instead of at its next scheduled time: "20m", "in 2 hours", or an RFC 3339 time with a timezone (optional) :return: JSON with the updated automation details """ if __request__ is None: @@ -4574,34 +4623,30 @@ async def update_automation( return JSONCodec.dumps({'error': 'User context not available'}) try: - from open_webui.models.automations import ( - AutomationData, - AutomationForm, - Automations, - AutomationTarget, - AutomationMachineConfig, - AutomationWebhook, - ) + from open_webui.models.automations import AutomationData, AutomationForm, Automations from open_webui.models.users import Users from open_webui.routers.automations import check_automation_limits - from open_webui.utils.automations import schedule_next_run, schedule_next_runs, validate_rrule + from open_webui.utils.automations import ( + schedule_next_run, + schedule_next_run_at, + schedule_next_runs, + validate_rrule, + ) user_id = __user__.get('id') user = await Users.get_user_by_id(user_id) if not user: return JSONCodec.dumps({'error': 'User not found'}) + automation_id = automation_id or (__metadata__ or {}).get('automation_id') + if not automation_id: + return JSONCodec.dumps({'error': 'automation_id is required outside a run of an automation'}) automation = await Automations.get_by_id(automation_id) if not automation: return JSONCodec.dumps({'error': 'Automation not found'}) if automation.user_id != user_id: return JSONCodec.dumps({'error': 'Access denied'}) - # Merge provided fields with existing values - new_name = name if name is not None else automation.name - new_prompt = prompt if prompt is not None else automation.data.get('prompt', '') - new_model_id = model_id.strip() if model_id and model_id.strip() else automation.data.get('model_id', '') - new_rrule = rrule if rrule is not None else automation.data.get('rrule', '') if folder_id is None: new_folder_id = None elif not folder_id.strip(): @@ -4612,38 +4657,57 @@ async def update_automation( except ValueError as e: return JSONCodec.dumps({'error': str(e)}) - # Validate RRULE if changed - if rrule: - try: - await validate_rrule(new_rrule, tz=user.timezone) - except ValueError as e: - return JSONCodec.dumps({'error': f'Invalid schedule: {e}'}) + new_triggers = automation.data['triggers'] + if triggers is not None: + triggers = [ + (t.model_dump() if isinstance(t, BaseModel) else AutomationSchedule.model_validate(t).model_dump()) + for t in triggers + ] + for trigger in triggers: + try: + await validate_rrule(trigger['rrule'], tz=user.timezone) + await check_automation_limits(__request__, user, trigger['rrule'], None) + except ValueError as e: + return JSONCodec.dumps({'error': f'Invalid schedule: {e}'}) + except HTTPException as e: + return JSONCodec.dumps({'error': e.detail}) + new_triggers = triggers + [t for t in new_triggers if t['type'] == 'webhook'] - try: - await check_automation_limits(__request__, user, new_rrule or None, None) - except HTTPException as e: - return JSONCodec.dumps({'error': e.detail}) + new_action = automation.data['action'] + if action is not None: + action = TypeAdapter(AutomationActionForm).validate_python( + action.model_dump(exclude_unset=True) if isinstance(action, BaseModel) else action + ) + built = await _automation_action( + action, __metadata__ or {}, user_id, automation.data['action'].get('tools', []) + ) + # Only what was given changes: the prompt or code, and where prompts go only when new_chat is set. + old = automation.data['action'] + new_action = { + **{key: built[key] for key in ('type', 'prompt', 'code', 'args', 'tools') if key in built}, + 'model_id': old['model_id'], + 'machine': old.get('machine') or built.get('machine'), + 'target': built['target'] if 'new_chat' in action.model_fields_set else old.get('target'), + } + if action.type == 'code' and 'args' not in action.model_fields_set: + new_action['args'] = old.get('args') tz = user.timezone form = AutomationForm( - name=new_name, + name=name if name is not None else automation.name, folder_id=new_folder_id, - data=AutomationData( - prompt=new_prompt, - model_id=new_model_id, - rrule=new_rrule, - target=AutomationTarget(**automation.data['target']) if automation.data.get('target') else None, - machine=AutomationMachineConfig(**automation_machine_of(automation.data)) - if automation_machine_of(automation.data) - else None, - webhook=AutomationWebhook(**automation.data['webhook']) if automation.data.get('webhook') else None, - ), + data=AutomationData(triggers=new_triggers, action=new_action), is_active=automation.is_active, ) - - updated = await Automations.update_by_id( - automation_id, form, await schedule_next_run(form.data.model_dump(), tz=tz) - ) + updated = await Automations.update_by_id(automation_id, form, await schedule_next_run(form.data.model_dump(), tz=tz)) + if next_run_at: + try: + await Automations.update_state_by_id( + automation_id, updated.state, await schedule_next_run_at(next_run_at, user) + ) + except ValueError as e: + return JSONCodec.dumps({'error': f'Invalid next_run_at: {e}'}) + updated = await Automations.get_by_id(automation_id) return JSONCodec.dumps( { @@ -4651,9 +4715,10 @@ async def update_automation( 'id': updated.id, 'name': updated.name, 'folder_id': updated.folder_id, - 'model_id': new_model_id, - 'target': updated.data.get('target'), + 'triggers': [t for t in updated.data['triggers'] if t['type'] == 'schedule'], + 'action': {k: v for k, v in updated.data['action'].items() if k != 'tools'}, 'is_active': updated.is_active, + 'next_run_at': updated.next_run_at, 'next_runs': await schedule_next_runs(updated.data, tz=tz), }, ensure_ascii=False, @@ -4676,7 +4741,7 @@ async def list_automations( :param status: Filter by status: "active", "paused", or omit for all :param folder_id: Optional owner-owned folder ID filter; pass an empty string to clear the folder filter :param count: Maximum number of automations to return (default: 10) - :return: JSON list of automations with id, name, prompt snippet, schedule, status, and next runs + :return: JSON list of automations with id, name, action type and snippet, schedules, status, and next runs """ if __request__ is None: return JSONCodec.dumps({'error': 'Request context not available'}) @@ -4707,19 +4772,20 @@ async def list_automations( automations = [] for item in result.items: - rrule = item.data.get('rrule', '') - prompt_text = item.data.get('prompt', '') - snippet = prompt_text[:100] + ('...' if len(prompt_text) > 100 else '') + action = item.data['action'] + text = action.get('prompt') or action.get('code') or '' + snippet = text[:100] + ('...' if len(text) > 100 else '') automations.append( { 'id': item.id, 'name': item.name, 'folder_id': item.folder_id, - 'prompt_snippet': snippet, - 'model_id': item.data.get('model_id', ''), - 'target': item.data.get('target'), - 'rrule': rrule, + 'action_type': action['type'], + 'snippet': snippet, + 'model_id': action['model_id'], + 'target': action.get('target'), + 'schedules': [t['rrule'] for t in item.data['triggers'] if t['type'] == 'schedule'], 'webhook': has_webhook(item.data), 'is_active': item.is_active, 'last_run_at': item.last_run_at, diff --git a/backend/open_webui/utils/automations.py b/backend/open_webui/utils/automations.py index 7332763300..e12fe0f240 100644 --- a/backend/open_webui/utils/automations.py +++ b/backend/open_webui/utils/automations.py @@ -15,13 +15,16 @@ Environment: CALENDAR_ALERT_LOOKAHEAD_MINUTES – default alert window (default: 5) """ +import ast import asyncio import copy +import json import logging import os import random +import re import time -from datetime import timedelta +from datetime import datetime, timedelta from typing import Optional from uuid import uuid4 @@ -31,7 +34,7 @@ from open_webui.utils.machines import automation_machine_of, machine_id_of from open_webui.constants import ERROR_MESSAGES from open_webui.events import EVENTS, build_event, publish_event from open_webui.internal.db import get_async_db -from open_webui.models.automations import AutomationModel, AutomationRuns, Automations +from open_webui.models.automations import AutomationCodeResult, AutomationModel, AutomationRuns, Automations from open_webui.models.chats import ChatForm, Chats from open_webui.models.config import Config from open_webui.models.folders import Folders @@ -58,6 +61,7 @@ from open_webui.utils.machines import ( initialize_machine_directory, resolve_machine_connection, ) +from pydantic_monty import AsyncMonty from starlette.datastructures import Headers log = logging.getLogger(__name__) @@ -71,11 +75,25 @@ CALENDAR_ALERT_LOOKAHEAD_MINUTES = int(os.getenv('CALENDAR_ALERT_LOOKAHEAD_MINUT async def schedule_next_run(data: dict, tz: str = None) -> Optional[int]: - return await next_run_ns(data['rrule'], tz=tz) if data.get('rrule') else None + runs = [await next_run_ns(t['rrule'], tz=tz) for t in data.get('triggers', []) if t['type'] == 'schedule'] + return min((run for run in runs if run), default=None) + + +async def schedule_next_run_at(value: str, user) -> int: + """A next run asked for by code or a run, as the timer tool's `at` takes it, no sooner than automations may run.""" + from open_webui.utils.timers import parse_timer_at + + floor = SCHEDULER_POLL_INTERVAL + if user.role != 'admin': + floor = max(floor, int(await Config.get('automations.min_interval') or 0)) + return max(parse_timer_at(value), time.time_ns() + floor * 1_000_000_000) async def schedule_next_runs(data: dict, tz: str = None) -> list[int]: - return await next_n_runs_ns(data['rrule'], tz=tz) if data.get('rrule') else [] + runs = [ + run for t in data.get('triggers', []) if t['type'] == 'schedule' for run in await next_n_runs_ns(t['rrule'], tz=tz) + ] + return sorted(runs)[:5] # Worker Loop @@ -130,7 +148,7 @@ async def scheduler_worker_loop(app) -> None: if batch: log.info('Claimed %s due automation(s)', len(batch)) for automation in batch: - asyncio.create_task(execute_automation(app, automation)) + asyncio.create_task(execute_automation(app, automation, trigger='schedule')) except Exception: log.exception('Scheduler: automation error') @@ -219,9 +237,9 @@ async def _resolve_model_defaults(app, model_id: str) -> dict: return defaults -async def validate_automation_machine(request, user, data: dict, automation_id: str | None = None): - machine = automation_machine_of(data) - model_id = data['model_id'] +async def validate_automation_machine(request, user, action: dict, automation_id: str | None = None): + machine = automation_machine_of(action) + model_id = action['model_id'] is_agent = model_id.startswith('agent:') if not machine.get('server_id'): if is_agent: @@ -232,7 +250,7 @@ async def validate_automation_machine(request, user, data: dict, automation_id: _, template = await template_connection(user, machine['server_id']) scope = (template.get('data') or {}).get('scope') - if (data.get('target') or {}).get('type') == 'channel' and (is_agent or scope == 'chat'): + if (action.get('target') or {}).get('type') == 'channel' and (is_agent or scope == 'chat'): raise HTTPException(400, 'This machine requires a chat destination.') if scope == 'model': await require_model_access(user, model_id, machine['server_id'], request) @@ -243,7 +261,7 @@ async def validate_automation_machine(request, user, data: dict, automation_id: if not await resolve_machine_connection(request, user, metadata): raise HTTPException(400, 'The configured machine is unavailable for this automation.') if is_agent: - if (data.get('target') or {}).get('type') == 'channel': + if (action.get('target') or {}).get('type') == 'channel': raise HTTPException(400, 'Agent automations require a chat destination.') available = await get_agent_models(request, user, metadata, cwd=machine.get('cwd')) if not any(model['id'] == model_id for model in available): @@ -257,8 +275,9 @@ async def _execute_channel_automation( prompt: str, model_id: str, token: str, + output: Optional[str] = None, ) -> None: - target = automation.data.get('target') or {} + target = automation.data['action'].get('target') or {} channel_id = target.get('channel_id') if not channel_id or not await Config.get('channels.enable'): raise ValueError('Channel not found') @@ -351,7 +370,7 @@ async def _execute_channel_automation( 'automation_id': automation.id, 'background_tasks': {}, } - machine = automation_machine_of(automation.data) + machine = automation_machine_of(automation.data['action']) if machine.get('server_id'): form_data['machine_id'] = machine['server_id'] await initialize_machine_directory( @@ -377,7 +396,7 @@ async def _execute_channel_automation( room=f'user:{automation.user_id}', ) - await _record_run(request, automation.id, 'success', chat_id=f'channel:{channel.id}') + await _record_run(request, automation.id, 'success', chat_id=f'channel:{channel.id}', output=output) await publish_event( request, EVENTS.AUTOMATION_RUN_COMPLETED, @@ -390,18 +409,23 @@ async def _execute_channel_automation( _run_semaphore: asyncio.Semaphore | None = None -async def execute_automation(app, automation: AutomationModel, variables: Optional[dict] = None) -> None: +async def execute_automation( + app, automation: AutomationModel, variables: Optional[dict] = None, trigger: str = 'manual' +) -> None: + """`trigger` is what started the run: schedule, webhook or manual. A webhook's variables are its body.""" global _run_semaphore max_concurrent = await Config.get('automations.max_concurrent') if not max_concurrent: - return await _execute_automation(app, automation, variables) + return await _execute_automation(app, automation, variables, trigger) if _run_semaphore is None: _run_semaphore = asyncio.Semaphore(int(max_concurrent)) async with _run_semaphore: - await _execute_automation(app, automation, variables) + await _execute_automation(app, automation, variables, trigger) -async def _execute_automation(app, automation: AutomationModel, variables: Optional[dict] = None) -> None: +async def _execute_automation( + app, automation: AutomationModel, variables: Optional[dict] = None, trigger: str = 'manual' +) -> None: """Execute an automation through the full chat completion pipeline. Creates a real chat or channel message, then calls chat_completion exactly like the frontend: @@ -409,6 +433,7 @@ async def _execute_automation(app, automation: AutomationModel, variables: Optio (filters, model params, knowledge/RAG, tools, DB saves, webhooks). """ chat = None + code_output = None request = _build_request(app) try: user = await Users.get_user_by_id(automation.user_id) @@ -427,8 +452,8 @@ async def _execute_automation(app, automation: AutomationModel, variables: Optio await _record_run(request, automation.id, 'error', error=error, actor=user) return - prompt = fill_variables(await prompt_template(automation.data['prompt'], user), variables, strict=False) - model_id = automation.data['model_id'] + action = automation.data['action'] + model_id = action['model_id'] try: expires_delta = parse_duration(str(await Config.get('automations.auth_token_expires_in', '1h'))) except ValueError: @@ -447,11 +472,56 @@ async def _execute_automation(app, automation: AutomationModel, variables: Optio await get_all_models(_build_request(app, token=token), user=user) request = _build_request(app, token=token) - await validate_automation_machine(request, user, automation.data, automation.id) + await validate_automation_machine(request, user, action, automation.id) - target = automation.data.get('target') or {} + if action['type'] == 'code': + from open_webui.socket.main import sio + + # Open editors reload the state and activity when a run that sends nothing ends. + finished = {'automation_id': automation.id, 'name': automation.name, 'status': 'success'} + latest = await AutomationRuns.get_latest(automation.id) + failing = latest is not None and latest.status == 'error' + # Every run is recorded with what it printed and returned, capped like a chat tool result. + limit = await Config.get('tools.output_max_chars') + prints: list[str] = [] + try: + returned = await execute_automation_code( + request, user, automation, trigger, variables if trigger == 'webhook' else None, prints + ) + result = returned or AutomationCodeResult(state=automation.state) + next_run_at = await schedule_next_run_at(result.next_run_at, user) if result.next_run_at else None + except Exception as e: + # A failure notifies once per streak, or every time when run by hand. + output = ''.join(prints)[:limit] if limit else ''.join(prints) + await _record_run( + request, + automation.id, + 'error', + error=f'Code failed: {e}'[:4000], + actor=user, + output=output or None, + notify=not failing or trigger == 'manual', + ) + await sio.emit('automation:result', {**finished, 'status': 'error'}, room=f'user:{automation.user_id}') + return + # A result without `state` keeps the saved one. + state = result.state if 'state' in result.model_fields_set else automation.state + code_output = ''.join(prints) + json.dumps( + returned.model_dump(exclude_unset=True) if returned else None, default=str + ) + code_output = code_output[:limit] if limit else code_output + await Automations.update_state_by_id(automation.id, state, next_run_at, is_active=not result.done) + if not result.prompt: + await _record_run(request, automation.id, 'success', actor=user, output=code_output) + await sio.emit('automation:result', finished, room=f'user:{automation.user_id}') + return + prompt = result.prompt + else: + prompt = fill_variables(await prompt_template(action['prompt'], user), variables, strict=False) + + target = action.get('target') or {} if target.get('type') == 'channel': - await _execute_channel_automation(app, automation, user, prompt, model_id, token) + await _execute_channel_automation(app, automation, user, prompt, model_id, token, code_output) return # Runs land in the automation's folder while its creator can still write there. @@ -465,7 +535,7 @@ async def _execute_automation(app, automation: AutomationModel, variables: Optio assistant_msg_id = str(uuid4()) parent_id = None defaults = await _resolve_model_defaults(app, model_id) - machine = automation_machine_of(automation.data) + machine = automation_machine_of(action) if folder_id and await get_folder_machine_mismatch(folder_id, machine.get('server_id')): folder_machine = await get_folder_machine(folder_id) if machine.get('server_id') or await can_use_machine(user, folder_machine['machine_id']): @@ -579,7 +649,7 @@ async def _execute_automation(app, automation: AutomationModel, variables: Optio room=f'user:{automation.user_id}', ) - await _record_run(request, automation.id, 'success', chat_id=chat.id) + await _record_run(request, automation.id, 'success', chat_id=chat.id, output=code_output) await publish_event( request, EVENTS.AUTOMATION_RUN_COMPLETED, @@ -591,11 +661,219 @@ async def _execute_automation(app, automation: AutomationModel, variables: Optio except (Exception, asyncio.CancelledError) as e: log.exception(f'Automation {automation.id} failed') error = 'Automation reply was cancelled' if isinstance(e, asyncio.CancelledError) else str(e)[:4000] - await _record_run(request, automation.id, 'error', chat_id=chat.id if chat else None, error=error) + await _record_run( + request, automation.id, 'error', chat_id=chat.id if chat else None, error=error, output=code_output + ) if isinstance(e, asyncio.CancelledError): raise +# Code actions + + +async def get_automation_tools( + code: str, chat_tools: Optional[dict], saved: list[dict], request: Optional[Request] = None, user=None +) -> list[dict]: + """The tools a program calls, as `call_tool("namespace.name", {...})` with a literal path. + + Each comes from `saved` (approved earlier), the creating chat's tools, or, for code the owner + writes in the editor (`request` and `user` given), any tool the owner can use. Any other use of + `call_tool` is refused, so every tool a run can reach is known when the automation is saved. + """ + tree = ast.parse(code) + # The sandbox (Monty) has no generators yet; say so on save rather than on the first run. + if any(isinstance(n, (ast.Yield, ast.YieldFrom)) for n in ast.walk(tree)): + raise ValueError('Automation code cannot use yield (generators); build and return a list instead.') + calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call) and getattr(n.func, 'id', None) == 'call_tool'] + direct = {id(n.func) for n in calls} + for node in ast.walk(tree): + name = getattr(node, 'id', None) or getattr(node, 'arg', None) or getattr(node, 'name', None) + if isinstance(node, ast.alias): + name = node.asname or node.name + if name == 'call_tool' and id(node) not in direct: + raise ValueError('call_tool can only be called directly, as call_tool("namespace.name", {...}).') + + available = {f"{t['namespace']}.{t['name']}": t for t in saved} + for key, tool in (chat_tools or {}).items(): + if tool.get('type') == 'mcp': + # The chat's key flattens server and tool; the client still has both. + client = tool['client'] + name = next( + (n for n in client.tool_definitions if re.sub(r'[^a-zA-Z0-9_-]', '_', f'{client.server_name}_{n}') == key), + None, + ) + if name is None: + continue + pair, source = (client.server_name, name), {'type': 'mcp', 'server_id': client.server_name} + elif tool.get('type') == 'terminal': + pair, source = ('machine', key), {'type': 'machine'} + elif tool.get('type') == 'builtin': + # Other built-ins need a chat around them. + if key != 'fetch_url': + continue + pair, source = ('builtin', key), {'type': 'builtin'} + else: + pair, source = (tool['tool_id'], key), {'type': 'tool', 'tool_id': tool['tool_id']} + available.setdefault( + f'{pair[0]}.{pair[1]}', {'namespace': pair[0], 'name': pair[1], 'source': {**source, 'name': pair[1]}} + ) + + tools = {} + for call in calls: + path = call.args[0] if call.args else None + if not (isinstance(path, ast.Constant) and isinstance(path.value, str)): + raise ValueError('call_tool needs a literal path, as call_tool("gmail.search_emails", {...}).') + path = path.value + if path not in available and request is not None: + from open_webui.utils.oauth import get_system_oauth_token + from open_webui.utils.tools import connect_mcp_server, get_tools + + extra_params = { + '__user__': user.model_dump(), + '__request__': request, + '__metadata__': {}, + '__event_emitter__': None, + '__event_call__': None, + '__oauth_token__': await get_system_oauth_token(request, user), + } + # A namespace may itself contain dots, so try each split, shortest namespace first. + parts = path.split('.') + for i in range(1, len(parts)): + namespace, name = '.'.join(parts[:i]), '.'.join(parts[i:]) + source = None + if namespace == 'machine': + source = {'type': 'machine'} + elif namespace == 'builtin': + source = {'type': 'builtin'} if name == 'fetch_url' else None + elif name in await get_tools(request, [namespace], user, extra_params): + source = {'type': 'tool', 'tool_id': namespace} + elif connected := await connect_mcp_server(request, namespace, user, extra_params): + client, _ = connected + if name in client.tool_definitions: + source = {'type': 'mcp', 'server_id': namespace} + await client.disconnect() + if source: + available[path] = {'namespace': namespace, 'name': name, 'source': {**source, 'name': name}} + break + if path not in available and request is not None: + raise ValueError(f'No tool "{path}" you can use.') + if path not in available: + choices = ', '.join(f'"{p}"' for p in sorted(available)) or 'none' + raise ValueError(f'No tool "{path}" in this chat. Available: {choices}.') + tools[path] = available[path] + return list(tools.values()) + + +async def execute_automation_code( + request: Request, + user, + automation: AutomationModel, + trigger: str, + event: Optional[dict] = None, + prints: Optional[list[str]] = None, +) -> Optional[AutomationCodeResult]: + """Run a code action once in the Monty sandbox. It reaches nothing but the tools it was approved for. + + What the program prints is appended to `prints`, kept even when the run fails. + """ + from open_webui.tools.builtin import fetch_url + from open_webui.utils.oauth import get_system_oauth_token + from open_webui.utils.tools import connect_mcp_server, get_machine_tools, get_tools + + action = automation.data['action'] + approved = {f"{t['namespace']}.{t['name']}": t['source'] for t in action.get('tools', [])} + machine = automation_machine_of(action) + extra_params = { + '__user__': user.model_dump(), + '__request__': request, + '__metadata__': { + 'automation_id': automation.id, + 'model_id': action['model_id'], + 'machine_id': machine.get('server_id'), + }, + '__event_emitter__': None, + '__event_call__': None, + '__oauth_token__': await get_system_oauth_token(request, user), + } + + async def call_tool(path: str, arguments: Optional[dict] = None): + source = approved.get(path) + if source is None: + raise ValueError(f'Tool "{path}" was not approved for this automation.') + arguments = arguments or {} + if source['type'] == 'mcp': + connected = await connect_mcp_server(request, source['server_id'], user, extra_params) + if not connected: + raise ValueError(f'MCP server {source["server_id"]} is not available.') + client, _ = connected + try: + raw = await client.call_tool_raw(source['name'], arguments) + finally: + await client.disconnect() + texts = [item['text'] for item in raw.get('content', []) if item.get('type') == 'text'] + if raw.get('isError'): + raise ValueError('\n'.join(texts) or 'The MCP tool returned an error.') + if raw.get('structuredContent') is not None: + return raw['structuredContent'] + result = '\n'.join(texts) + elif source['type'] == 'builtin': + result = await fetch_url(**arguments, __request__=request, __user__=user.model_dump()) + else: + if source['type'] == 'machine': + if not machine.get('server_id'): + raise ValueError(f'Tool "{path}" needs a machine; choose one in the automation\'s Machine row.') + tools = await get_machine_tools(request, machine.get('server_id'), user, extra_params) + tools = tools[0] if isinstance(tools, tuple) else tools + else: + tools = await get_tools(request, [source['tool_id']], user, extra_params) + if not tools or source['name'] not in tools: + raise ValueError(f'Tool "{path}" is not available.') + # A machine runs commands in the background unless asked to wait. Like OpenCode's shell in an + # automation, wait for the output; a command still running when the run's time is up fails the call. + if source['type'] == 'machine' and source['name'] == 'run_command': + arguments = {'wait': min(timeout, 300), **arguments} + result = await tools[source['name']]['callable'](**arguments) + result = result[0] if isinstance(result, tuple) else result + if source['type'] == 'machine' and source['name'] == 'run_command': + if result.get('status') == 'running': + await tools['kill_process']['callable'](process_id=result['id']) + raise ValueError(f'Command still running after {arguments["wait"]:g}s; stopped.') + # The shape of OpenCode's shell result: one output string with stdout and stderr together. + result = { + 'output': ''.join(item.get('data', '') for item in result.get('output', [])), + 'exit_code': result.get('exit_code'), + } + if isinstance(result, str): + try: + return json.loads(result) + except ValueError: + return result + # Values cross into the sandbox as JSON. + return json.loads(json.dumps(result, default=str)) + + # At most AUTOMATION_CODE_TIMEOUT, and done before its next scheduled run. + intervals = [ + await rrule_interval_seconds(t['rrule']) for t in automation.data['triggers'] if t['type'] == 'schedule' + ] + timeout = min([float(await Config.get('automations.code_timeout')), *(i for i in intervals if i)]) + zone = _resolve_tz(user.timezone) + async with AsyncMonty() as pool: + async with pool.checkout(limits={'max_feed_duration_secs': timeout}) as session: + value = await session.feed_run( + action['code'], + inputs={ + 'state': automation.state, + 'args': action.get('args'), + 'now': (datetime.now(zone) if zone else datetime.now().astimezone()).isoformat(), + 'trigger': {'type': trigger}, + 'event': event, + }, + external_lookup={'call_tool': call_tool}, + print_callback=None if prints is None else lambda _stream, text: prints.append(text), + ) + return None if value is None else AutomationCodeResult.model_validate(value) + + # Internals @@ -817,9 +1095,19 @@ async def _record_run( chat_id: str = None, error: str = None, actor=None, + output: str = None, + notify: bool = True, ): """Insert a run record into automation_run.""" async with get_async_db() as db: await AutomationRuns.insert( - automation_id, status, chat_id=chat_id, error=error, request=request, event_actor=actor, db=db + automation_id, + status, + chat_id=chat_id, + error=error, + output=output, + notify=notify, + request=request, + event_actor=actor, + db=db, ) diff --git a/backend/requirements-slim.txt b/backend/requirements-slim.txt index c561c4aabd..3253ff2f35 100644 --- a/backend/requirements-slim.txt +++ b/backend/requirements-slim.txt @@ -6,6 +6,7 @@ typer==0.25.1 fastapi==0.136.3 uvicorn[standard]==0.54.0 pydantic==2.13.4 +pydantic-monty==1.6.0 python-multipart==0.0.32 itsdangerous==2.2.0 diff --git a/backend/requirements.txt b/backend/requirements.txt index 3cbcf66ac9..d4925377c4 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,6 +1,7 @@ fastapi==0.136.3 uvicorn[standard]==0.54.0 pydantic==2.13.4 +pydantic-monty==1.6.0 python-multipart==0.0.32 itsdangerous==2.2.0 diff --git a/pyproject.toml b/pyproject.toml index 824e481410..725ceea028 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,7 @@ dependencies = [ "fastapi==0.136.3", "uvicorn[standard]==0.54.0", "pydantic==2.13.4", + "pydantic-monty==1.6.0", "python-multipart==0.0.32", "itsdangerous==2.2.0", diff --git a/src/lib/apis/automations/index.ts b/src/lib/apis/automations/index.ts index 3704148944..db466c34e2 100644 --- a/src/lib/apis/automations/index.ts +++ b/src/lib/apis/automations/index.ts @@ -28,21 +28,53 @@ export const startsNew = (target?: AutomationTarget | null) => export const repliesInThread = (target?: AutomationTarget | null) => target?.reply_in_thread !== false; +export type AutomationSchedule = { + type: 'schedule'; + rrule: string; +}; + export type AutomationWebhook = { + type: 'webhook'; /** Set by the server. */ token?: string | null; allow_get?: boolean; }; -export type AutomationData = { +export type AutomationTrigger = AutomationSchedule | AutomationWebhook; + +export type AutomationPromptAction = { + type: 'prompt'; prompt: string; model_id: string; - /** Empty: no schedule. */ - rrule: string; - machine?: AutomationMachineConfig; - terminal?: AutomationMachineConfig; // former name of machine, on automations saved before the rename + machine?: AutomationMachineConfig | null; target?: AutomationTarget | null; - webhook?: AutomationWebhook | null; +}; + +/** A tool a code action calls, as `call_tool(namespace, name, ...)`. */ +export type AutomationTool = { + namespace: string; + name: string; + source: Record; +}; + +/** Python run without a model on every trigger; a prompt it sends goes to `target` with `model_id`. */ +export type AutomationCodeAction = { + type: 'code'; + code: string; + args?: any; + model_id: string; + machine?: AutomationMachineConfig | null; + target?: AutomationTarget | null; + /** Set by the server. */ + tools: AutomationTool[]; +}; + +export type AutomationAction = AutomationPromptAction | AutomationCodeAction; + +export type AutomationData = { + /** Empty: run manually only. */ + triggers: AutomationTrigger[]; + action: AutomationAction; }; // Filled by the server, not the Run form. @@ -54,10 +86,12 @@ export const getRunVariables = (prompt: string): Record => Object.entries(extractInputVariables(prompt)).filter(([name]) => !BUILTIN_VARIABLE.test(name)) ); -export const getAutomationHookUrl = (automation: { id: string; data: AutomationData }) => - automation.data.webhook?.token - ? `${window.location.origin}${WEBUI_API_BASE_URL}/automations/hooks/${automation.id}/${automation.data.webhook.token}` +export const getAutomationHookUrl = (automation: { id: string; data: AutomationData }) => { + const webhook = automation.data.triggers.find((trigger) => trigger.type === 'webhook'); + return webhook?.type === 'webhook' && webhook.token + ? `${window.location.origin}${WEBUI_API_BASE_URL}/automations/hooks/${automation.id}/${webhook.token}` : ''; +}; export type AutomationForm = { name: string; @@ -78,6 +112,8 @@ export type AutomationRunModel = { chat_id: string | null; status: string; error: string | null; + /** What a code run printed, then what it returned as JSON. */ + output: string | null; created_at: number; }; @@ -91,6 +127,8 @@ export type AutomationResponse = { is_active: boolean; last_run_at: number | null; next_run_at: number | null; + /** A code action's state between runs. */ + state?: any; created_at: number; updated_at: number; diff --git a/src/lib/components/AutomationModal.svelte b/src/lib/components/AutomationModal.svelte index aa43aa8406..659a0433ff 100644 --- a/src/lib/components/AutomationModal.svelte +++ b/src/lib/components/AutomationModal.svelte @@ -5,6 +5,7 @@ import Modal from '$lib/components/common/Modal.svelte'; import XMark from '$lib/components/icons/XMark.svelte'; import Spinner from '$lib/components/common/Spinner.svelte'; + import CodeEditor from '$lib/components/common/CodeEditor.svelte'; import ScheduleDropdown from '$lib/components/automations/ScheduleDropdown.svelte'; import ModelDropdown from '$lib/components/automations/ModelDropdown.svelte'; @@ -25,7 +26,6 @@ type AutomationForm, type AutomationResponse } from '$lib/apis/automations'; - import { automationMachineOf } from '$lib/utils/machines'; const i18n = getContext('i18n'); const dispatch = createEventDispatcher(); @@ -38,6 +38,8 @@ let name = ''; let prompt = ''; + let code = ''; + let action_type: 'prompt' | 'code' = 'prompt'; let model_id = ''; let machineServerId = ''; let machineCwd = ''; @@ -108,7 +110,7 @@ $: allowWebhook = !!$config?.features?.enable_automation_webhooks; const submitHandler = async () => { - if (!name.trim() || !prompt.trim() || !model_id.trim()) { + if (!name.trim() || !(action_type === 'code' ? code : prompt).trim() || !model_id.trim()) { toast.error($i18n.t('Name, prompt, and model are required')); return; } @@ -130,23 +132,35 @@ loading = true; try { const rrule = scheduleDropdown.buildRrule(); - const sourceRrule = (automation ?? cloneFrom)?.data.rrule; + // The modal edits the first schedule; any others are kept as they are. + const sourceRrules = ((automation ?? cloneFrom)?.data.triggers ?? []).flatMap((trigger) => + trigger.type === 'schedule' ? [trigger.rrule] : [] + ); const form: AutomationForm = { name: name.trim(), folder_id: target_type === 'channel' ? null : folder_id || null, data: { - prompt: prompt.trim(), - model_id: model_id.trim(), - // An untouched schedule keeps its stored start date. - rrule: sourceRrule && rrule === savedRrule ? sourceRrule : rrule, - webhook: webhookEnabled ? { allow_get: webhookAllowGet } : null, - machine: machineServerId - ? { server_id: machineServerId, cwd: machineCwd.trim() || undefined } - : undefined, - target: - target_type === 'channel' - ? { type: 'channel', channel_id, new_thread: start_new, reply_in_thread } - : { type: 'chat', new_chat: start_new } + triggers: [ + // An untouched schedule keeps its stored start date. + ...[(rrule === savedRrule && sourceRrules[0]) || rrule, ...sourceRrules.slice(1)] + .filter(Boolean) + .map((rrule) => ({ type: 'schedule' as const, rrule })), + ...(webhookEnabled ? [{ type: 'webhook' as const, allow_get: webhookAllowGet }] : []) + ], + action: { + // The server works out a code action's tools from the code. + ...(action_type === 'code' + ? { type: 'code' as const, code, tools: [] } + : { type: 'prompt' as const, prompt: prompt.trim() }), + model_id: model_id.trim(), + machine: machineServerId + ? { server_id: machineServerId, cwd: machineCwd.trim() || undefined } + : undefined, + target: + target_type === 'channel' + ? { type: 'channel', channel_id, new_thread: start_new, reply_in_thread } + : { type: 'chat', new_chat: start_new } + } }, is_active }; @@ -184,43 +198,61 @@ channelsLoaded = true; } - machineServerId = automationMachineOf((automation ?? cloneFrom)?.data)?.server_id ?? ''; - machineCwd = automationMachineOf((automation ?? cloneFrom)?.data)?.cwd ?? ''; + machineServerId = (automation ?? cloneFrom)?.data.action.machine?.server_id ?? ''; + machineCwd = (automation ?? cloneFrom)?.data.action.machine?.cwd ?? ''; if (automation) { name = automation.name; - prompt = automation.data.prompt; - model_id = automation.data.model_id; + prompt = automation.data.action.type === 'prompt' ? automation.data.action.prompt : ''; + code = automation.data.action.type === 'code' ? automation.data.action.code : ''; + action_type = automation.data.action.type; + model_id = automation.data.action.model_id; folder_id = automation.folder_id ?? ''; - target_type = automation.data.target?.type === 'channel' ? 'channel' : 'chat'; - channel_id = automation.data.target?.channel_id ?? ''; - start_new = startsNew(automation.data.target); - reply_in_thread = repliesInThread(automation.data.target); + target_type = automation.data.action.target?.type === 'channel' ? 'channel' : 'chat'; + channel_id = automation.data.action.target?.channel_id ?? ''; + start_new = startsNew(automation.data.action.target); + reply_in_thread = repliesInThread(automation.data.action.target); is_active = automation.is_active; - webhookEnabled = !!automation.data.webhook; - webhookAllowGet = !!automation.data.webhook?.allow_get; - scheduleDropdown?.parseRrule(automation.data.rrule); + webhookEnabled = automation.data.triggers.some((trigger) => trigger.type === 'webhook'); + webhookAllowGet = automation.data.triggers.some( + (trigger) => trigger.type === 'webhook' && !!trigger.allow_get + ); + scheduleDropdown?.parseRrule( + automation.data.triggers.flatMap((trigger) => + trigger.type === 'schedule' ? [trigger.rrule] : [] + )[0] ?? '' + ); } else if (cloneFrom) { name = cloneFrom.name; - prompt = cloneFrom.data.prompt; - model_id = cloneFrom.data.model_id; + prompt = cloneFrom.data.action.type === 'prompt' ? cloneFrom.data.action.prompt : ''; + code = cloneFrom.data.action.type === 'code' ? cloneFrom.data.action.code : ''; + action_type = cloneFrom.data.action.type; + model_id = cloneFrom.data.action.model_id; folder_id = ($folders ?? []).some((folder) => folder.id === cloneFrom.folder_id) ? (cloneFrom.folder_id ?? '') : ''; - target_type = cloneFrom.data.target?.type === 'channel' ? 'channel' : 'chat'; + target_type = cloneFrom.data.action.target?.type === 'channel' ? 'channel' : 'chat'; channel_id = ($channels ?? []).some( - (channel) => channel.id === cloneFrom.data.target?.channel_id + (channel) => channel.id === cloneFrom.data.action.target?.channel_id ) - ? (cloneFrom.data.target?.channel_id ?? '') + ? (cloneFrom.data.action.target?.channel_id ?? '') : ''; - start_new = startsNew(cloneFrom.data.target); - reply_in_thread = repliesInThread(cloneFrom.data.target); + start_new = startsNew(cloneFrom.data.action.target); + reply_in_thread = repliesInThread(cloneFrom.data.action.target); is_active = true; - webhookEnabled = !!cloneFrom.data.webhook; - webhookAllowGet = !!cloneFrom.data.webhook?.allow_get; - scheduleDropdown?.parseRrule(cloneFrom.data.rrule); + webhookEnabled = cloneFrom.data.triggers.some((trigger) => trigger.type === 'webhook'); + webhookAllowGet = cloneFrom.data.triggers.some( + (trigger) => trigger.type === 'webhook' && !!trigger.allow_get + ); + scheduleDropdown?.parseRrule( + cloneFrom.data.triggers.flatMap((trigger) => + trigger.type === 'schedule' ? [trigger.rrule] : [] + )[0] ?? '' + ); } else { name = ''; prompt = ''; + code = ''; + action_type = 'prompt'; model_id = ''; folder_id = folderId ?? ''; target_type = 'chat'; @@ -260,18 +292,41 @@ - +
- -