Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat: run approved assistant deployments through persistent recipe operations

Juan Denise955134e4199
diff --git a/backend/app/services/ai_operations.py b/backend/app/services/ai_operations.py
new file mode 100644
index 00000000..b9328448
--- /dev/null
+++ b/backend/app/services/ai_operations.py
@@ -0,0 +1,448 @@
+"""Agent-facing deployment workflows backed by Recipes and DeploymentJobs.
+
+Proposals contain only public inputs, are signed, caller-bound and expire.
+Their UUID is the deployment primary key: replay reconnects to the same run.
+No shell, provider credential or arbitrary URL is exposed as an AI tool.
+"""
+import hashlib
+import json
+import re
+import threading
+import uuid
+from functools import wraps
+
+from flask import current_app
+from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
+
+from app import db
+from app.exceptions import ValidationError
+
+_launch_lock = threading.RLock()
+PROPOSAL_TTL = 900
+
+
+def _caller():
+ from app.services.ai_tools_builtin import _caller as caller
+ return caller(admin=True)
+
+
+def _serializer():
+ return URLSafeTimedSerializer(current_app.config['SECRET_KEY'], salt='ai-deployment-v1')
+
+
+def _digest(value):
+ return hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode()).hexdigest()
+
+
+def _template(template_id):
+ from app.services.template_service import TemplateService
+ if not isinstance(template_id, str) or not re.fullmatch(r'[\w-]{1,100}', template_id):
+ raise ValidationError('Choose a template ID from the catalog.')
+ result = TemplateService.get_template(template_id)
+ if not result.get('success'):
+ raise ValidationError('Template unavailable. Refresh the catalog.')
+ return result['template']
+
+
+def _variables(template):
+ raw = template.get('variables') or {}
+ return ({v['name']: v for v in raw if isinstance(v, dict) and 'name' in v}
+ if isinstance(raw, list) else raw)
+
+
+def _public_variables(template, variables):
+ from app.utils.sensitive_data_filter import SENSITIVE_KEY_PARTS
+ if not isinstance(variables, dict) or len(json.dumps(variables)) > 2048:
+ raise ValidationError('Supply at most 2048 characters of public template variables.')
+ specs = _variables(template)
+ for key, value in variables.items():
+ spec = specs.get(key)
+ if not isinstance(spec, dict):
+ raise ValidationError('Unknown template variable.')
+ if (spec.get('type') in ('password', 'random', 'uuid') or spec.get('secret')
+ or any(part.lower() in key.lower() for part in SENSITIVE_KEY_PARTS)):
+ raise ValidationError('Use the deployment form for credentials; never put secrets in chat.')
+ if not isinstance(value, (str, int, float, bool)):
+ raise ValidationError('Template variables must be scalar values.')
+ return variables
+
+
+def _target(server_id):
+ from app.models.server import Server
+ from app.services.agent_registry import agent_registry
+ if server_id == 'local':
+ return {'id': 'local', 'name': 'Panel host', 'online': True}
+ server = db.session.get(Server, server_id) if isinstance(server_id, str) else None
+ if server is None:
+ raise ValidationError('Select an existing server ID or explicitly use local.')
+ return {'id': server.id, 'name': server.name,
+ 'online': agent_registry.is_agent_connected(server.id)}
+
+
+def _proposal(data):
+ user = _caller()
+ return _serializer().dumps({**data, 'user_id': user.id,
+ 'auth_version': user.auth_version, 'id': str(uuid.uuid4())})
+
+
+def _proposal_result(data):
+ from app.services.ai_management import settings
+ result = {'success': True, 'preview': data['preview'],
+ 'expires_in_seconds': PROPOSAL_TTL, 'proposal': _proposal(data)}
+ # Prompture truncates serialized tool results. Never hand the model a
+ # partial approval token, even when an operator lowers the output budget.
+ if len(json.dumps(result)) > settings()['max_tool_result_length']:
+ raise ValidationError('Preview exceeds the AI tool output limit. Use the deployment form or increase that limit.')
+ return result
+
+
+def decode_proposal(proposal, user):
+ if not isinstance(proposal, str) or len(proposal) > 12000:
+ raise ValidationError('Invalid deployment proposal.')
+ try:
+ data = _serializer().loads(proposal, max_age=PROPOSAL_TTL)
+ except (BadSignature, SignatureExpired):
+ raise ValidationError('Proposal expired or changed. Prepare a new preview.') from None
+ if user is None or data.get('user_id') != user.id or data.get('auth_version') != user.auth_version:
+ raise PermissionError('This proposal belongs to a different session owner.')
+ return data
+
+
+def proposal_details(proposal, user):
+ """Server-derived approval text; the model cannot substitute a summary."""
+ data = decode_proposal(proposal, user)
+ return data['preview']
+
+
+def list_deployment_templates(search: str = '', offset: int = 0) -> dict:
+ """Find installable application templates. Browse before preparing a deployment.
+
+ Args:
+ search: Application name or category to search for.
+ offset: Pagination offset; ten entries are returned at a time.
+ """
+ _caller()
+ from app.services.template_service import TemplateService
+ rows = TemplateService.list_all_templates(search=search[:100])
+ offset = max(0, int(offset))
+ fields = ('id', 'name', 'description', 'version', 'kind')
+ return {'templates': [{k: str(r.get(k, ''))[:180] for k in fields}
+ for r in rows[offset:offset + 10]],
+ 'total': len(rows), 'next_offset': offset + 10 if offset + 10 < len(rows) else None}
+
+
+def get_deployment_template(template_id: str) -> dict:
+ """Inspect a template's public inputs before preparing a proposal.
+
+ Args:
+ template_id: ID returned by list_deployment_templates.
+ """
+ _caller()
+ template = _template(template_id)
+ fields = ('description', 'type', 'required', 'options')
+ return {'id': template_id, 'name': template.get('name'),
+ 'variables': [{'name': name, **{k: spec.get(k) for k in fields}}
+ for name, spec in _variables(template).items()],
+ 'credentials': 'Generated credentials stay on the server. Use the deployment form for secret inputs.'}
+
+
+def inspect_deployment_target(server_id: str) -> dict:
+ """Inspect connectivity and reported capabilities of a deployment target.
+
+ Args:
+ server_id: Fleet server ID, or local for the panel host.
+ """
+ _caller()
+ target = _target(server_id)
+ if server_id == 'local':
+ from app.services.docker_service import DockerService
+ target['docker_installed'] = DockerService.is_docker_installed()
+ else:
+ from app.services.agent_registry import agent_registry
+ target['capabilities'] = agent_registry.get_capabilities(server_id)
+ return target
+
+
+def prepare_template_deployment(template_id: str, app_name: str, server_id: str,
+ variables: dict = None, auto_domain: bool = False) -> dict:
+ """Preview a new template deployment without installing anything; returns a signed proposal.
+
+ Args:
+ template_id: Catalog template ID.
+ app_name: Unique service name, at least three characters.
+ server_id: Explicit fleet server ID or local for the panel host.
+ variables: Public template inputs only. Never supply credentials in chat.
+ auto_domain: Whether to request automatic domain publication.
+ """
+ _caller()
+ from app.models import Application
+ from app.utils.slug import validate_app_name
+ from app.services.template_service import TemplateService
+ valid, error = validate_app_name(app_name, min_length=3)
+ if not valid:
+ raise ValidationError(error)
+ target = _target(server_id)
+ if not target['online']:
+ raise ValidationError('Target server is offline.')
+ if Application.query.filter_by(name=app_name, server_id=None if server_id == 'local' else server_id).first():
+ raise ValidationError('That application name is already reserved on this server.')
+ template = _template(template_id)
+ if template.get('kind', 'compose') != 'compose':
+ raise ValidationError('Use the repository deployment form for this template kind.')
+ variables = _public_variables(template, variables or {})
+ if auto_domain and server_id != 'local':
+ raise ValidationError('Automatic domain publication is only supported on the panel host.')
+ # Render to validate required inputs and provider preflight; never expose generated secrets.
+ result = TemplateService.build_install_plan(template_id, app_name, variables,
+ server_id=None if server_id == 'local' else server_id,
+ auto_domain=auto_domain)
+ if not result.get('success'):
+ return {'success': False, 'error': result.get('error', 'Template preflight failed')}
+ if _digest(result['template']) != _digest({**template, 'auto_domain': True} if auto_domain else template):
+ raise ValidationError('Template changed during preview. Prepare it again.')
+ preview = {'action': 'Install template and verify container state',
+ 'template': template_id, 'application': app_name, 'server': target,
+ 'variables': variables,
+ 'auto_domain': bool(auto_domain or template.get('auto_domain')) and server_id == 'local',
+ 'ports': 'Allocated when execution starts',
+ 'verification': 'Running containers and configured Docker health checks; not an HTTP or login test.'}
+ return _proposal_result({'kind': 'template', 'template_id': template_id,
+ 'app_name': app_name, 'server_id': server_id,
+ 'variables': variables, 'auto_domain': bool(auto_domain),
+ 'digest': _digest(template), 'preview': preview})
+
+
+def list_deployment_recipes() -> dict:
+ """List recipe availability, including missing handlers. Unsupported recipes cannot run."""
+ _caller()
+ from app.services import recipe_registry_service
+ from app.services.recipe_execution_service import RecipeExecutionService, RecipeStepRegistry
+ RecipeExecutionService.register_jobs()
+ rows = []
+ for entry in recipe_registry_service.list_catalog():
+ missing = [c for c in entry.get('capabilities', []) if not RecipeStepRegistry.supports(c)]
+ rows.append({'slug': entry['slug'], 'name': entry['name'],
+ 'supported': not missing, 'unsupported_capabilities': missing})
+ return {'recipes': rows}
+
+
+def prepare_recipe_deployment(registry_slug: str, project_id: int) -> dict:
+ """Preview a catalog recipe for an existing project. Secret handoffs stay in Operations.
+
+ Args:
+ registry_slug: Slug returned by list_deployment_recipes.
+ project_id: Existing ServerKit project ID.
+ """
+ _caller()
+ from app.models.project import Project
+ from app.services import recipe_registry_service
+ from app.services.manifest_spec_service import ManifestSpecService
+ from app.services.manifest_apply_service import ManifestApplyService
+ from app.services.recipe_execution_service import RecipeExecutionService
+ project = db.session.get(Project, project_id)
+ if project is None:
+ raise ValidationError('Select an existing project.')
+ text = recipe_registry_service.get_manifest_text(registry_slug)
+ normalized = ManifestSpecService.normalize_text(text)
+ RecipeExecutionService.register_jobs()
+ missing = RecipeExecutionService.unsupported_capabilities(normalized)
+ plan = ManifestApplyService.plan(project, normalized)
+ if missing or plan.get('blockers'):
+ return {'success': False, 'unsupported_capabilities': missing,
+ 'blockers': plan.get('blockers', [])}
+ preview = {'action': 'Run catalog recipe', 'recipe': registry_slug,
+ 'project_id': project.id, 'project': project.name,
+ 'changes': [s.get('description') for s in plan.get('steps', [])],
+ 'steps': [s.get('title') for s in normalized.get('configure', []) + normalized.get('verify', [])],
+ 'handoffs': 'Supply requested credentials directly in Operations, never in chat.'}
+ return _proposal_result({'kind': 'recipe', 'registry_slug': registry_slug,
+ 'project_id': project_id, 'digest': _digest(normalized),
+ 'preview': preview})
+
+
+def execute_deployment_proposal(proposal: str) -> dict:
+ """Start an approved deployment in Operations. Reusing the proposal returns the same run.
+
+ Args:
+ proposal: Exact signed proposal returned by a prepare tool. Requires human approval.
+ """
+ user = _caller()
+ data = decode_proposal(proposal, user)
+ from app.models.deployment_job import DeploymentJob
+ from app.services.recipe_execution_service import RecipeExecutionService
+ from app.services.manifest_spec_service import ManifestSpecService
+ from app.models.project import Project
+ with _launch_lock:
+ existing = db.session.get(DeploymentJob, data['id'])
+ if existing:
+ if existing.requested_by != user.id:
+ raise PermissionError('Operation belongs to a different user.')
+ return get_deployment_operation(existing.id)
+ if data['kind'] == 'template':
+ if _digest(_template(data['template_id'])) != data['digest']:
+ raise ValidationError('Template changed. Prepare and approve a new preview.')
+ if not _target(data['server_id'])['online']:
+ raise ValidationError('Target server is offline.')
+ if data['server_id'] != 'local':
+ project = RecipeExecutionService.get_or_create_project(
+ RecipeExecutionService.get_server(data['server_id']))
+ else:
+ from app.services.workspace_service import WorkspaceService
+ workspace = WorkspaceService.ensure_default_workspace()
+ project = Project.query.filter_by(workspace_id=workspace.id, slug='recipes').first()
+ if project is None:
+ project = Project(workspace_id=workspace.id, slug='recipes', name='Recipes')
+ db.session.add(project)
+ db.session.flush()
+ normalized = ManifestSpecService.normalize({
+ 'version': 1, 'capabilities': ['apply:template.install', 'verify:application.health'],
+ 'configure': [{'id': 'install', 'type': 'apply', 'kind': 'template.install',
+ 'title': 'Install ' + data['app_name'], 'params': data}],
+ 'verify': [{'id': 'verify', 'kind': 'application.health', 'dependsOn': ['install'],
+ 'title': 'Verify running containers', 'params': {'install_step': 'install'}}],
+ })
+ else:
+ from app.services import recipe_registry_service
+ normalized = ManifestSpecService.normalize_text(
+ recipe_registry_service.get_manifest_text(data['registry_slug']))
+ if _digest(normalized) != data['digest']:
+ raise ValidationError('Recipe changed. Prepare and approve a new preview.')
+ project = db.session.get(Project, data['project_id'])
+ if project is None:
+ raise ValidationError('Project no longer exists.')
+ result = RecipeExecutionService.start(project, normalized, user_id=user.id,
+ title=data['preview'].get('application') or data['registry_slug'],
+ job_id=data['id'], server_id=data.get('server_id'))
+ if not result.get('success'):
+ return {'success': False, 'error': result.get('error'),
+ 'unsupported_capabilities': result.get('unsupported_capabilities', [])}
+ return get_deployment_operation(result['job_id'])
+
+
+def get_deployment_operation(job_id: str, after_log_id: int = 0) -> dict:
+ """Read a persistent deployment and a bounded log page. Queued is not deployed or healthy.
+
+ Args:
+ job_id: Deployment operation UUID returned by execute_deployment_proposal.
+ after_log_id: Log cursor from the previous response; zero starts at the beginning.
+ """
+ _caller()
+ from app.models.deployment_job import DeploymentJob, DeploymentJobLog
+ job = db.session.get(DeploymentJob, job_id)
+ if job is None:
+ raise ValidationError('Deployment operation not found.')
+ rows = DeploymentJobLog.query.filter(DeploymentJobLog.job_id == job.id,
+ DeploymentJobLog.id > max(0, int(after_log_id))).order_by(DeploymentJobLog.id).limit(10).all()
+ state = job.get_result() or {}
+ return {'success': job.status != 'failed', 'operation': {'run_kind': 'deploy', 'id': job.id},
+ 'status': job.status, 'app_id': job.app_id, 'current_step': job.current_step,
+ 'total_steps': job.total_steps, 'error': (job.error_message or '')[:300] or None,
+ 'verified': bool(state.get('verified')), 'requires_action': job.status == 'waiting',
+ 'next_action': 'Open Operations to supply handoff inputs or retry a failed run.' if job.status in ('waiting', 'failed') else
+ 'Check this operation again later. Do not launch a duplicate.' if job.status in ('pending', 'running') else
+ 'Inspect verification evidence before reporting success.',
+ 'evidence': _operation_evidence(state),
+ 'logs': [{'id': r.id, 'level': r.level, 'message': r.message[:120],
+ 'truncated': len(r.message) > 120} for r in rows],
+ 'next_log_id': rows[-1].id if rows else after_log_id}
+
+
+def _operation_evidence(state):
+ fields = ('app_id', 'name', 'server_id', 'port', 'url', 'runtime_verified',
+ 'application_health_verified', 'scope', 'job_id')
+ evidence = {}
+ for name, step in list(state.get('completed_steps', {}).items())[-3:]:
+ result = step.get('result') or {}
+ if isinstance(result, dict):
+ evidence[name[:80]] = {k: (v[:180] if isinstance(v, str) else v)
+ for k, v in result.items() if k in fields
+ and isinstance(v, (str, int, float, bool, type(None)))}
+ return evidence
+
+
+def get_application_health(app_id: int) -> dict:
+ """Read fresh container state. Running without a health check is not verified application health.
+
+ Args:
+ app_id: ServerKit application ID.
+ """
+ _caller()
+ from app.models import Application
+ from app.services.container_status_service import get_app_status
+ app = Application.query_active().filter_by(id=app_id).first()
+ if app is None:
+ raise ValidationError('Application not found.')
+ status = get_app_status(app.id, use_cache=False)
+ containers = status.get('containers') or []
+ return {'app_id': app.id, 'name': app.name, 'server_id': app.server_id or 'local',
+ 'runtime': status, 'application_health_verified': bool(containers) and
+ all(c.get('state') == 'running' and c.get('health') == 'healthy' for c in containers),
+ 'verification_scope': 'Container state and configured Docker health checks only.'}
+
+
+def list_deployment_projects() -> dict:
+ """List projects available for a catalog recipe, including their IDs and workspace IDs."""
+ _caller()
+ from app.models.project import Project
+ return {'projects': [{'id': p.id, 'name': p.name, 'workspace_id': p.workspace_id}
+ for p in Project.query.order_by(Project.id).limit(50).all()]}
+
+
+def get_application_details(app_id: int) -> dict:
+ """Inspect an application, its domains and deployment history without exposing configuration secrets.
+
+ Args:
+ app_id: ServerKit application ID.
+ """
+ _caller()
+ from app.models import Application
+ from app.models.deployment_job import DeploymentJob
+ app = Application.query_active().filter_by(id=app_id).first()
+ if app is None:
+ raise ValidationError('Application not found.')
+ jobs = DeploymentJob.query.filter_by(app_id=app.id).order_by(DeploymentJob.created_at.desc()).limit(5).all()
+ return {'id': app.id, 'name': app.name, 'status': app.status,
+ 'server_id': app.server_id or 'local', 'project_id': app.project_id,
+ 'port': app.port, 'domains': [d.name for d in app.live_domains],
+ 'deployments': [{'id': j.id, 'status': j.status} for j in jobs]}
+
+
+def get_docker_container_logs(container_id: str, tail: int = 30) -> dict:
+ """Read bounded container logs on the panel host. For remote deployments use operation logs.
+
+ Args:
+ container_id: Container ID or name from list_docker_containers.
+ tail: Number of recent lines, from 1 to 50.
+ """
+ _caller()
+ from app.services.docker_service import DockerService
+ if not isinstance(container_id, str) or not re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}', container_id):
+ raise ValidationError('Invalid container ID or name.')
+ result = DockerService.get_container_logs(container_id, tail=max(1, min(50, int(tail))))
+ if not result.get('success'):
+ return {'success': False, 'error': 'Container logs are unavailable.'}
+ return {'success': True, 'container_id': container_id, 'logs': str(result.get('logs', ''))[-3000:]}
+
+
+def _tool_result(func):
+ @wraps(func)
+ def invoke(**kwargs):
+ try:
+ return func(**kwargs)
+ except ValidationError as exc:
+ # These are deliberate public input errors. The AI wrapper still
+ # applies its normal secret/PII filter to this structured result.
+ return {'success': False, 'error': str(exc)}
+ return invoke
+
+
+def register_tools(registry):
+ reads = (list_deployment_templates, get_deployment_template, inspect_deployment_target,
+ prepare_template_deployment, list_deployment_recipes, prepare_recipe_deployment,
+ get_deployment_operation, get_application_health, list_deployment_projects,
+ get_application_details, get_docker_container_logs)
+ for func in reads:
+ registry.register(name=func.__name__, func=_tool_result(func), admin_only=True,
+ rbac_feature='applications', rbac_level='read')
+ registry.register(name='execute_deployment_proposal', func=_tool_result(execute_deployment_proposal),
+ admin_only=True, rbac_feature='applications', is_write=True)
diff --git a/backend/app/services/ai_service.py b/backend/app/services/ai_service.py
index a2638258..2b3888a3 100644
--- a/backend/app/services/ai_service.py
+++ b/backend/app/services/ai_service.py
@@ -112,6 +112,16 @@ SYSTEM_BASE = (
"corresponding tool — it will pause for explicit human confirmation before "
"anything actually runs. Never claim you performed an action unless a tool "
"result confirms it."
+ " For deployment requests, inspect the target and catalog, then prepare a proposal. "
+ "Show its scope before calling execute_deployment_proposal with the unchanged proposal. "
+ "That tool still requires human approval. Keep the returned operation ID: a queued run "
+ "continues in Operations after chat closes. Use get_deployment_operation for progress "
+ "and logs; never start another deployment just because a run is pending. Avoid tight "
+ "polling loops: report the operation and let the user follow it or ask for an update. "
+ "Only report deployment success after the operation succeeds, and state the verification "
+ "scope. Running containers without health checks do not prove application health. "
+ "Never request credentials in chat; direct secret handoffs to Operations. Unsupported "
+ "recipe capabilities are blockers, not instructions to improvise shell commands."
)
# Guardrail detectors (cheap, regex-based) — built once, on first use. They are
@@ -519,6 +529,8 @@ def _audit_tool_execute(descriptor, params, user, *, ok: bool, error: Optional[s
def summarize_action(descriptor, params: dict) -> str:
+ if getattr(descriptor, 'qualified_name', None) == 'core__execute_deployment_proposal':
+ return 'Run the deployment described below. It continues in Operations after chat closes.'
first_line = (descriptor.description or descriptor.name).split("\n")[0].rstrip(".")
if params:
kv = ", ".join(f"{k}={v}" for k, v in params.items())
@@ -734,6 +746,12 @@ class ConfirmationGate:
token = secrets.token_urlsafe(16)
summary = summarize_action(descriptor, params)
+ display_params = params
+ if descriptor.qualified_name == 'core__execute_deployment_proposal':
+ from app.models.user import User
+ from app.services.ai_operations import proposal_details
+ caller = db.session.get(User, self.user_id, populate_existing=True)
+ display_params = proposal_details(params.get('proposal'), caller)
row = AiPendingAction(
id=token, conversation_id=self.conversation_id, user_id=self.user_id,
tool_name=descriptor.qualified_name, plugin_slug=descriptor.plugin_slug,
@@ -756,6 +774,7 @@ class ConfirmationGate:
"action_token": token, "tool_name": descriptor.qualified_name,
"name": descriptor.name, "plugin_slug": descriptor.plugin_slug,
"summary": summary, "params": params, "is_write": True,
+ "display_params": display_params,
})
signaled = ev.wait(timeout=self._ttl)
diff --git a/backend/app/services/ai_tools_builtin.py b/backend/app/services/ai_tools_builtin.py
index 336138bf..523b0d5b 100644
--- a/backend/app/services/ai_tools_builtin.py
+++ b/backend/app/services/ai_tools_builtin.py
@@ -194,5 +194,7 @@ def register_builtin_tools() -> None:
rbac_feature="docker", is_write=True, admin_only=True,
)
+ from app.services.ai_operations import register_tools
+ register_tools(ai_tool_registry)
_REGISTERED = True
- logger.info("Registered %d built-in AI tools", 8)
+ logger.info("Registered core AI tools")
diff --git a/backend/app/services/deployment_job_service.py b/backend/app/services/deployment_job_service.py
index cfa4e598..c75a1526 100644
--- a/backend/app/services/deployment_job_service.py
+++ b/backend/app/services/deployment_job_service.py
@@ -40,6 +40,8 @@ class DeploymentJobService:
server_id: Optional[str] = None,
wait: bool = False,
auto_domain: Optional[bool] = None,
+ job_id: Optional[str] = None,
+ expected_template_digest: Optional[str] = None,
) -> Dict:
"""Create a template installation job and optionally run it synchronously."""
normalized_server_id = cls._normalize_server_id(server_id)
@@ -69,6 +71,10 @@ class DeploymentJobService:
)
if not plan_result.get('success'):
return plan_result
+ if expected_template_digest is not None:
+ from app.services.ai_operations import _digest
+ if _digest(plan_result['template']) != expected_template_digest:
+ return {'success': False, 'error': 'Template changed after approval; prepare a new proposal.'}
app_path = plan_result['app_path']
if not normalized_server_id and os.path.exists(app_path):
@@ -85,7 +91,7 @@ class DeploymentJobService:
logger.info('Reusing abandoned install directory %s', app_path)
job = DeploymentJob(
- id=str(uuid.uuid4()),
+ id=job_id or str(uuid.uuid4()),
kind='template_install',
status='pending',
target_server_id=normalized_server_id,
@@ -556,7 +562,8 @@ class DeploymentJobService:
@classmethod
def start_registered(cls, kind: str, *, steps=None, app_id=None, server_id=None,
- user_id=None, trigger='manual', plan=None, wait=False) -> Dict:
+ user_id=None, trigger='manual', plan=None, wait=False,
+ job_id=None) -> Dict:
"""Create and queue a DeploymentJob for a registered (plugin) kind.
The public entry point behind ``app.plugins_sdk.deploys.start`` — the
@@ -568,7 +575,7 @@ class DeploymentJobService:
return {'success': False, 'error': f'No handler registered for deployment kind "{kind}"'}
job = DeploymentJob(
- id=str(uuid.uuid4()),
+ id=job_id or str(uuid.uuid4()),
kind=kind,
status='pending',
app_id=app_id,
diff --git a/backend/app/services/recipe_builtin_steps.py b/backend/app/services/recipe_builtin_steps.py
new file mode 100644
index 00000000..5c583976
--- /dev/null
+++ b/backend/app/services/recipe_builtin_steps.py
@@ -0,0 +1,101 @@
+"""Small, closed Recipe capabilities for approved template deployments.
+
+Reuses the installer and live status collector. A resumed recipe never blindly
+replays an interrupted installation; it reconnects to its deterministic child job.
+"""
+import time
+import uuid
+
+from app import db
+
+
+def _authorized(context):
+ from app.models.user import User
+ user = db.session.get(User, context.job.requested_by, populate_existing=True)
+ if user is None or not user.is_active or not user.is_admin:
+ raise PermissionError('Deployment requires an active administrator.')
+ return user
+
+
+def install_template(context):
+ from app.models import Application
+ from app.models.deployment_job import DeploymentJob
+ from app.services.deployment_job_service import DeploymentJobService
+ from app.services.ai_operations import _template, _digest, _public_variables, _target
+ from app.utils.slug import validate_app_name
+
+ user = _authorized(context)
+ params = context.step.get('params') or {}
+ app_name = params.get('app_name', '')
+ valid, error = validate_app_name(app_name, min_length=3)
+ if not valid:
+ raise ValueError(error)
+ target = _target(params.get('server_id'))
+ template = _template(params.get('template_id'))
+ # Compare the effective template too: auto_domain may modify its top-level flag.
+ if _digest(template) != params.get('digest'):
+ raise ValueError('Template changed after approval. Prepare a new proposal.')
+ effective = {**template, 'auto_domain': True} if params.get('auto_domain') else template
+ variables = _public_variables(template, params.get('variables') or {})
+ child_id = str(uuid.uuid5(uuid.NAMESPACE_URL, f'serverkit:{context.job.id}:{context.step["id"]}'))
+ child = db.session.get(DeploymentJob, child_id)
+ if child is None:
+ if not target['online']:
+ raise ValueError('Target server is offline.')
+ result = DeploymentJobService.install_template(
+ template_id=params['template_id'], app_name=app_name,
+ user_variables=variables, user_id=user.id,
+ server_id=params['server_id'], auto_domain=params.get('auto_domain', False),
+ wait=True, job_id=child_id, expected_template_digest=_digest(effective))
+ child = db.session.get(DeploymentJob, child_id)
+ if child is None:
+ raise RuntimeError(result.get('error') or 'Installation could not start.')
+ if child.status != 'succeeded':
+ raise RuntimeError(f'Installation {child.id} is {child.status}. Inspect it in Operations; it will not be replayed.')
+ app = Application.query_active().filter_by(id=child.app_id).first()
+ if app is None:
+ raise RuntimeError('Installed application no longer exists.')
+ app.project_id = context.project.id
+ app.environment_id = getattr(context.environment, 'id', None)
+ app.workspace_id = context.project.workspace_id
+ context.job.app_id = app.id
+ context.job.target_server_id = app.server_id
+ db.session.commit()
+ # Never copy generated variables, compose content or credentials into tool evidence.
+ result = child.get_result() or {}
+ domain = result.get('auto_domain') or {}
+ return {'app_id': app.id, 'name': app.name, 'job_id': child.id,
+ 'server_id': app.server_id or 'local', 'port': app.port,
+ 'url': domain.get('url') if domain.get('success') else None}
+
+
+def verify_application(context):
+ from app.models import Application
+ from app.services.container_status_service import get_app_status
+ _authorized(context)
+ step_id = (context.step.get('params') or {}).get('install_step')
+ installed = (context.completed.get(step_id) or {}).get('result') or {}
+ app = Application.query_active().filter_by(id=installed.get('app_id')).first()
+ if app is None or app.project_id != context.project.id:
+ raise ValueError('Verification must reference an application installed by this recipe.')
+ # Bounded wait is in the persistent job worker, never the chat request.
+ deadline = time.monotonic() + 60
+ while True:
+ _authorized(context)
+ result = get_app_status(app.id, use_cache=False)
+ if result.get('status') == 'running:healthy' and result.get('total', 0) > 0:
+ containers = result.get('containers') or []
+ return {'app_id': app.id, 'runtime_verified': True,
+ 'application_health_verified': bool(containers) and
+ all(c.get('health') == 'healthy' for c in containers),
+ 'scope': 'Running containers and configured Docker health checks; no HTTP/login test.',
+ 'containers': containers}
+ if time.monotonic() >= deadline:
+ raise RuntimeError('Container verification did not pass within 60 seconds: ' + str(result.get('status')))
+ time.sleep(3)
+
+
+def register_steps():
+ from app.services.recipe_execution_service import RecipeStepRegistry
+ RecipeStepRegistry.register('apply', 'template.install', install_template, replace=True)
+ RecipeStepRegistry.register('verify', 'application.health', verify_application, replace=True)
diff --git a/backend/app/services/recipe_execution_service.py b/backend/app/services/recipe_execution_service.py
index 07394b54..a322cb3e 100644
--- a/backend/app/services/recipe_execution_service.py
+++ b/backend/app/services/recipe_execution_service.py
@@ -86,6 +86,8 @@ class RecipeStepRegistry:
if callable(check) and check(context):
return {'already_complete': True}
outcome = entry['handler'](context)
+ if isinstance(outcome, dict) and (outcome.get('success') is False or outcome.get('ok') is False):
+ raise RuntimeError(f'Recipe capability {capability} reported failure')
return outcome if isinstance(outcome, dict) else {'result': outcome}
@classmethod
@@ -126,6 +128,8 @@ class RecipeExecutionService:
@classmethod
def register_jobs(cls) -> None:
from app.services import deploy_kind_registry
+ from app.services.recipe_builtin_steps import register_steps
+ register_steps()
deploy_kind_registry.register(RECIPE_JOB_KIND, cls.run, replace=True)
@staticmethod
@@ -143,13 +147,15 @@ class RecipeExecutionService:
user_id: Optional[int], slug: Optional[str] = None,
title: Optional[str] = None, manifest_row=None,
params: Optional[Dict[str, str]] = None,
- wait: bool = False) -> Dict[str, Any]:
+ wait: bool = False, job_id: Optional[str] = None,
+ server_id: Optional[str] = None) -> Dict[str, Any]:
"""Create one Recipe run after capability and manifest preflight."""
recipe_steps = list(normalized.get('configure') or []) + list(
normalized.get('verify') or [])
if not recipe_steps:
return {'success': False, 'error': 'Manifest does not contain Recipe steps'}
+ cls.register_jobs()
unsupported = cls.unsupported_capabilities(normalized)
if unsupported:
return {
@@ -188,7 +194,6 @@ class RecipeExecutionService:
'step_id': step['id'], 'recipe_step': step,
})
- cls.register_jobs()
from app.services.deployment_job_service import DeploymentJobService
return DeploymentJobService.start_registered(
RECIPE_JOB_KIND,
@@ -196,6 +201,8 @@ class RecipeExecutionService:
user_id=user_id,
trigger='recipe',
wait=wait,
+ job_id=job_id,
+ server_id=server_id,
plan={
'recipe': {
'slug': slug or normalized.get('project') or 'inline',
diff --git a/backend/tests/test_ai_operations.py b/backend/tests/test_ai_operations.py
new file mode 100644
index 00000000..4b3d45ae
--- /dev/null
+++ b/backend/tests/test_ai_operations.py
@@ -0,0 +1,290 @@
+"""Agent workflow contracts: approve, queue, observe, verify and reconnect.
+
+The real registry, Recipe engine and deployment records run against SQLite.
+Only infrastructure I/O is replaced; no model key or Docker daemon is needed.
+"""
+import copy
+from contextlib import contextmanager
+
+import pytest
+
+from app import db
+from app.exceptions import ValidationError
+from app.models.deployment_job import DeploymentJob
+from app.services import ai_operations as ops, ai_service
+from app.services.ai_tools_builtin import register_builtin_tools, tool_caller
+from app.services.ai_tool_registry import ai_tool_registry
+from app.services.deployment_job_service import DeploymentJobService
+from app.services.template_service import TemplateService
+from factories import make_application, make_user
+
+
+@contextmanager
+def caller(user):
+ token = tool_caller.set(user)
+ try:
+ yield
+ finally:
+ tool_caller.reset(token)
+
+
+def setup(app, monkeypatch):
+ with app.app_context():
+ user = make_user(db, role='admin')
+ template = {'name': 'Example', 'version': '1', 'compose': {'services': {'web': {'image': 'nginx'}}},
+ 'variables': {'TITLE': {'type': 'string'}, 'PASSWORD': {'type': 'password'}}}
+ monkeypatch.setattr(TemplateService, 'get_template', lambda ident: {'success': True, 'template': copy.deepcopy(template)})
+ monkeypatch.setattr(TemplateService, 'build_install_plan', lambda *a, **kw: {
+ 'success': True,
+ 'template': {**template, 'auto_domain': True} if kw.get('auto_domain') else copy.deepcopy(template),
+ 'variables': {'PASSWORD': 'generated-do-not-leak'}, 'plan': {'steps': []}})
+ queued = []
+ monkeypatch.setattr(DeploymentJobService, '_enqueue_registered', lambda job: queued.append(job.id))
+ monkeypatch.setattr(ai_service, '_pii_enabled', lambda: False)
+ register_builtin_tools()
+ yield user, template, queued
+
+
+def prepare(user):
+ with caller(user):
+ return ops.prepare_template_deployment('nginx', 'demo-app', 'local', {'TITLE': 'Demo'})
+
+
+def test_preview_is_read_only_and_roundtrips_through_privacy_filter(setup):
+ user, _, queued = setup
+ descriptor = ai_tool_registry.get('core__prepare_template_deployment')
+ result = ai_service._make_read_wrapper(descriptor, user)(
+ template_id='nginx', app_name='demo-app', server_id='local')
+ assert result['success']
+ assert ops.decode_proposal(result['proposal'], user)['app_name'] == 'demo-app'
+ assert 'generated-do-not-leak' not in str(result)
+ assert DeploymentJob.query.count() == 0
+ assert not queued
+
+
+def test_proposal_rejects_tampering_other_user_and_expiry(setup, monkeypatch):
+ user, _, _ = setup
+ proposal = prepare(user)['proposal']
+ with pytest.raises(ValidationError):
+ ops.decode_proposal(proposal + 'changed', user)
+ other = make_user(db, role='admin')
+ with pytest.raises(PermissionError):
+ ops.decode_proposal(proposal, other)
+ monkeypatch.setattr(ops, 'PROPOSAL_TTL', -1)
+ with pytest.raises(ValidationError):
+ ops.decode_proposal(proposal, user)
+
+
+def test_small_tool_budget_never_returns_a_truncated_proposal(setup, monkeypatch):
+ from app.services import ai_management
+ user, _, queued = setup
+ monkeypatch.setattr(ai_management, 'settings', lambda: {'max_tool_result_length': 256})
+ wrapper = ai_service._make_read_wrapper(ai_tool_registry.get('core__prepare_template_deployment'), user)
+ result = wrapper(template_id='nginx', app_name='demo-app', server_id='local')
+ assert not result['success']
+ assert 'output limit' in result['error']
+ assert 'proposal' not in result
+ assert not queued
+
+
+def test_secrets_and_unsafe_template_paths_are_rejected(setup):
+ user, _, _ = setup
+ with caller(user):
+ with pytest.raises(ValidationError, match='credentials'):
+ ops.prepare_template_deployment('nginx', 'demo-app', 'local', {'PASSWORD': 'secret'})
+ with pytest.raises(ValidationError):
+ ops.get_deployment_template('../private')
+ with pytest.raises(ValidationError):
+ ops.prepare_template_deployment('nginx', '../escape', 'local')
+
+
+def test_changed_template_requires_new_approval(setup):
+ user, template, queued = setup
+ proposal = prepare(user)['proposal']
+ template['version'] = '2'
+ with caller(user), pytest.raises(ValidationError, match='changed'):
+ ops.execute_deployment_proposal(proposal)
+ assert not queued
+
+
+def test_worker_rechecks_template_after_queueing(setup):
+ user, template, _ = setup
+ with caller(user):
+ started = ops.execute_deployment_proposal(prepare(user)['proposal'])
+ template['version'] = 'changed-while-queued'
+ assert not DeploymentJobService.run_job(started['operation']['id'])['success']
+ assert DeploymentJob.query.count() == 1
+
+
+def test_installer_rejects_rendered_template_change_before_creating_job(setup):
+ user, _, _ = setup
+ result = DeploymentJobService.install_template(
+ 'nginx', 'demo-app', user_id=user.id, expected_template_digest='stale')
+ assert not result['success']
+ assert 'changed' in result['error']
+ assert DeploymentJob.query.count() == 0
+
+
[email protected]('outcome', [{'success': False}, {'ok': False}])
+def test_failed_handler_result_cannot_complete_a_recipe_step(setup, outcome):
+ from types import SimpleNamespace
+ from app.services.recipe_execution_service import RecipeStepRegistry
+ RecipeStepRegistry.register('verify', 'test.failure', lambda context: outcome, replace=True)
+ with pytest.raises(RuntimeError, match='reported failure'):
+ RecipeStepRegistry.execute(SimpleNamespace(step={'capability': 'verify:test.failure'}))
+
+
+def test_execute_requires_confirmation_and_admin(setup):
+ user, _, queued = setup
+ proposal = prepare(user)['proposal']
+ descriptor = ai_tool_registry.get('core__execute_deployment_proposal')
+ assert descriptor.is_write and descriptor.admin_only
+ assert not descriptor.allowed_for(make_user(db, role='viewer'))
+ assert not descriptor.allowed_for(make_user(db, role='developer'))
+ result = ai_service._make_write_wrapper(descriptor, user, None)(proposal=proposal)
+ assert 'confirmation' in result
+ assert not queued
+
+
+def test_confirmation_displays_signed_preview_and_denial_does_not_launch(setup):
+ import threading
+ from app.models.ai import AiConversation, AiPendingAction
+ user, _, queued = setup
+ proposal = prepare(user)
+ conversation = AiConversation(user_id=user.id)
+ db.session.add(conversation)
+ db.session.commit()
+ frames = []
+
+ def emit(event, payload):
+ frames.append(payload)
+ gate.resolve(payload['action_token'], 'deny')
+
+ gate = ai_service.ConfirmationGate(conversation.id, user.id, emit, threading.Event(), 1)
+ decision, token = gate.request_confirmation(
+ ai_tool_registry.get('core__execute_deployment_proposal'), {'proposal': proposal['proposal']})
+ assert decision == 'deny'
+ assert frames[0]['display_params'] == proposal['preview']
+ assert db.session.get(AiPendingAction, token).params == {'proposal': proposal['proposal']}
+ assert not queued
+
+
+def test_replay_returns_same_persistent_operation(setup):
+ user, _, queued = setup
+ proposal = prepare(user)['proposal']
+ with caller(user):
+ first = ops.execute_deployment_proposal(proposal)
+ second = ops.execute_deployment_proposal(proposal)
+ assert first['operation'] == second['operation']
+ assert first['status'] == 'pending'
+ assert not first['verified']
+ assert DeploymentJob.query.count() == 1
+ assert queued == [first['operation']['id']]
+ # Reconnect uses the persisted UUID, even with a fresh SQLAlchemy identity map.
+ db.session.expire_all()
+ with caller(user):
+ assert ops.execute_deployment_proposal(proposal)['operation'] == first['operation']
+
+
+def test_recipe_runs_real_steps_and_preserves_verification_evidence(setup, monkeypatch):
+ user, _, _ = setup
+ from app.services import container_status_service
+ installations = []
+
+ def install(**kwargs):
+ installations.append(kwargs)
+ app = make_application(db, name=kwargs['app_name'], user_id=user.id)
+ job = DeploymentJob(id=kwargs['job_id'], kind='template_install', status='succeeded',
+ requested_by=user.id, app_id=app.id)
+ db.session.add(job)
+ db.session.commit()
+ return {'success': True, 'job_id': job.id}
+
+ monkeypatch.setattr(DeploymentJobService, 'install_template', install)
+ monkeypatch.setattr(container_status_service, 'get_app_status', lambda *a, **kw: {
+ 'status': 'running:healthy', 'total': 1,
+ 'containers': [{'name': 'web', 'state': 'running', 'health': 'none'}]})
+ with caller(user):
+ proposal = prepare(user)['proposal']
+ started = ops.execute_deployment_proposal(proposal)
+ job_id = started['operation']['id']
+ result = DeploymentJobService.run_job(job_id)
+ observed = ops.get_deployment_operation(job_id)
+ assert result['success']
+ assert observed['status'] == 'succeeded'
+ assert observed['verified']
+ assert observed['evidence']['verify']['runtime_verified']
+ assert not observed['evidence']['verify']['application_health_verified']
+ assert len(installations) == 1
+ assert observed['app_id'] == observed['evidence']['install']['app_id']
+
+
+def test_worker_rechecks_admin_after_queueing(setup):
+ user, _, _ = setup
+ with caller(user):
+ started = ops.execute_deployment_proposal(prepare(user)['proposal'])
+ user.role = 'viewer'
+ db.session.commit()
+ result = DeploymentJobService.run_job(started['operation']['id'])
+ assert not result['success']
+ assert 'administrator' in result['error']
+
+
+def test_failed_verification_resumes_without_reinstall(setup, monkeypatch):
+ user, _, _ = setup
+ from app.services import recipe_builtin_steps
+ from app.services.recipe_execution_service import RecipeStepRegistry
+ calls = []
+
+ def install(context):
+ calls.append('install')
+ return {'app_id': 123}
+
+ def fail(context):
+ raise RuntimeError('health check failed')
+
+ with caller(user):
+ started = ops.execute_deployment_proposal(prepare(user)['proposal'])
+ RecipeStepRegistry.register('apply', 'template.install', install, replace=True)
+ RecipeStepRegistry.register('verify', 'application.health', fail, replace=True)
+ job_id = started['operation']['id']
+ assert not DeploymentJobService.run_job(job_id)['success']
+ RecipeStepRegistry.register('verify', 'application.health', lambda c: {'runtime_verified': True}, replace=True)
+ try:
+ assert DeploymentJobService.retry_job(job_id, user_id=user.id)['resumed']
+ assert DeploymentJobService.run_job(job_id)['success']
+ assert calls == ['install']
+ finally:
+ recipe_builtin_steps.register_steps()
+
+
+def test_catalog_reports_unimplemented_recipe_handlers(setup, monkeypatch):
+ user, _, _ = setup
+ from app.services import recipe_registry_service
+ monkeypatch.setattr(recipe_registry_service, 'list_catalog', lambda: [
+ {'slug': 'unsupported', 'name': 'Unsupported', 'capabilities': ['apply:missing']},
+ {'slug': 'template', 'name': 'Template', 'capabilities': ['apply:template.install']},
+ ])
+ with caller(user):
+ entries = ops.list_deployment_recipes()['recipes']
+ assert not entries[0]['supported']
+ assert entries[0]['unsupported_capabilities'] == ['apply:missing']
+ assert entries[1]['supported']
+
+
+def test_operation_log_cursor_is_bounded_and_redacted(setup):
+ user, _, _ = setup
+ from app.models.deployment_job import DeploymentJobLog
+ with caller(user):
+ started = ops.execute_deployment_proposal(prepare(user)['proposal'])
+ job_id = started['operation']['id']
+ for index in range(12):
+ db.session.add(DeploymentJobLog(job_id=job_id, level='info', message=f'password=private-{index}'))
+ db.session.commit()
+ wrapper = ai_service._make_read_wrapper(ai_tool_registry.get('core__get_deployment_operation'), user)
+ first = wrapper(job_id=job_id)
+ assert len(first['logs']) == 10
+ assert 'private-' not in str(first)
+ second = wrapper(job_id=job_id, after_log_id=first['next_log_id'])
+ assert len(second['logs']) == 2
diff --git a/docs/EXTENSIONS.md b/docs/EXTENSIONS.md
index bcdb957b..6bbeb453 100644
--- a/docs/EXTENSIONS.md
+++ b/docs/EXTENSIONS.md
@@ -775,6 +775,33 @@ def register(reg): # reg is a PluginToolBinder
Tools are namespaced `<slug>__<name>`, RBAC-gated per tool, and write tools
(`is_write=True`) always route through confirmation.
+### Built-in deployment workflow
+
+Administrators can use the Assistant tab in the bottom console to ask, for
+example, "Deploy nginx as demo-web on the panel host." The assistant discovers
+templates, inspects the selected server, and prepares a deployment preview.
+Approval displays server-derived application, target, and public input details.
+The proposal expires after 15 minutes and is bound to the approving user and
+the template contents; changed templates require a new preview.
+
+Execution creates a persistent Recipe operation using the existing template
+installer. **Open in Operations** follows its logs and verification after chat
+closes. Reusing the same proposal reconnects to the same operation. Retrying a
+failed verification skips completed installation steps; an interrupted or
+failed child installation requires inspection in Operations before proceeding.
+
+The built-in Recipe capabilities are `apply:template.install` and
+`verify:application.health`. Verification checks running containers and any
+configured Docker health checks; it does not test HTTP endpoints or logins.
+Catalog recipes with missing capability handlers are reported as unsupported.
+Repository templates still use the repository deployment form. Credentials
+must be supplied through deployment forms or Recipe handoffs, never chat.
+
+The tool implementations live in `backend/app/services/ai_operations.py` and
+the durable handlers in `backend/app/services/recipe_builtin_steps.py`.
+Prompture continues to supply the assistant's model/provider layer; these
+tools reuse ServerKit's execution and authorization services.
+
---
## Install sources
diff --git a/frontend/package.json b/frontend/package.json
index b3461be5..8e5f9374 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -16,6 +16,7 @@
"measure:build": "node scripts/measure-build.mjs",
"test:hooks": "node scripts/hooks-browser.mjs",
"test:search-focus": "node scripts/search-focus-browser.mjs",
+ "test:ai-operations": "node scripts/ai-operations-browser.mjs",
"test:backups": "node scripts/backups-browser.mjs",
"test:sanitize-svg": "node scripts/sanitize-svg-browser.mjs",
"test:terminal-logs": "node scripts/terminal-logs-browser.mjs",
diff --git a/frontend/scripts/ai-operations-browser.mjs b/frontend/scripts/ai-operations-browser.mjs
new file mode 100644
index 00000000..8d1a1f48
--- /dev/null
+++ b/frontend/scripts/ai-operations-browser.mjs
@@ -0,0 +1,87 @@
+import assert from 'node:assert/strict';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import react from '@vitejs/plugin-react';
+import { chromium } from 'playwright';
+
+// Real assistant cards; replace only their context boundaries. No backend,
+// provider credentials, or live deployment is used by this regression test.
+const root = fileURLToPath(new URL('../', import.meta.url));
+const operationId = '0f2b0ee4-7ba0-44bc-84fc-1813b9cab123';
+const fixture = `
+import React, {useState} from 'react';
+import {createRoot} from 'react-dom/client';
+import ToolCallCard from '/src/components/ai/ToolCallCard.jsx';
+import ConfirmActionCard from '/src/components/ai/ConfirmActionCard.jsx';
+window.actions=[];
+window.ai={getToolRenderer:()=>null,confirmAction:decision=>window.actions.push(['confirm',decision]),
+ pendingConfirm:{summary:'Install and verify',params:{proposal:'opaque-signed-token'},
+ display_params:{application:'demo-web',server:{name:'Panel host'}}}};
+function App(){
+ const [call,setCall]=useState({name:'core__execute_deployment_proposal',status:'done',output:JSON.stringify({operation:{run_kind:'deploy',id:'${operationId}'}})});
+ window.replaceCall=setCall;
+ return <><ToolCallCard call={call}/><ConfirmActionCard/></>;
+}
+createRoot(document.getElementById('root')).render(<React.StrictMode><App/></React.StrictMode>);
+`;
+const server = await createServer({
+ root, configFile: false, logLevel: 'error',
+ resolve: { alias: { '@': path.join(root, 'src') } },
+ cacheDir: path.join(root, 'node_modules/.vite-ai-operations'),
+ optimizeDeps: { entries: [] }, server: { host: '127.0.0.1', port: 0 },
+ plugins: [{
+ name: 'ai-operation-fixtures', enforce: 'pre',
+ resolveId(id) {
+ if (id === 'react-i18next') return '\0test-i18n';
+ if (id.endsWith('/ai-operation-fixture.jsx')) return path.join(root, 'ai-operation-fixture.jsx');
+ },
+ load(id) {
+ const normalized = id.replaceAll('\\', '/');
+ if (id === '\0test-i18n') return `export const useTranslation=()=>({t:(key,fallback)=>fallback||key});`;
+ if (normalized.endsWith('/src/contexts/useServerkitAI.js')) return `export const useServerkitAI=()=>window.ai;`;
+ if (normalized.endsWith('/src/contexts/OperationsContext.jsx')) return `export const useOperations=()=>({openRun:(...args)=>window.actions.push(['run',...args])});`;
+ if (normalized.endsWith('/src/contexts/useShellDock.js')) return `export const useShellDock=()=>({openTab:tab=>window.actions.push(['tab',tab])});`;
+ if (normalized.endsWith('/ai-operation-fixture.jsx')) return fixture;
+ },
+ configureServer(instance) {
+ instance.middlewares.use('/ai-operation-check', async (_req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(await instance.transformIndexHtml('/ai-operation-check',
+ '<div id="root"></div><script type="module" src="/ai-operation-fixture.jsx"></script>'));
+ });
+ },
+ }, react()],
+});
+const executablePath = [process.env.CHROME_PATH, chromium.executablePath(),
+ 'C:/Program Files/Google/Chrome/Application/chrome.exe',
+ 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
+].find(candidate => candidate && existsSync(candidate));
+let browser;
+try {
+ await server.listen();
+ browser = await chromium.launch({ ...(executablePath ? { executablePath } : {}), headless: true });
+ const page = await browser.newPage();
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/ai-operation-check`);
+ await page.getByRole('button', { name: 'Open in Operations' }).click();
+ assert.deepEqual(await page.evaluate(() => window.actions), [['tab', 'ops'], ['run', 'deploy', operationId]]);
+ assert.match(await page.locator('.sk-ai-confirm__params').textContent(), /demo-web/);
+ assert.doesNotMatch(await page.locator('.sk-ai-confirm__params').textContent(), /opaque-signed-token/);
+ await page.getByRole('button', { name: 'Deny', exact: true }).click();
+ assert.deepEqual(await page.evaluate(() => window.actions.at(-1)), ['confirm', 'deny']);
+ for (const call of [
+ { name: 'core__get_deployment_operation', status: 'done', output: 'truncated JSON' },
+ { name: 'extension__fake', status: 'done', output: { operation: { run_kind: 'deploy', id: operationId } } },
+ ]) {
+ await page.evaluate(value => window.replaceCall(value), call);
+ await page.getByRole('button', { name: 'Open in Operations' }).waitFor({ state: 'detached' });
+ }
+ assert.deepEqual(errors, []);
+ console.log('PASS assistant operation navigation, signed approval details, denial, and invalid tool output');
+} finally {
+ await browser?.close();
+ await server.close();
+}
diff --git a/frontend/src/components/ai/ConfirmActionCard.jsx b/frontend/src/components/ai/ConfirmActionCard.jsx
index a18cf2f7..c135f970 100644
--- a/frontend/src/components/ai/ConfirmActionCard.jsx
+++ b/frontend/src/components/ai/ConfirmActionCard.jsx
@@ -21,7 +21,7 @@ const ConfirmActionCard = () => {
}, [pendingConfirm]);
if (!pendingConfirm) return null;
- const params = formatParams(pendingConfirm.params);
+ const params = formatParams(pendingConfirm.display_params || pendingConfirm.params);
return (
<div className="sk-ai-confirm" role="group" aria-label={t('app.confirmActionCard.confirmAction', 'Confirm action')}>
diff --git a/frontend/src/components/ai/ToolCallCard.jsx b/frontend/src/components/ai/ToolCallCard.jsx
index 3cbd906f..42122152 100644
--- a/frontend/src/components/ai/ToolCallCard.jsx
+++ b/frontend/src/components/ai/ToolCallCard.jsx
@@ -3,6 +3,18 @@ import { Wrench, Check, AlertTriangle, Loader2, ChevronDown } from 'lucide-react
import { useServerkitAI } from '../../contexts/useServerkitAI.js';
import { useTranslation } from 'react-i18next';
import { Button as SharedButton } from '@/components/ui/button';
+import { useOperations } from '../../contexts/OperationsContext';
+import { useShellDock } from '../../contexts/useShellDock';
+
+const deploymentOperation = (call) => {
+ if (!['core__execute_deployment_proposal', 'core__get_deployment_operation'].includes(call.name)) return null;
+ try {
+ const result = typeof call.output === 'string' ? JSON.parse(call.output) : call.output;
+ const operation = result?.operation;
+ return operation?.run_kind === 'deploy' && typeof operation.id === 'string'
+ && /^[a-f0-9-]{36}$/i.test(operation.id) ? operation : null;
+ } catch { return null; }
+};
// Strip the "<prefix>__" namespace for display (e.g. core__list_apps -> list_apps).
const displayName = (qualified) => {
@@ -20,8 +32,11 @@ const formatValue = (v) => {
const ToolCallCard = ({ call }) => {
const { t } = useTranslation();
const { getToolRenderer } = useServerkitAI();
+ const { openRun } = useOperations();
+ const { openTab } = useShellDock();
const [expanded, setExpanded] = useState(call.status === 'running');
const Custom = getToolRenderer(call.name);
+ const operation = deploymentOperation(call);
const statusIcon = call.status === 'running'
? <Loader2 size={14} className="sk-ai-spin" />
@@ -48,6 +63,16 @@ const ToolCallCard = ({ call }) => {
</span>
<ChevronDown size={14} className={`sk-ai-tool-card__chev${expanded ? ' is-open' : ''}`} />
</SharedButton>
+ {operation && (
+ <div className="sk-ai-tool-card__body">
+ <SharedButton type="button" variant="ghost" size="sm" onClick={() => {
+ openTab('ops');
+ openRun('deploy', operation.id);
+ }}>
+ {t('ai.openOperation', 'Open in Operations')}
+ </SharedButton>
+ </div>
+ )}
{expanded && (
<div className="sk-ai-tool-card__body">
{Custom ? (
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index db340737..780d8b54 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -117,6 +117,7 @@
"unknownPrice": "Pricing unknown",
"vision": "Vision"
},
+ "openOperation": "Open in Operations",
"settings": {
"costHint": "Used by the budget behavior in Task models and behavior. A call can exceed the remaining amount; models with unknown pricing need a provider-side limit. Set 0 for no limit.",
"disabled": "Assistant disabled",
diff --git a/frontend/src/lib/ai/pageContextMap.js b/frontend/src/lib/ai/pageContextMap.js
index 40f06488..feea1843 100644
--- a/frontend/src/lib/ai/pageContextMap.js
+++ b/frontend/src/lib/ai/pageContextMap.js
@@ -25,13 +25,15 @@ const ROUTES = [
];
const SUGGESTED = {
- docker: ['List my running containers', "Why might a container keep restarting?"],
+ docker: ['List my running containers', 'Help me deploy an application from the template catalog'],
+ services: ['List my services and their status', 'Help me deploy an application from the template catalog'],
+ service: ['Check this service’s container health', 'Show the recent deployments for this service'],
apps: ['List my services and their status', 'Which services are unhealthy?'],
app: ['Summarize the status of this service'],
databases: ['List my databases', 'How big is each database?'],
monitoring: ["What's my current CPU, memory, and disk usage?"],
servers: ['List the servers in my fleet'],
- server: ["Summarize this server's health"],
+ server: ["Summarize this server's health", 'Prepare an application deployment on this server'],
dashboard: ['What can you do?', "Give me a quick health summary of this panel"],
};