Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(scheduled): add agent-confirmed research tasks

AirHua-byte651907745c1d
diff --git a/README.md b/README.md
index 87007e898..ea57ed6f3 100644
--- a/README.md
+++ b/README.md
@@ -1175,7 +1175,11 @@ vibe-trading serve --port 8899
| `POST` | `/channels/pairing/command` | Run a sender-pairing command against the shared store |
| `POST` | `/scheduled-runs` | Create a scheduled research job (interval-ms or cron) |
| `GET` | `/scheduled-runs` | List scheduled jobs |
+| `GET` | `/scheduled-runs/status` | Executor state and configured delivery targets |
+| `GET` | `/scheduled-runs/{job_id}` | Read one scheduled job |
| `DELETE` | `/scheduled-runs/{job_id}` | Cancel a scheduled job |
+| `POST` | `/scheduled-runs/proposals/{proposal_id}/commit` | Confirm an agent-proposed create/cancel |
+| `POST` | `/scheduled-runs/proposals/{proposal_id}/discard` | Discard an agent proposal |
| `GET` | `/scheduled-runs/playbooks` | List the research templates |
| `GET` | `/scheduled-runs/playbooks/{slug}` | Show one template, with its variables |
| `POST` | `/scheduled-runs/playbooks/{slug}` | Schedule a job from a template |
@@ -1233,6 +1237,40 @@ curl -X DELETE http://localhost:8899/scheduled-runs/<job_id>
Each fire runs the `prompt` through a fresh agent session (optional backtest parameters go in `config`), and jobs persist under `~/.vibe-trading/` so they survive restarts. Without the flag, the `/scheduled-runs` endpoints still record jobs but nothing fires. Add `-H "Authorization: Bearer <key>"` to each call when `API_AUTH_KEY` is set.
+The agent sees exactly one scheduling tool, `scheduled_research`. Its read
+actions inspect status/jobs/playbooks; `propose_create` and `propose_cancel`
+only persist a short-lived confirmation proposal. They never mutate the job
+store. Web renders a deterministic confirmation card, CLI asks `y/N`, and IM
+conversations require an exact `确认` or `取消`; only that surface action calls
+the commit endpoint. Create drafts carry `title`, `source`, `schedule`,
+`end_at`, and `delivery`. Once `end_at` passes, the retained job becomes
+`expired` and is not dispatched again.
+
+Scheduled delivery is channel-agnostic. Configure reusable opaque target refs
+under `channels.deliveryTargets`; the agent tool and its confirmation surfaces
+expose the ref, label, and channel but never the provider's raw chat/user id.
+The existing direct REST/admin fields remain available for backward
+compatibility:
+
+```json
+{
+ "channels": {
+ "deliveryTargets": {
+ "research-team": {
+ "label": "Research Team",
+ "channel": "feishu",
+ "target": "<provider chat or user id>"
+ }
+ }
+ }
+}
+```
+
+Any configured channel adapter can be selected. Delivery status is `accepted`
+when an adapter succeeded without a provider receipt, and `sent` only when the
+adapter returned a provider message id (currently implemented end to end for
+Feishu). Failures remain retryable in the persisted outbox.
+
**Five ready-to-schedule templates** ship with the scheduler — `premarket-brief`, `earnings-season-tracker`, `portfolio-checkup`, `a-share-money-flow`, `institutional-holdings-diff`. Each states the data a run needs in plain language instead of naming tools, so a template keeps working as the tool surface grows, and each is required to name a missing input rather than fill it from memory. Reach them from the CLI, over REST, or with `/playbook` in the TUI:
```bash
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index c52803a39..7a99fc19a 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -960,6 +960,10 @@ def _format_tool_result_preview(tool: str, status: str, preview: str) -> str:
_PROPOSAL_TOOL_NAME = "propose_mandate_profiles"
_PROPOSAL_ID_RE = re.compile(r'"proposal_id"\s*:\s*"(mp_[0-9a-f]{32})"')
+_SCHEDULED_PROPOSAL_TOOL_NAME = "scheduled_research"
+_SCHEDULED_PROPOSAL_ID_RE = re.compile(
+ r'"proposal_id"\s*:\s*"(srp_[0-9a-f]{32})"'
+)
def _load_full_proposal(proposal_id: str) -> Optional[Dict[str, Any]]:
@@ -1018,6 +1022,21 @@ def _mandate_proposal_from_tool_result(data: Dict[str, Any]) -> Optional[Dict[st
return _load_full_proposal(match.group(1))
+def _scheduled_proposal_from_tool_result(data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """Recover the full scheduled-research proposal from a tool preview."""
+ if data.get("tool") != _SCHEDULED_PROPOSAL_TOOL_NAME or data.get("status") != "ok":
+ return None
+ match = _SCHEDULED_PROPOSAL_ID_RE.search(str(data.get("preview") or ""))
+ if not match:
+ return None
+ try:
+ from src.scheduled_research.proposals import load_proposal
+
+ return load_proposal(match.group(1))
+ except Exception: # noqa: BLE001 - relay must never break the turn
+ return None
+
+
def _ensure_session_id(title: str, *, session_id: Optional[str] = None) -> str:
"""Return a host-owned session id, registering the session record if new.
@@ -1116,6 +1135,8 @@ def _run_agent(
# the tool_result still flows on to the dashboard / no-rich printers.
if event_type == "tool_result" and proposal_sink is not None:
proposal = _mandate_proposal_from_tool_result(data)
+ if proposal is None:
+ proposal = _scheduled_proposal_from_tool_result(data)
if proposal is not None:
try:
proposal_sink(proposal)
diff --git a/agent/cli/main.py b/agent/cli/main.py
index 0ae28cc4d..6d5bc0cb1 100644
--- a/agent/cli/main.py
+++ b/agent/cli/main.py
@@ -357,6 +357,7 @@ class InteractiveContext:
last_recap_history_len: int = 0
pending_prompt: Optional[str] = None
pending_proposal: Optional[Dict[str, Any]] = None
+ pending_scheduled_proposal: Optional[Dict[str, Any]] = None
# ---------------------------------------------------------------------------
@@ -759,8 +760,12 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:
# numbered choice block isn't clobbered by the live region, and arm the
# REPL to intercept the next reply (SPEC.md Consent §2).
if captured_proposal:
- ctx.pending_proposal = dict(captured_proposal)
- _render_mandate_proposal(console, ctx.pending_proposal)
+ if captured_proposal.get("type") == "scheduled_research.proposal":
+ ctx.pending_scheduled_proposal = dict(captured_proposal)
+ _render_scheduled_proposal(console, ctx.pending_scheduled_proposal)
+ else:
+ ctx.pending_proposal = dict(captured_proposal)
+ _render_mandate_proposal(console, ctx.pending_proposal)
ctx.history.append({"role": "user", "content": user_input})
answer = (result.get("content") or "").strip()
@@ -1020,6 +1025,7 @@ def _render_mandate_proposal(console: Any, proposal: Dict[str, Any]) -> None:
)
console.print()
+
for profile in profiles:
ordinal = profile.get("ordinal", "?")
label = profile.get("label", "")
@@ -1057,6 +1063,69 @@ def _render_mandate_proposal(console: Any, proposal: Dict[str, Any]) -> None:
console.print()
+def _render_scheduled_proposal(console: Any, proposal: Dict[str, Any]) -> None:
+ """Render the deterministic y/N confirmation block for a scheduled job."""
+ job = proposal.get("job") or {}
+ schedule = job.get("schedule") or {}
+ delivery = job.get("delivery") or {}
+ operation = proposal.get("operation")
+ verb = "创建" if operation == "create" else "取消"
+ channel_suffix = f" ({delivery.get('channel')})" if delivery.get("channel") else ""
+ console.print()
+ console.print(f"[bold orange1]定时研究确认 · {verb}[/bold orange1]")
+ console.print(f" 任务: {job.get('title') or job.get('id') or '?'}")
+ if operation == "create":
+ console.print(
+ f" 节奏: {schedule.get('expression')} · "
+ f"{schedule.get('timezone') or 'UTC'} · 截止 {schedule.get('end_at') or '无'}"
+ )
+ console.print(
+ f" 投递: {delivery.get('target_label') or '仅应用内'}{channel_suffix}"
+ )
+ console.print("[bold]确认执行? [y/N][/bold]")
+
+
+def _handle_scheduled_proposal_reply(text: str, ctx: InteractiveContext) -> bool:
+ """Commit/discard an outstanding scheduled proposal before the model."""
+ token = text.strip().lower()
+ if token not in {"y", "yes", "确认", "n", "no", "取消", "放弃"}:
+ return False
+ proposal = ctx.pending_scheduled_proposal or {}
+ proposal_id = str(proposal.get("proposal_id") or "")
+ console = get_console()
+ try:
+ import httpx
+
+ from src.config.accessor import get_env_config, reset_env_config
+
+ reset_env_config()
+ api_config = get_env_config().api
+ base = api_config.vibe_trading_api_url.rstrip("/")
+ key = api_config.api_auth_key.strip()
+ headers = {"Authorization": f"Bearer {key}"} if key else {}
+ endpoint = "commit" if token in {"y", "yes", "确认"} else "discard"
+ response = httpx.post(
+ f"{base}/scheduled-runs/proposals/{proposal_id}/{endpoint}",
+ headers=headers,
+ timeout=15.0,
+ )
+ response.raise_for_status()
+ result = response.json()
+ if token in {"y", "yes", "确认"}:
+ action = "创建" if proposal.get("operation") == "create" else "取消"
+ console.print(
+ f"[green]定时研究任务已{action}:[/green] "
+ f"{result.get('committed_job_id') or '?'}"
+ )
+ else:
+ console.print("[dim]已放弃这次定时研究变更。[/dim]")
+ except Exception as exc: # noqa: BLE001 - keep proposal open for retry
+ console.print(f"[red]定时研究确认失败:[/red] {exc}")
+ return True
+ ctx.pending_scheduled_proposal = None
+ return True
+
+
def _commit_mandate(proposal: Dict[str, Any], selected_ordinal: int) -> Dict[str, Any]:
"""Commit a mandate selection via the surface commit endpoint.
@@ -1267,6 +1336,13 @@ def _interactive_loop(max_iter: int, resume_session_id: Optional[str] = None) ->
ctx.pending_proposal = None
continue
+ # Scheduled research confirmation is a surface commit. Exact y/N
+ # replies are intercepted before the model; any other text remains a
+ # normal conversational adjustment request.
+ if ctx.pending_scheduled_proposal is not None and not text.startswith("/"):
+ if _handle_scheduled_proposal_reply(text, ctx):
+ continue
+
# Mandate pick — when a proposal is outstanding, a bare numeric reply
# is a COMMIT handled here (the model never sees it). An adjust reply
# falls through to the agent for a fresh proposal (SPEC.md Consent §2).
diff --git a/agent/src/api/scheduled_routes.py b/agent/src/api/scheduled_routes.py
index 9e285c2de..2806c25d4 100644
--- a/agent/src/api/scheduled_routes.py
+++ b/agent/src/api/scheduled_routes.py
@@ -10,7 +10,7 @@ import re
import sys as _sys
import time
import uuid
-from typing import Any, Awaitable, Callable, Dict, List, Optional
+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional
from fastapi import Depends, FastAPI, HTTPException, Query, status
from pydantic import BaseModel, Field
@@ -18,6 +18,9 @@ from starlette.responses import Response
from src.config.accessor import get_env_config
+if TYPE_CHECKING:
+ from src.scheduled_research.models import ScheduledResearchJob
+
logger = logging.getLogger(__name__)
@@ -112,7 +115,7 @@ def _read_scheduled_briefing(session_id: str) -> Optional[tuple[str, str]]:
return None
-async def _send_scheduled_briefing(channel: str, target: Optional[str], text: str) -> None:
+async def _send_scheduled_briefing(channel: str, target: Optional[str], text: str):
"""Deliver one briefing through the configured IM channel.
Args:
@@ -136,7 +139,7 @@ async def _send_scheduled_briefing(channel: str, target: Optional[str], text: st
raise RuntimeError(f"channel {channel!r} is not configured")
if not target:
raise RuntimeError(f"channel {channel!r} has no delivery target configured")
- await adapter.send(
+ return await adapter.send_with_receipt(
OutboundMessage(channel=channel, chat_id=target, content=text)
)
@@ -190,6 +193,7 @@ class CreateScheduledRunRequest(BaseModel):
prompt: str = Field(
..., min_length=1, description="Research prompt or backtest description"
)
+ title: Optional[str] = Field(None, description="Human-readable monitor title")
schedule: str = Field(
..., min_length=1, description="Interval-ms or 5-field cron expression"
)
@@ -219,6 +223,12 @@ class CreateScheduledRunRequest(BaseModel):
None,
description="Address within that channel (chat / group / user id).",
)
+ delivery_target_ref: Optional[str] = Field(
+ None, description="Opaque operator-configured target ref; preferred over raw target ids"
+ )
+ end_at: Optional[int] = Field(
+ None, description="Epoch-ms boundary after which no further run is dispatched"
+ )
class PlaybookResponse(BaseModel):
@@ -278,6 +288,9 @@ class CreateRunFromPlaybookRequest(BaseModel):
next_run_at: Optional[int] = Field(
None, description="Explicit first-fire epoch-ms, bypassing the default rule"
)
+ title: Optional[str] = None
+ end_at: Optional[int] = None
+ delivery_target_ref: Optional[str] = None
class ScheduledRunResponse(BaseModel):
@@ -285,6 +298,10 @@ class ScheduledRunResponse(BaseModel):
id: str
prompt: str
+ title: str = ""
+ source_type: str = "prompt"
+ playbook_slug: Optional[str] = None
+ end_at: Optional[int] = None
schedule: str
next_run_at: int
status: str
@@ -297,9 +314,13 @@ class ScheduledRunResponse(BaseModel):
timezone: Optional[str] = None
delivery_channel: Optional[str] = None
delivery_target: Optional[str] = None
+ delivery_target_ref: Optional[str] = None
+ delivery_target_label: Optional[str] = None
delivery_status: str = "none"
delivery_error: Optional[str] = None
delivery_updated_at: Optional[int] = None
+ delivery_attempts: int = 0
+ delivery_provider_message_id: Optional[str] = None
last_verdict: Optional[Dict[str, Any]] = None
@@ -325,6 +346,8 @@ def _job_to_response(job: ScheduledResearchJob) -> "ScheduledRunResponse":
delivery_status=delivery.get("status", "none"),
delivery_error=delivery.get("error"),
delivery_updated_at=delivery.get("updated_at"),
+ delivery_attempts=delivery.get("attempts", 0),
+ delivery_provider_message_id=delivery.get("provider_message_id"),
)
@@ -426,8 +449,31 @@ def register_scheduled_routes(
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
+ if request.end_at is not None:
+ if request.end_at <= now_ms:
+ raise HTTPException(status_code=422, detail="end_at must be in the future")
+ if next_run_at > request.end_at:
+ raise HTTPException(
+ status_code=422, detail="the first scheduled run occurs after end_at"
+ )
+
+ delivery_channel = request.delivery_channel
+ delivery_target = request.delivery_target
+ delivery_target_label = None
+ if request.delivery_target_ref:
+ from src.channels.targets import resolve_delivery_target
+
+ try:
+ resolved_target = resolve_delivery_target(request.delivery_target_ref)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ delivery_channel = resolved_target.channel
+ delivery_target = resolved_target.target
+ delivery_target_label = resolved_target.label
+
job = ScheduledResearchJob(
id=request.id or str(uuid.uuid4()),
+ title=request.title or "",
prompt=request.prompt,
schedule=request.schedule,
next_run_at=next_run_at,
@@ -435,8 +481,11 @@ def register_scheduled_routes(
created_at=now_ms,
config=request.config,
timezone=request.timezone,
- delivery_channel=request.delivery_channel,
- delivery_target=request.delivery_target,
+ end_at=request.end_at,
+ delivery_channel=delivery_channel,
+ delivery_target=delivery_target,
+ delivery_target_ref=request.delivery_target_ref,
+ delivery_target_label=delivery_target_label,
)
_get_scheduled_research_store().upsert(job)
return _job_to_response(job)
@@ -456,6 +505,44 @@ def register_scheduled_routes(
)
return [_job_to_response(j) for j in jobs]
+ @app.get(
+ "/scheduled-runs/status",
+ dependencies=[Depends(require_auth)],
+ )
+ async def get_scheduled_research_status() -> Dict[str, Any]:
+ from src.channels.targets import list_delivery_targets
+ from src.scheduled_research.service import scheduler_status
+
+ payload = scheduler_status()
+ payload["delivery_targets"] = [
+ target.public_dict() for target in list_delivery_targets()
+ ]
+ return payload
+
+ @app.post(
+ "/scheduled-runs/proposals/{proposal_id}/commit",
+ dependencies=[Depends(require_auth)],
+ )
+ async def commit_scheduled_research_proposal(proposal_id: str) -> Dict[str, Any]:
+ from src.scheduled_research.proposals import ProposalError, commit_proposal
+
+ try:
+ return commit_proposal(proposal_id)
+ except ProposalError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+
+ @app.post(
+ "/scheduled-runs/proposals/{proposal_id}/discard",
+ dependencies=[Depends(require_auth)],
+ )
+ async def discard_scheduled_research_proposal(proposal_id: str) -> Dict[str, Any]:
+ from src.scheduled_research.proposals import ProposalError, discard_proposal
+
+ try:
+ return discard_proposal(proposal_id)
+ except ProposalError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
@app.delete(
"/scheduled-runs/{job_id}",
status_code=status.HTTP_204_NO_CONTENT,
@@ -584,5 +671,42 @@ def register_scheduled_routes(
# schedule / timezone / cron-window failures, all ValueError.
raise HTTPException(status_code=422, detail=str(exc)) from exc
+ now_ms = int(time.time() * 1000)
+ if request.end_at is not None:
+ if request.end_at <= now_ms or job.next_run_at > request.end_at:
+ raise HTTPException(
+ status_code=422,
+ detail="end_at must be in the future and after the first run",
+ )
+ job.end_at = request.end_at
+ job.title = request.title or playbook.name
+ job.source_type = "playbook"
+ job.playbook_slug = playbook.slug
+ if request.delivery_target_ref:
+ from src.channels.targets import resolve_delivery_target
+
+ try:
+ target = resolve_delivery_target(request.delivery_target_ref)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ job.delivery_channel = target.channel
+ job.delivery_target = target.target
+ job.delivery_target_ref = target.ref
+ job.delivery_target_label = target.label
+
_get_scheduled_research_store().upsert(job)
return _job_to_response(job)
+
+ # Registered after the static /playbooks routes so "playbooks" is never
+ # consumed as a dynamic job id by Starlette's first-match routing.
+ @app.get(
+ "/scheduled-runs/{job_id}",
+ response_model=ScheduledRunResponse,
+ dependencies=[Depends(require_auth)],
+ )
+ async def get_scheduled_run(job_id: str) -> ScheduledRunResponse:
+ _host_validate_path_param(job_id, "job_id")
+ job = _get_scheduled_research_store().get(job_id)
+ if job is None:
+ raise HTTPException(status_code=404, detail=f"scheduled run {job_id} not found")
+ return _job_to_response(job)
diff --git a/agent/src/api/sessions_routes.py b/agent/src/api/sessions_routes.py
index b3f5f47d6..d9f0c22e1 100644
--- a/agent/src/api/sessions_routes.py
+++ b/agent/src/api/sessions_routes.py
@@ -188,6 +188,10 @@ def _get_goal_store():
_PROPOSAL_TOOL_NAME = "propose_mandate_profiles"
_PROPOSAL_ID_RE = re.compile(r'"proposal_id"\s*:\s*"(mp_[0-9a-f]{32})"')
+_SCHEDULED_PROPOSAL_TOOL_NAME = "scheduled_research"
+_SCHEDULED_PROPOSAL_ID_RE = re.compile(
+ r'"proposal_id"\s*:\s*"(srp_[0-9a-f]{32})"'
+)
def _load_full_proposal(proposal_id: str) -> Optional[Dict[str, Any]]:
@@ -231,6 +235,32 @@ def _mandate_proposal_frame_from_tool_result(event: Any) -> Optional[str]:
return frame.to_sse()
+def _scheduled_proposal_frame_from_tool_result(event: Any) -> Optional[str]:
+ """Build a deterministic scheduled-research confirmation SSE frame."""
+ data = getattr(event, "data", None)
+ if getattr(event, "event_type", None) != "tool_result" or not isinstance(data, dict):
+ return None
+ if data.get("tool") != _SCHEDULED_PROPOSAL_TOOL_NAME or data.get("status") != "ok":
+ return None
+ match = _SCHEDULED_PROPOSAL_ID_RE.search(str(data.get("preview") or ""))
+ if not match:
+ return None
+ try:
+ from src.scheduled_research.proposals import load_proposal
+
+ proposal = load_proposal(match.group(1))
+ except Exception: # pragma: no cover - relay must never break the stream
+ logger.debug("scheduled proposal reload failed", exc_info=True)
+ return None
+ from src.session.events import SSEEvent
+
+ return SSEEvent(
+ event_type="scheduled_research.proposal",
+ data=proposal,
+ session_id=getattr(event, "session_id", "") or "",
+ ).to_sse()
+
+
_LIVE_ACTION_ID_RE = re.compile(r'"audit_id"\s*:\s*"(la_[0-9a-zA-Z]+)"')
@@ -790,6 +820,9 @@ def register_sessions_routes(app: FastAPI) -> None:
relayed = _mandate_proposal_frame_from_tool_result(event)
if relayed is not None:
yield relayed
+ scheduled_relay = _scheduled_proposal_frame_from_tool_result(event)
+ if scheduled_relay is not None:
+ yield scheduled_relay
live_action = _live_action_frame_from_tool_result(event)
if live_action is not None:
yield live_action
diff --git a/agent/src/channels/base.py b/agent/src/channels/base.py
index d919d8fe8..2cb6b4464 100644
--- a/agent/src/channels/base.py
+++ b/agent/src/channels/base.py
@@ -4,10 +4,9 @@ from __future__ import annotations
import logging
from abc import ABC, abstractmethod
-from pathlib import Path
from typing import Any
-from src.channels.bus.events import InboundMessage, OutboundMessage
+from src.channels.bus.events import DeliveryReceipt, InboundMessage, OutboundMessage
from src.channels.bus.queue import MessageBus
from src.channels.pairing import (
PAIRING_CODE_META_KEY,
@@ -80,6 +79,18 @@ class BaseChannel(ABC):
can apply any retry policy in one place.
"""
+ async def send_with_receipt(self, msg: OutboundMessage) -> DeliveryReceipt:
+ """Send and return the strongest generic acknowledgement available.
+
+ Existing adapters remain compatible through ``accepted``. Adapters
+ that expose provider message ids should override this method and return
+ ``sent`` only after receiving that id.
+ """
+ import time
+
+ await self.send(msg)
+ return DeliveryReceipt(status="accepted", sent_at=int(time.time() * 1000))
+
# --- Streaming hooks (override in subclasses) ---
async def send_delta(
diff --git a/agent/src/channels/bus/events.py b/agent/src/channels/bus/events.py
index d1492446a..b9d55d6f3 100644
--- a/agent/src/channels/bus/events.py
+++ b/agent/src/channels/bus/events.py
@@ -2,7 +2,7 @@
from dataclasses import dataclass, field
from datetime import datetime, timezone
-from typing import Any
+from typing import Any, Literal
# Optional OutboundMessage.metadata key for structured, channel-agnostic UI
@@ -52,3 +52,18 @@ class OutboundMessage:
media: list[str] = field(default_factory=list)
metadata: dict[str, Any] = field(default_factory=dict)
buttons: list[list[str]] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class DeliveryReceipt:
+ """Provider acknowledgement for an outbound channel message.
+
+ ``accepted`` means the adapter returned successfully but its provider did
+ not expose a durable message id. ``sent`` is reserved for an explicit
+ provider receipt so scheduled delivery never reports more certainty than
+ the adapter can prove.
+ """
+
+ status: Literal["accepted", "sent"]
+ provider_message_id: str | None = None
+ sent_at: int | None = None
diff --git a/agent/src/channels/feishu.py b/agent/src/channels/feishu.py
index 295f2ee92..1a09470d9 100644
--- a/agent/src/channels/feishu.py
+++ b/agent/src/channels/feishu.py
@@ -21,7 +21,7 @@ from rich.markup import escape
from rich.panel import Panel
from rich.text import Text
-from src.channels.bus.events import OutboundMessage
+from src.channels.bus.events import DeliveryReceipt, OutboundMessage
from src.channels.bus.queue import MessageBus
from src.channels.base import BaseChannel
from src.channels.utils import get_media_dir
@@ -1958,8 +1958,7 @@ class FeishuChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send a message through Feishu, including media (images/files) if present."""
if not self._client:
- self.logger.warning("client not initialized")
- return
+ raise RuntimeError("Feishu client is not initialized")
try:
receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"
@@ -2111,6 +2110,63 @@ class FeishuChannel(BaseChannel):
self.logger.exception("Error sending message")
raise
+ async def send_with_receipt(self, msg: OutboundMessage) -> DeliveryReceipt:
+ """Send a non-reply message and retain Feishu's provider message id.
+
+ Scheduled briefings use this path. Rich reply/media sends keep the
+ generic adapter contract because Feishu's reply and upload APIs do not
+ expose one uniform receipt shape.
+ """
+ if msg.media or msg.reply_to or msg.metadata:
+ return await super().send_with_receipt(msg)
+ if not self._client:
+ raise RuntimeError("Feishu client is not initialized")
+ content = (msg.content or "").strip()
+ if not content:
+ raise ValueError("Feishu message content must not be empty")
+
+ receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"
+ loop = asyncio.get_running_loop()
+ payloads: list[tuple[str, str]] = []
+ fmt = self._detect_msg_format(content)
+ if fmt == "text":
+ payloads.append(("text", json.dumps({"text": content}, ensure_ascii=False)))
+ elif fmt == "post":
+ payloads.append(("post", self._markdown_to_post(content)))
+ else:
+ elements = self._build_card_elements(content)
+ for chunk in self._split_elements_by_table_limit(elements):
+ payloads.append(
+ (
+ "interactive",
+ json.dumps(
+ {"config": {"wide_screen_mode": True}, "elements": chunk},
+ ensure_ascii=False,
+ ),
+ )
+ )
+
+ message_ids: list[str] = []
+ for message_type, payload in payloads:
+ message_id = await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ receive_id_type,
+ msg.chat_id,
+ message_type,
+ payload,
+ )
+ if not message_id:
+ raise RuntimeError(
+ f"Feishu did not acknowledge {message_type} message delivery"
+ )
+ message_ids.append(message_id)
+ return DeliveryReceipt(
+ status="sent",
+ provider_message_id=message_ids[-1],
+ sent_at=int(time.time() * 1000),
+ )
+
def _on_message_sync(self, data: Any) -> None:
"""
Sync handler for incoming messages (called from WebSocket thread).
diff --git a/agent/src/channels/runtime.py b/agent/src/channels/runtime.py
index fbd6061bf..2cda5195d 100644
--- a/agent/src/channels/runtime.py
+++ b/agent/src/channels/runtime.py
@@ -184,6 +184,8 @@ class ChannelRuntime:
return
session_id = self._session_for(msg)
+ if await self._handle_scheduled_confirmation(msg, session_id):
+ return
result = await self.session_service.send_message(
session_id,
msg.content,
@@ -191,11 +193,32 @@ class ChannelRuntime:
)
attempt_id = result.get("attempt_id") if isinstance(result, dict) else None
reply = await self._wait_for_reply(session_id, attempt_id)
+ reply_content = reply.content
+ try:
+ from src.scheduled_research.proposals import latest_pending_for_session
+
+ proposal = latest_pending_for_session(session_id)
+ except Exception: # noqa: BLE001 - confirmation UI must not hide the reply
+ proposal = None
+ if proposal is not None:
+ job = proposal.get("job") or {}
+ schedule = job.get("schedule") or {}
+ delivery = job.get("delivery") or {}
+ action = "创建" if proposal.get("operation") == "create" else "取消"
+ reply_content = (
+ f"{reply_content}\n\n"
+ f"【定时研究确认 · {action}】\n"
+ f"任务:{job.get('title') or job.get('id') or '?'}\n"
+ f"节奏:{schedule.get('expression') or '-'} · "
+ f"{schedule.get('timezone') or 'UTC'}\n"
+ f"投递:{delivery.get('target_label') or '仅应用内'}\n"
+ "请准确回复「确认」或「取消」。"
+ )
await self.bus.publish_outbound(
OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
- content=reply.content,
+ content=reply_content,
metadata={
"_channel_runtime": True,
"attempt_id": attempt_id,
@@ -244,6 +267,46 @@ class ChannelRuntime:
)
)
+ async def _handle_scheduled_confirmation(
+ self, msg: InboundMessage, session_id: str
+ ) -> bool:
+ """Commit/discard exact IM confirmation replies outside the model."""
+ token = msg.content.strip()
+ if token not in {"确认", "取消"}:
+ return False
+ try:
+ from src.scheduled_research.proposals import (
+ commit_proposal,
+ discard_proposal,
+ latest_pending_for_session,
+ )
+
+ proposal = latest_pending_for_session(session_id)
+ if proposal is None:
+ return False
+ if token == "确认":
+ result = commit_proposal(proposal["proposal_id"])
+ action = "创建" if proposal.get("operation") == "create" else "取消"
+ content = f"✅ 定时研究任务已{action}:{result.get('committed_job_id') or '?'}"
+ else:
+ discard_proposal(proposal["proposal_id"])
+ content = "已放弃这次定时研究变更。"
+ except Exception as exc: # noqa: BLE001 - keep proposal pending for retry
+ content = f"定时研究确认失败:{exc}"
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=content,
+ metadata={
+ "_channel_runtime": True,
+ "scheduled_research_confirmation": True,
+ "message_id": msg.metadata.get("message_id"),
+ },
+ )
+ )
+ return True
+
def _session_for(self, msg: InboundMessage) -> str:
key = msg.session_key
existing = self._session_map.get(key)
diff --git a/agent/src/channels/targets.py b/agent/src/channels/targets.py
new file mode 100644
index 000000000..61f531d35
--- /dev/null
+++ b/agent/src/channels/targets.py
@@ -0,0 +1,47 @@
+"""Opaque, channel-agnostic scheduled-delivery target registry."""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+from src.config.loader import load_agent_config
+
+_SAFE_REF = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
+
+
+@dataclass(frozen=True)
+class DeliveryTarget:
+ ref: str
+ label: str
+ channel: str
+ target: str
+
+ def public_dict(self) -> dict[str, str]:
+ return {"ref": self.ref, "label": self.label, "channel": self.channel}
+
+
+def list_delivery_targets() -> list[DeliveryTarget]:
+ """Load enabled operator targets without exposing raw provider ids."""
+ configured = load_agent_config().channels.delivery_targets
+ targets: list[DeliveryTarget] = []
+ for ref, item in configured.items():
+ if not _SAFE_REF.fullmatch(ref) or not item.enabled:
+ continue
+ targets.append(
+ DeliveryTarget(
+ ref=ref,
+ label=item.label,
+ channel=item.channel,
+ target=item.target,
+ )
+ )
+ return sorted(targets, key=lambda item: (item.channel, item.label, item.ref))
+
+
+def resolve_delivery_target(ref: str) -> DeliveryTarget:
+ """Resolve an opaque ref or raise a user-facing validation error."""
+ for target in list_delivery_targets():
+ if target.ref == ref:
+ return target
+ raise ValueError(f"unknown or disabled delivery target ref {ref!r}")
diff --git a/agent/src/config/schema.py b/agent/src/config/schema.py
index 5ca11a765..c5df50aba 100644
--- a/agent/src/config/schema.py
+++ b/agent/src/config/schema.py
@@ -426,6 +426,15 @@ class MCPServerConfigOverride(ConfigBase):
enabled_tools: list[str] | None = None
+class DeliveryTargetConfig(ConfigBase):
+ """Operator-owned reusable destination for scheduled delivery."""
+
+ label: str = Field(min_length=1, max_length=128)
+ channel: str = Field(min_length=1, max_length=64)
+ target: str = Field(min_length=1, max_length=512)
+ enabled: bool = True
+
+
class ChannelsConfig(ConfigBase):
"""Top-level IM channel config.
@@ -447,6 +456,7 @@ class ChannelsConfig(ConfigBase):
# authenticated CLI/REST admin plane. Per-channel operators (channel-scoped
# authority) live under each channel section's own ``operators`` list.
operators: list[str] = Field(default_factory=list)
+ delivery_targets: dict[str, DeliveryTargetConfig] = Field(default_factory=dict)
class AgentConfig(ConfigBase):
diff --git a/agent/src/scheduled_research/executor.py b/agent/src/scheduled_research/executor.py
index 87b7bcaf3..987fb7c3c 100644
--- a/agent/src/scheduled_research/executor.py
+++ b/agent/src/scheduled_research/executor.py
@@ -16,6 +16,7 @@ from typing import Awaitable, Callable, Optional
from zoneinfo import ZoneInfo
from src.config.accessor import get_env_config
+from src.channels.bus.events import DeliveryReceipt
from src.scheduled_research.models import (
CRON_BOUNDS,
DeliveryRecord,
@@ -53,7 +54,9 @@ DispatchCallback = Callable[[ScheduledResearchJob], Awaitable[Optional[str]]]
#: session_id -> (terminal status, briefing text), or None while in flight.
BriefingReader = Callable[[str], Optional[tuple[str, str]]]
#: (channel, target, text) -> delivered.
-ChannelSender = Callable[[str, Optional[str], str], Awaitable[None]]
+ChannelSender = Callable[
+ [str, Optional[str], str], Awaitable[DeliveryReceipt | None]
+]
_TRUE_VALUES = {"1", "true", "yes", "on"}
# Search by day, not by minute, so an impossible date (e.g. Feb 31) fails fast
@@ -94,7 +97,14 @@ def is_due(job: ScheduledResearchJob, now_ms: int) -> bool:
schedule shorter than that gap would otherwise re-dispatch onto the same
row and overwrite it, orphaning the briefing a sweep still owes.
"""
- if job.status in {JobStatus.CANCELLED, JobStatus.RUNNING, JobStatus.FAILED}:
+ if job.status in {
+ JobStatus.CANCELLED,
+ JobStatus.RUNNING,
+ JobStatus.FAILED,
+ JobStatus.EXPIRED,
+ }:
+ return False
+ if job.end_at is not None and now_ms > job.end_at:
return False
if job.delivery.status in {DeliveryStatus.PENDING, DeliveryStatus.SENDING}:
return False
@@ -313,6 +323,7 @@ class ScheduledResearchExecutor:
"""
self.recover_stale_running()
now = self._now_fn() if now_ms is None else now_ms
+ self._expire_elapsed_jobs(now)
jobs = sorted(
(job for job in self._store.load().values() if is_due(job, now)),
key=lambda job: job.next_run_at,
@@ -333,6 +344,26 @@ class ScheduledResearchExecutor:
# is picked up here on the next tick.
await self.sweep_deliveries()
+ def _expire_elapsed_jobs(self, now_ms: int) -> int:
+ """Persist jobs whose configured end boundary has elapsed."""
+ jobs = self._store.load()
+ changed = 0
+ for job in jobs.values():
+ if job.end_at is None or now_ms <= job.end_at:
+ continue
+ if job.status in {
+ JobStatus.CANCELLED,
+ JobStatus.FAILED,
+ JobStatus.EXPIRED,
+ JobStatus.RUNNING,
+ }:
+ continue
+ job.status = JobStatus.EXPIRED
+ changed += 1
+ if changed:
+ self._store.save(jobs)
+ return changed
+
def recover_stale_running(self) -> int:
"""Reset jobs left ``RUNNING`` by a previous executor process.
@@ -466,7 +497,11 @@ class ScheduledResearchExecutor:
job.next_run_at = scheduled_next_run
if dispatch_error is None:
- job.status = JobStatus.COMPLETED
+ job.status = (
+ JobStatus.EXPIRED
+ if job.end_at is not None and scheduled_next_run > job.end_at
+ else JobStatus.COMPLETED
+ )
job.failure_kind = None
job.last_error = None
else:
@@ -478,6 +513,8 @@ class ScheduledResearchExecutor:
job.status = JobStatus.PENDING
retry_delay = self._retry_delay_ms(job.consecutive_failures)
job.next_run_at = max(scheduled_next_run, now_ms + retry_delay)
+ if job.end_at is not None and job.next_run_at > job.end_at:
+ job.status = JobStatus.EXPIRED
logger.warning(
"scheduled research job %s will retry after failure %d/%d at %d",
job.id,
@@ -612,7 +649,9 @@ class ScheduledResearchExecutor:
self._store.upsert(current, validate=False)
try:
- await self._channel_sender(job.delivery_channel, job.delivery_target, text)
+ receipt = await self._channel_sender(
+ job.delivery_channel, job.delivery_target, text
+ )
except asyncio.CancelledError:
raise
except Exception as exc:
@@ -621,7 +660,18 @@ class ScheduledResearchExecutor:
changed += 1
continue
- current.delivery.status = DeliveryStatus.SENT
+ if receipt is None:
+ # Compatibility for pre-receipt injected senders used by
+ # embedders and older tests. Production adapters always return
+ # an explicit receipt through BaseChannel.send_with_receipt.
+ current.delivery.status = DeliveryStatus.SENT
+ current.delivery.provider_message_id = None
+ elif receipt.status == "sent":
+ current.delivery.status = DeliveryStatus.SENT
+ current.delivery.provider_message_id = receipt.provider_message_id
+ else:
+ current.delivery.status = DeliveryStatus.ACCEPTED
+ current.delivery.provider_message_id = receipt.provider_message_id
current.delivery.error = None
current.delivery.updated_at = self._now_fn()
# The verdict rides the same write as the terminal delivery state,
diff --git a/agent/src/scheduled_research/models.py b/agent/src/scheduled_research/models.py
index 2adf63f02..d1488f06d 100644
--- a/agent/src/scheduled_research/models.py
+++ b/agent/src/scheduled_research/models.py
@@ -189,6 +189,7 @@ class JobStatus(str, Enum):
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
+ EXPIRED = "expired"
class DeliveryStatus(str, Enum):
@@ -209,6 +210,7 @@ class DeliveryStatus(str, Enum):
#: expires. Without the claim, a concurrent sweep reads PENDING while the
#: first send is still in flight and delivers the same briefing twice.
SENDING = "sending"
+ ACCEPTED = "accepted"
SENT = "sent"
FAILED = "failed"
@@ -237,6 +239,7 @@ class DeliveryRecord:
error: Optional[str] = None
attempts: int = 0
updated_at: Optional[int] = None
+ provider_message_id: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
"""Serialize to a plain JSON-serializable dict."""
@@ -247,6 +250,7 @@ class DeliveryRecord:
"error": self.error,
"attempts": self.attempts,
"updated_at": self.updated_at,
+ "provider_message_id": self.provider_message_id,
}
@classmethod
@@ -273,7 +277,7 @@ class DeliveryRecord:
status = DeliveryStatus(raw_status)
except ValueError as exc:
raise ValueError(f"unknown delivery status {raw_status!r}") from exc
- for name in ("session_id", "key", "error"):
+ for name in ("session_id", "key", "error", "provider_message_id"):
value = data.get(name)
if value is not None and not isinstance(value, str):
raise TypeError(f"'delivery.{name}' must be a string or null")
@@ -290,6 +294,7 @@ class DeliveryRecord:
error=data.get("error"),
attempts=attempts,
updated_at=updated_at,
+ provider_message_id=data.get("provider_message_id"),
)
@@ -358,6 +363,10 @@ class ScheduledResearchJob:
id: str
prompt: str
schedule: str
+ title: str = ""
+ source_type: str = "prompt"
+ playbook_slug: Optional[str] = None
+ end_at: Optional[int] = None
next_run_at: int = field(default_factory=lambda: int(time.time() * 1000))
status: JobStatus = JobStatus.PENDING
created_at: int = field(default_factory=lambda: int(time.time() * 1000))
@@ -369,6 +378,8 @@ class ScheduledResearchJob:
timezone: Optional[str] = None
delivery_channel: Optional[str] = None
delivery_target: Optional[str] = None
+ delivery_target_ref: Optional[str] = None
+ delivery_target_label: Optional[str] = None
delivery: DeliveryRecord = field(default_factory=DeliveryRecord)
last_verdict: Optional[VerdictRecord] = None
@@ -383,6 +394,10 @@ class ScheduledResearchJob:
"id": self.id,
"prompt": self.prompt,
"schedule": self.schedule,
+ "title": self.title,
+ "source_type": self.source_type,
+ "playbook_slug": self.playbook_slug,
+ "end_at": self.end_at,
"next_run_at": self.next_run_at,
"status": self.status.value,
"created_at": self.created_at,
@@ -394,6 +409,8 @@ class ScheduledResearchJob:
"timezone": self.timezone,
"delivery_channel": self.delivery_channel,
"delivery_target": self.delivery_target,
+ "delivery_target_ref": self.delivery_target_ref,
+ "delivery_target_label": self.delivery_target_label,
"delivery": self.delivery.to_dict(),
"last_verdict": self.last_verdict.to_dict() if self.last_verdict else None,
}
@@ -453,13 +470,29 @@ class ScheduledResearchJob:
raw_tz,
)
status = JobStatus(data["status"])
+ title = data.get("title", "")
+ source_type = data.get("source_type", "prompt")
+ playbook_slug = data.get("playbook_slug")
+ end_at = data.get("end_at")
+ if not isinstance(title, str):
+ raise TypeError("'title' must be a string")
+ if source_type not in {"prompt", "playbook"}:
+ raise ValueError("'source_type' must be 'prompt' or 'playbook'")
+ if playbook_slug is not None and not isinstance(playbook_slug, str):
+ raise TypeError("'playbook_slug' must be a string or null")
+ if end_at is not None and (isinstance(end_at, bool) or not isinstance(end_at, int)):
+ raise TypeError("'end_at' must be an integer (epoch ms) or null")
raw_config = data.get("config")
config: Dict[str, Any] = raw_config if isinstance(raw_config, dict) else {}
delivery_channel = data.get("delivery_channel")
delivery_target = data.get("delivery_target")
+ delivery_target_ref = data.get("delivery_target_ref")
+ delivery_target_label = data.get("delivery_target_label")
for name, value in (
("delivery_channel", delivery_channel),
("delivery_target", delivery_target),
+ ("delivery_target_ref", delivery_target_ref),
+ ("delivery_target_label", delivery_target_label),
):
if value is not None and not isinstance(value, str):
raise TypeError(f"'{name}' must be a string or null")
@@ -467,6 +500,10 @@ class ScheduledResearchJob:
id=job_id,
prompt=prompt,
schedule=schedule,
+ title=title,
+ source_type=source_type,
+ playbook_slug=playbook_slug,
+ end_at=end_at,
next_run_at=next_run_at,
status=status,
created_at=created_at,
@@ -478,6 +515,8 @@ class ScheduledResearchJob:
timezone=tz,
delivery_channel=delivery_channel,
delivery_target=delivery_target,
+ delivery_target_ref=delivery_target_ref,
+ delivery_target_label=delivery_target_label,
delivery=DeliveryRecord.from_dict(data.get("delivery")),
last_verdict=_verdict_record_or_none(data.get("last_verdict"), job_id),
)
diff --git a/agent/src/scheduled_research/proposals.py b/agent/src/scheduled_research/proposals.py
new file mode 100644
index 000000000..5478ea1d5
--- /dev/null
+++ b/agent/src/scheduled_research/proposals.py
@@ -0,0 +1,197 @@
+"""Durable confirmation proposals for scheduled-research mutations."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import threading
+import time
+import uuid
+from contextlib import suppress
+from pathlib import Path
+from typing import Any, Mapping
+
+from src.config.paths import get_runtime_root
+from src.scheduled_research.service import (
+ build_job_from_draft,
+ default_store,
+ public_job,
+ scheduler_status,
+)
+
+_ID_RE = re.compile(r"^srp_[0-9a-f]{32}$")
+_TTL_MS = 15 * 60 * 1000
+_LOCK = threading.Lock()
+
+
+class ProposalError(ValueError):
+ pass
+
+
+def _path(proposal_id: str) -> Path:
+ if not _ID_RE.fullmatch(proposal_id):
+ raise ProposalError("invalid scheduled research proposal id")
+ return (
+ get_runtime_root() / "scheduled_research" / "proposals" / f"{proposal_id}.json"
+ )
+
+
+def _write(path: Path, payload: Mapping[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ try:
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ fd = -1
+ handle.write(
+ (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode()
+ )
+ handle.flush()
+ os.fsync(handle.fileno())
+ finally:
+ if fd >= 0:
+ os.close(fd)
+ os.replace(tmp, path)
+ except BaseException:
+ with suppress(OSError):
+ os.unlink(tmp)
+ raise
+ os.chmod(path, 0o600)
+
+
+def _read(proposal_id: str) -> dict[str, Any]:
+ path = _path(proposal_id)
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ raise ProposalError(f"proposal {proposal_id!r} is unknown") from exc
+ if not isinstance(payload, dict):
+ raise ProposalError("proposal record is malformed")
+ return payload
+
+
+def public_proposal(payload: Mapping[str, Any]) -> dict[str, Any]:
+ return {
+ "type": "scheduled_research.proposal",
+ "proposal_id": payload["proposal_id"],
+ "operation": payload["operation"],
+ "status": payload["status"],
+ "expires_at": payload["expires_at"],
+ "job": payload.get("job"),
+ "job_id": payload.get("job_id"),
+ "committed_job_id": payload.get("committed_job_id"),
+ }
+
+
+def propose_create(
+ draft: Mapping[str, Any], *, session_id: str | None = None
+) -> dict[str, Any]:
+ job = build_job_from_draft(draft, session_id=session_id)
+ now = int(time.time() * 1000)
+ payload = {
+ "proposal_id": f"srp_{uuid.uuid4().hex}",
+ "operation": "create",
+ "status": "pending",
+ "session_id": session_id,
+ "created_at": now,
+ "expires_at": now + _TTL_MS,
+ "job": public_job(job),
+ "internal_job": job.to_dict(),
+ }
+ _write(_path(payload["proposal_id"]), payload)
+ return public_proposal(payload)
+
+
+def propose_cancel(job_id: str, *, session_id: str | None = None) -> dict[str, Any]:
+ job = default_store().get(job_id)
+ if job is None:
+ raise ProposalError(f"scheduled research job {job_id!r} was not found")
+ now = int(time.time() * 1000)
+ payload = {
+ "proposal_id": f"srp_{uuid.uuid4().hex}",
+ "operation": "cancel",
+ "status": "pending",
+ "session_id": session_id,
+ "created_at": now,
+ "expires_at": now + _TTL_MS,
+ "job_id": job_id,
+ "job": public_job(job),
+ }
+ _write(_path(payload["proposal_id"]), payload)
+ return public_proposal(payload)
+
+
+def load_proposal(proposal_id: str) -> dict[str, Any]:
+ return public_proposal(_read(proposal_id))
+
+
+def latest_pending_for_session(session_id: str) -> dict[str, Any] | None:
+ """Return the newest pending proposal bound to one conversation."""
+ directory = get_runtime_root() / "scheduled_research" / "proposals"
+ if not directory.exists():
+ return None
+ newest: dict[str, Any] | None = None
+ for path in directory.glob("srp_*.json"):
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ if not isinstance(payload, dict):
+ continue
+ if (
+ payload.get("session_id") != session_id
+ or payload.get("status") != "pending"
+ ):
+ continue
+ if newest is None or int(payload.get("created_at") or 0) > int(
+ newest.get("created_at") or 0
+ ):
+ newest = payload
+ return public_proposal(newest) if newest is not None else None
+
+
+def commit_proposal(proposal_id: str) -> dict[str, Any]:
+ with _LOCK:
+ payload = _read(proposal_id)
+ if payload.get("status") == "committed":
+ return public_proposal(payload)
+ if payload.get("status") != "pending":
+ raise ProposalError(f"proposal is {payload.get('status')}")
+ if int(payload.get("expires_at") or 0) < int(time.time() * 1000):
+ payload["status"] = "expired"
+ _write(_path(proposal_id), payload)
+ raise ProposalError("proposal has expired")
+ runtime = scheduler_status()
+ if not runtime["executable"]:
+ raise ProposalError(
+ "scheduled research executor is not enabled and running"
+ )
+
+ store = default_store()
+ if payload["operation"] == "create":
+ from src.scheduled_research.models import ScheduledResearchJob
+
+ job = ScheduledResearchJob.from_dict(payload["internal_job"])
+ store.upsert(job)
+ payload["committed_job_id"] = job.id
+ elif payload["operation"] == "cancel":
+ if not store.delete(payload["job_id"]):
+ raise ProposalError("scheduled research job no longer exists")
+ payload["committed_job_id"] = payload["job_id"]
+ else:
+ raise ProposalError("unsupported proposal operation")
+ payload["status"] = "committed"
+ payload["committed_at"] = int(time.time() * 1000)
+ _write(_path(proposal_id), payload)
+ return public_proposal(payload)
+
+
+def discard_proposal(proposal_id: str) -> dict[str, Any]:
+ with _LOCK:
+ payload = _read(proposal_id)
+ if payload.get("status") == "pending":
+ payload["status"] = "discarded"
+ _write(_path(proposal_id), payload)
+ return public_proposal(payload)
diff --git a/agent/src/scheduled_research/service.py b/agent/src/scheduled_research/service.py
new file mode 100644
index 000000000..97d7c8ab0
--- /dev/null
+++ b/agent/src/scheduled_research/service.py
@@ -0,0 +1,212 @@
+"""Domain service shared by HTTP, tools, CLI and IM surfaces."""
+
+from __future__ import annotations
+
+import sys
+import time
+import uuid
+from datetime import datetime
+from typing import Any, Mapping
+
+from src.channels.targets import resolve_delivery_target
+from src.scheduled_research.executor import next_due, scheduler_enabled_from_env
+from src.scheduled_research.models import (
+ JobStatus,
+ ScheduledResearchJob,
+ is_interval_schedule,
+ validate_schedule,
+ validate_timezone,
+ validate_timezone_shape,
+)
+from src.scheduled_research.playbooks import get_playbook
+from src.scheduled_research.store import ScheduledResearchJobStore
+
+
+def public_job(job: ScheduledResearchJob) -> dict[str, Any]:
+ """Return the user-facing job shape without raw channel destination ids."""
+ state = job.status.value
+ if job.status in {JobStatus.PENDING, JobStatus.COMPLETED}:
+ state = "active"
+ return {
+ "id": job.id,
+ "title": job.title or job.id,
+ "state": state,
+ "source": {
+ "kind": job.source_type,
+ "playbook_slug": job.playbook_slug,
+ "prompt": job.prompt if job.source_type == "prompt" else None,
+ },
+ "schedule": {
+ "expression": job.schedule,
+ "timezone": job.timezone,
+ "next_run_at": None if job.status is JobStatus.EXPIRED else job.next_run_at,
+ "end_at": job.end_at,
+ },
+ "delivery": {
+ "channel": job.delivery_channel,
+ "target_ref": job.delivery_target_ref,
+ "target_label": job.delivery_target_label,
+ "status": job.delivery.status.value,
+ "attempts": job.delivery.attempts,
+ "provider_message_id": job.delivery.provider_message_id,
+ "error": job.delivery.error,
+ },
+ "last_run_at": job.last_run_at,
+ "last_error": job.last_error,
+ }
+
+
+def scheduler_status() -> dict[str, Any]:
+ """Return configuration and runtime state without starting the scheduler."""
+ enabled = scheduler_enabled_from_env()
+ running = False
+ host = sys.modules.get("api_server") or sys.modules.get("agent.api_server")
+ executor = getattr(host, "_scheduled_research_executor", None) if host else None
+ if executor is None:
+ try:
+ from src.api import scheduled_routes
+
+ executor = scheduled_routes._scheduled_research_executor
+ except Exception:
+ executor = None
+ if executor is not None:
+ running = bool(executor.is_running)
+ return {"enabled": enabled, "running": running, "executable": enabled and running}
+
+
+def _parse_end_at(value: Any) -> int | None:
+ if value in (None, ""):
+ return None
+ if isinstance(value, bool):
+ raise ValueError("end_at must be RFC3339 text or epoch milliseconds")
+ if isinstance(value, int):
+ return value
+ if not isinstance(value, str):
+ raise ValueError("end_at must be RFC3339 text or epoch milliseconds")
+ try:
+ parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
+ except ValueError as exc:
+ raise ValueError("end_at must be a valid RFC3339 timestamp") from exc
+ if parsed.tzinfo is None:
+ raise ValueError("end_at must include an explicit timezone offset")
+ return int(parsed.timestamp() * 1000)
+
+
+def _origin_target(session_id: str | None) -> tuple[str, str, str | None, str]:
+ if not session_id:
+ raise ValueError("origin delivery requires the originating session")
+ host = sys.modules.get("api_server") or sys.modules.get("agent.api_server")
+ service = (
+ host._get_session_service()
+ if host and hasattr(host, "_get_session_service")
+ else None
+ )
+ session = service.get_session(session_id) if service else None
+ config = getattr(session, "config", None) or {}
+ channel = config.get("channel")
+ target = config.get("channel_chat_id")
+ if not isinstance(channel, str) or not isinstance(target, str):
+ raise ValueError("the originating session is not an IM conversation")
+ return channel, target, None, "当前会话"
+
+
+def build_job_from_draft(
+ draft: Mapping[str, Any],
+ *,
+ session_id: str | None = None,
+ now_ms: int | None = None,
+) -> ScheduledResearchJob:
+ """Validate the public draft and build a persisted-model job."""
+ now = int(time.time() * 1000) if now_ms is None else now_ms
+ title = str(draft.get("title") or "").strip()
+ if not title:
+ raise ValueError("title is required")
+ source = draft.get("source")
+ schedule_spec = draft.get("schedule")
+ delivery_spec = draft.get("delivery") or {"mode": "in_app"}
+ if not isinstance(source, Mapping) or not isinstance(schedule_spec, Mapping):
+ raise ValueError("source and schedule must be objects")
+ if not isinstance(delivery_spec, Mapping):
+ raise ValueError("delivery must be an object")
+
+ source_type = str(source.get("kind") or "prompt")
+ playbook_slug = None
+ config: dict[str, Any] = {}
+ if source_type == "prompt":
+ prompt = str(source.get("prompt") or "").strip()
+ if not prompt:
+ raise ValueError("source.prompt is required")
+ elif source_type == "playbook":
+ playbook_slug = str(source.get("playbook_slug") or "").strip()
+ if not playbook_slug:
+ raise ValueError("source.playbook_slug is required")
+ playbook = get_playbook(playbook_slug)
+ variables = source.get("variables") or {}
+ if not isinstance(variables, Mapping):
+ raise ValueError("source.variables must be an object")
+ prompt = playbook.render(variables)
+ config["playbook"] = playbook_slug
+ else:
+ raise ValueError("source.kind must be 'prompt' or 'playbook'")
+
+ expression = str(schedule_spec.get("expression") or "").strip()
+ timezone = schedule_spec.get("timezone")
+ validate_schedule(expression)
+ if is_interval_schedule(expression):
+ validate_timezone_shape(timezone)
+ else:
+ validate_timezone(timezone)
+ next_run_at = now
+ if timezone is not None and not is_interval_schedule(expression):
+ next_run_at = next_due(expression, now, timezone)
+
+ end_at = _parse_end_at(draft.get("end_at"))
+ if end_at is not None and end_at <= now:
+ raise ValueError("end_at must be in the future")
+ if end_at is not None and next_run_at > end_at:
+ raise ValueError("the first scheduled run occurs after end_at")
+
+ mode = str(delivery_spec.get("mode") or "in_app")
+ delivery_channel = delivery_target = target_ref = target_label = None
+ if mode == "configured":
+ target_ref = str(delivery_spec.get("target_ref") or "").strip()
+ if not target_ref:
+ raise ValueError("delivery.target_ref is required for configured delivery")
+ target = resolve_delivery_target(target_ref)
+ delivery_channel, delivery_target = target.channel, target.target
+ target_label = target.label
+ elif mode == "origin":
+ delivery_channel, delivery_target, target_ref, target_label = _origin_target(
+ session_id
+ )
+ elif mode != "in_app":
+ raise ValueError("delivery.mode must be 'in_app', 'origin', or 'configured'")
+
+ return ScheduledResearchJob(
+ id=str(draft.get("id") or f"sr-{uuid.uuid4().hex[:12]}"),
+ title=title,
+ prompt=prompt,
+ source_type=source_type,
+ playbook_slug=playbook_slug,
+ schedule=expression,
+ timezone=timezone,
+ next_run_at=next_run_at,
+ end_at=end_at,
+ status=JobStatus.PENDING,
+ created_at=now,
+ config=config,
+ delivery_channel=delivery_channel,
+ delivery_target=delivery_target,
+ delivery_target_ref=target_ref,
+ delivery_target_label=target_label,
+ )
+
+
+def default_store() -> ScheduledResearchJobStore:
+ """Return the API singleton when available so every surface shares state."""
+ try:
+ from src.api.scheduled_routes import _get_scheduled_research_store
+
+ return _get_scheduled_research_store()
+ except Exception:
+ return ScheduledResearchJobStore()
diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.py
index 710aa63ac..eef58930b 100644
--- a/agent/src/tools/__init__.py
+++ b/agent/src/tools/__init__.py
@@ -132,6 +132,7 @@ def build_registry(
from src.tools.autopilot_tool import RunResearchAutopilotTool
from src.tools.remember_tool import RememberTool
from src.tools.swarm_tool import SwarmTool
+ from src.tools.scheduled_research_tool import ScheduledResearchTool
goal_tool_classes = {
StartResearchGoalTool,
@@ -141,7 +142,10 @@ def build_registry(
}
# Tools that need the host session id injected: they create or mutate the
# session's research goal, and the LLM never knows the session id.
- session_injected_classes = goal_tool_classes | {RunResearchAutopilotTool}
+ session_injected_classes = goal_tool_classes | {
+ RunResearchAutopilotTool,
+ ScheduledResearchTool,
+ }
classes = _discover_subclasses()
registry = ToolRegistry()
for module_name, reason in _DISCOVERY_FAILURES.items():
diff --git a/agent/src/tools/scheduled_research_tool.py b/agent/src/tools/scheduled_research_tool.py
new file mode 100644
index 000000000..dd3629e30
--- /dev/null
+++ b/agent/src/tools/scheduled_research_tool.py
@@ -0,0 +1,127 @@
+"""Single read-only agent tool for scheduled research and proposals."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from src.agent.tools import BaseTool
+from src.channels.targets import list_delivery_targets
+from src.scheduled_research.playbooks import list_playbooks
+from src.scheduled_research.proposals import propose_cancel, propose_create
+from src.scheduled_research.service import default_store, public_job, scheduler_status
+
+
+class ScheduledResearchTool(BaseTool):
+ """Inspect scheduled research or prepare a user-confirmable mutation."""
+
+ name = "scheduled_research"
+ description = (
+ "Inspect scheduled research and prepare create/cancel proposals. This is "
+ "the only scheduled-research tool and is READ-ONLY: propose_create and "
+ "propose_cancel never change jobs. A human must confirm the proposal in "
+ "the current surface before it is committed."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": [
+ "status",
+ "list_jobs",
+ "get_job",
+ "list_playbooks",
+ "propose_create",
+ "propose_cancel",
+ ],
+ },
+ "job_id": {"type": "string"},
+ "draft": {
+ "type": "object",
+ "description": "Create draft; required for propose_create.",
+ "properties": {
+ "title": {"type": "string"},
+ "source": {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "enum": ["prompt", "playbook"]},
+ "prompt": {"type": "string"},
+ "playbook_slug": {"type": "string"},
+ "variables": {"type": "object"},
+ },
+ "required": ["kind"],
+ },
+ "schedule": {
+ "type": "object",
+ "properties": {
+ "expression": {"type": "string"},
+ "timezone": {"type": ["string", "null"]},
+ },
+ "required": ["expression"],
+ },
+ "end_at": {
+ "type": ["string", "integer", "null"],
+ "description": "RFC3339 timestamp with offset, or epoch milliseconds.",
+ },
+ "delivery": {
+ "type": "object",
+ "properties": {
+ "mode": {
+ "type": "string",
+ "enum": ["in_app", "origin", "configured"],
+ },
+ "target_ref": {"type": "string"},
+ },
+ "required": ["mode"],
+ },
+ },
+ "required": ["title", "source", "schedule", "end_at", "delivery"],
+ },
+ },
+ "required": ["action"],
+ }
+ repeatable = True
+ is_readonly = True
+
+ def __init__(self, default_session_id: str | None = None, **_kwargs: Any) -> None:
+ self._default_session_id = default_session_id
+
+ def execute(self, **kwargs: Any) -> str:
+ action = str(kwargs.get("action") or "").strip()
+ session_id = (
+ str(kwargs.get("session_id") or self._default_session_id or "").strip()
+ or None
+ )
+ if action == "status":
+ payload = scheduler_status()
+ payload["delivery_targets"] = [
+ target.public_dict() for target in list_delivery_targets()
+ ]
+ elif action == "list_jobs":
+ payload = {
+ "jobs": [
+ public_job(job) for job in default_store().list_jobs(limit=200)
+ ]
+ }
+ elif action == "get_job":
+ job_id = str(kwargs.get("job_id") or "").strip()
+ job = default_store().get(job_id)
+ if job is None:
+ raise ValueError(f"scheduled research job {job_id!r} was not found")
+ payload = public_job(job)
+ elif action == "list_playbooks":
+ payload = {"playbooks": [item.to_dict() for item in list_playbooks()]}
+ elif action == "propose_create":
+ draft = kwargs.get("draft")
+ if not isinstance(draft, dict):
+ raise ValueError("draft is required for propose_create")
+ payload = propose_create(draft, session_id=session_id)
+ elif action == "propose_cancel":
+ job_id = str(kwargs.get("job_id") or "").strip()
+ if not job_id:
+ raise ValueError("job_id is required for propose_cancel")
+ payload = propose_cancel(job_id, session_id=session_id)
+ else:
+ raise ValueError(f"unsupported scheduled_research action {action!r}")
+ return json.dumps(payload, ensure_ascii=False)
diff --git a/agent/tests/test_scheduled_research_confirmation.py b/agent/tests/test_scheduled_research_confirmation.py
new file mode 100644
index 000000000..87f2785ec
--- /dev/null
+++ b/agent/tests/test_scheduled_research_confirmation.py
@@ -0,0 +1,176 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+from src.channels.bus.events import DeliveryReceipt
+from src.channels.targets import DeliveryTarget
+from src.scheduled_research.executor import ScheduledResearchExecutor
+from src.scheduled_research.models import (
+ DeliveryStatus,
+ JobStatus,
+ ScheduledResearchJob,
+)
+from src.scheduled_research.store import ScheduledResearchJobStore
+from src.scheduled_research.service import build_job_from_draft, public_job
+from src.tools.scheduled_research_tool import ScheduledResearchTool
+
+
+def _draft() -> dict:
+ return {
+ "title": "Morning scan",
+ "source": {"kind": "prompt", "prompt": "Summarize the market."},
+ "schedule": {"expression": "60000", "timezone": "Asia/Shanghai"},
+ "end_at": 2_000_000,
+ "delivery": {"mode": "in_app"},
+ }
+
+
+def test_proposal_does_not_create_until_surface_commit_and_commit_is_idempotent(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ from src.scheduled_research import proposals
+
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
+ store = ScheduledResearchJobStore(tmp_path / "jobs.json")
+ monkeypatch.setattr(proposals, "default_store", lambda: store)
+ monkeypatch.setattr(
+ proposals,
+ "scheduler_status",
+ lambda: {"enabled": True, "running": True, "executable": True},
+ )
+ monkeypatch.setattr("src.scheduled_research.service.time.time", lambda: 1_000)
+ monkeypatch.setattr("src.scheduled_research.proposals.time.time", lambda: 1_000)
+
+ result = json.loads(
+ ScheduledResearchTool().execute(action="propose_create", draft=_draft())
+ )
+ assert result["type"] == "scheduled_research.proposal"
+ assert result["status"] == "pending"
+ assert store.load() == {}
+
+ first = proposals.commit_proposal(result["proposal_id"])
+ second = proposals.commit_proposal(result["proposal_id"])
+ assert first == second
+ assert len(store.load()) == 1
+ job = next(iter(store.load().values()))
+ assert job.title == "Morning scan"
+ assert job.end_at == 2_000_000
+
+
+def test_elapsed_end_at_expires_without_dispatch(tmp_path: Path) -> None:
+ store = ScheduledResearchJobStore(tmp_path / "jobs.json")
+ store.upsert(
+ ScheduledResearchJob(
+ id="ended",
+ title="Ended",
+ prompt="never run",
+ schedule="60000",
+ next_run_at=1_000,
+ end_at=900,
+ )
+ )
+ dispatched: list[str] = []
+
+ async def dispatch(job: ScheduledResearchJob) -> str:
+ dispatched.append(job.id)
+ return "session"
+
+ executor = ScheduledResearchExecutor(store, dispatch, enabled=False)
+ asyncio.run(executor.tick(now_ms=1_001))
+ assert dispatched == []
+ assert store.get("ended").status is JobStatus.EXPIRED
+
+
+def test_configured_delivery_keeps_raw_provider_target_out_of_public_payload(
+ monkeypatch,
+) -> None:
+ from src.scheduled_research import service
+
+ target = DeliveryTarget(
+ ref="research-team",
+ label="Research Team",
+ channel="slack",
+ target="raw-provider-destination",
+ )
+ monkeypatch.setattr(service, "resolve_delivery_target", lambda _ref: target)
+ draft = _draft()
+ draft["delivery"] = {"mode": "configured", "target_ref": target.ref}
+
+ job = build_job_from_draft(draft, now_ms=1_000)
+ payload = public_job(job)
+
+ assert job.delivery_target == "raw-provider-destination"
+ assert payload["delivery"]["target_ref"] == "research-team"
+ assert payload["delivery"]["target_label"] == "Research Team"
+ assert "raw-provider-destination" not in json.dumps(payload)
+
+
+def test_provider_receipt_is_persisted_as_sent(tmp_path: Path) -> None:
+ store = ScheduledResearchJobStore(tmp_path / "jobs.json")
+ store.upsert(
+ ScheduledResearchJob(
+ id="receipt",
+ prompt="run",
+ schedule="60000",
+ next_run_at=1_000,
+ delivery_channel="feishu",
+ delivery_target="opaque-provider-target",
+ )
+ )
+
+ async def dispatch(_job: ScheduledResearchJob) -> str:
+ return "session-1"
+
+ async def sender(_channel: str, _target: str | None, _text: str) -> DeliveryReceipt:
+ return DeliveryReceipt(status="sent", provider_message_id="om_provider_receipt")
+
+ executor = ScheduledResearchExecutor(
+ store,
+ dispatch,
+ enabled=False,
+ now_fn=lambda: 1_000,
+ briefing_reader=lambda _session: ("completed", "briefing"),
+ channel_sender=sender,
+ )
+ asyncio.run(executor.tick(now_ms=1_000))
+ delivery = store.get("receipt").delivery
+ assert delivery.status is DeliveryStatus.SENT
+ assert delivery.provider_message_id == "om_provider_receipt"
+
+
+def test_generic_adapter_acknowledgement_is_persisted_as_accepted(
+ tmp_path: Path,
+) -> None:
+ store = ScheduledResearchJobStore(tmp_path / "jobs.json")
+ store.upsert(
+ ScheduledResearchJob(
+ id="accepted",
+ prompt="run",
+ schedule="60000",
+ next_run_at=1_000,
+ delivery_channel="slack",
+ delivery_target="opaque-provider-target",
+ )
+ )
+
+ async def dispatch(_job: ScheduledResearchJob) -> str:
+ return "session-2"
+
+ async def sender(_channel: str, _target: str | None, _text: str) -> DeliveryReceipt:
+ return DeliveryReceipt(status="accepted")
+
+ executor = ScheduledResearchExecutor(
+ store,
+ dispatch,
+ enabled=False,
+ now_fn=lambda: 1_000,
+ briefing_reader=lambda _session: ("completed", "briefing"),
+ channel_sender=sender,
+ )
+ asyncio.run(executor.tick(now_ms=1_000))
+ delivery = store.get("accepted").delivery
+ assert delivery.status is DeliveryStatus.ACCEPTED
+ assert delivery.provider_message_id is None
diff --git a/frontend/src/components/chat/ScheduledResearchProposalCard.tsx b/frontend/src/components/chat/ScheduledResearchProposalCard.tsx
new file mode 100644
index 000000000..ace3cdd07
--- /dev/null
+++ b/frontend/src/components/chat/ScheduledResearchProposalCard.tsx
@@ -0,0 +1,122 @@
+import { memo, useState } from "react";
+import { CalendarClock, Check, X } from "lucide-react";
+
+import i18n from "@/i18n";
+import { api, type ScheduledResearchProposal } from "@/lib/api";
+
+interface Props {
+ proposal: ScheduledResearchProposal;
+}
+
+function formatTime(value: number | null | undefined): string {
+ if (!value) return i18n.t("scheduled.proposalNoEnd");
+ return new Intl.DateTimeFormat(undefined, {
+ dateStyle: "medium",
+ timeStyle: "short",
+ }).format(new Date(value));
+}
+
+export const ScheduledResearchProposalCard = memo(function ScheduledResearchProposalCard({
+ proposal,
+}: Props) {
+ const [status, setStatus] = useState(proposal.status);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const job = proposal.job;
+ const isCreate = proposal.operation === "create";
+
+ async function decide(commit: boolean) {
+ setBusy(true);
+ setError(null);
+ try {
+ const result = commit
+ ? await api.commitScheduledResearchProposal(proposal.proposal_id)
+ : await api.discardScheduledResearchProposal(proposal.proposal_id);
+ setStatus(result.status);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ if (status !== "pending") {
+ return (
+ <div className="mx-auto flex max-w-2xl items-center gap-2 rounded-xl border border-border/60 bg-muted/35 px-4 py-3 text-sm">
+ <CalendarClock className="h-4 w-4 text-orange-500" />
+ <span className="font-medium">{job.title}</span>
+ <span className="text-muted-foreground">
+ {status === "committed"
+ ? i18n.t("scheduled.proposalConfirmed")
+ : status === "discarded"
+ ? i18n.t("scheduled.proposalDiscarded")
+ : i18n.t("scheduled.proposalExpired")}
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <section className="mx-auto max-w-2xl rounded-2xl border border-orange-500/25 bg-card p-5 shadow-sm">
+ <div className="flex items-start gap-3">
+ <div className="rounded-xl bg-orange-500/10 p-2 text-orange-500">
+ <CalendarClock className="h-5 w-5" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="text-xs font-semibold uppercase tracking-wide text-orange-500">
+ {i18n.t(
+ isCreate ? "scheduled.proposalCreateTitle" : "scheduled.proposalCancelTitle",
+ )}
+ </p>
+ <h3 className="mt-1 font-semibold text-foreground">{job.title}</h3>
+ </div>
+ </div>
+
+ {isCreate && (
+ <dl className="mt-4 grid gap-2 rounded-xl bg-muted/40 p-3 text-sm sm:grid-cols-2">
+ <div>
+ <dt className="text-muted-foreground">{i18n.t("scheduled.proposalCadence")}</dt>
+ <dd>{job.schedule.expression}</dd>
+ </div>
+ <div>
+ <dt className="text-muted-foreground">{i18n.t("scheduled.proposalTimezone")}</dt>
+ <dd>{job.schedule.timezone || "UTC"}</dd>
+ </div>
+ <div>
+ <dt className="text-muted-foreground">{i18n.t("scheduled.proposalEndAt")}</dt>
+ <dd>{formatTime(job.schedule.end_at)}</dd>
+ </div>
+ <div>
+ <dt className="text-muted-foreground">{i18n.t("scheduled.proposalDelivery")}</dt>
+ <dd>{job.delivery.target_label || i18n.t("scheduled.proposalInApp")}</dd>
+ </div>
+ </dl>
+ )}
+
+ {error && <p className="mt-3 text-sm text-destructive">{error}</p>}
+ <div className="mt-4 flex justify-end gap-2">
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => void decide(false)}
+ className="inline-flex items-center rounded-md border px-3 py-1.5 text-sm transition hover:bg-muted disabled:opacity-50"
+ >
+ <X className="mr-1 h-4 w-4" /> {i18n.t("scheduled.proposalDiscard")}
+ </button>
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => void decide(true)}
+ className="inline-flex items-center rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground transition hover:opacity-90 disabled:opacity-50"
+ >
+ <Check className="mr-1 h-4 w-4" />{" "}
+ {i18n.t(
+ isCreate
+ ? "scheduled.proposalConfirmCreate"
+ : "scheduled.proposalConfirmCancel",
+ )}
+ </button>
+ </div>
+ </section>
+ );
+});
diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts
index 721f05e36..6f52a25fa 100644
--- a/frontend/src/hooks/useSSE.ts
+++ b/frontend/src/hooks/useSSE.ts
@@ -91,7 +91,7 @@ export function useSSE(config?: SSEConfig) {
"attempt.cancelled",
"message.received", "session.created",
"goal.created", "goal.evidence", "goal.updated",
- "mandate.proposal", "mandate.committed", "live.halted", "live.resumed", "live.action",
+ "mandate.proposal", "mandate.committed", "scheduled_research.proposal", "live.halted", "live.resumed", "live.action",
"heartbeat", "done",
];
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index eff1d46ea..9a6a681ca 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -158,6 +158,23 @@
"statusCompleted": "مكتمل",
"statusFailed": "فشل",
"statusCancelled": "أُلغي",
+ "statusExpired": "منتهي الصلاحية",
+ "noFurtherRuns": "لا توجد عمليات تشغيل أخرى",
+ "endsAt": "ينتهي في {{when}}",
+ "proposalCreateTitle": "تأكيد البحث المجدول · إنشاء",
+ "proposalCancelTitle": "تأكيد البحث المجدول · إلغاء",
+ "proposalConfirmed": "تم التأكيد",
+ "proposalDiscarded": "تم التجاهل",
+ "proposalExpired": "منتهي الصلاحية",
+ "proposalCadence": "وتيرة التشغيل",
+ "proposalTimezone": "المنطقة الزمنية",
+ "proposalEndAt": "وقت الانتهاء",
+ "proposalNoEnd": "لا يوجد",
+ "proposalDelivery": "تسليم النتيجة",
+ "proposalInApp": "داخل التطبيق فقط",
+ "proposalDiscard": "تجاهل",
+ "proposalConfirmCreate": "تأكيد الإنشاء",
+ "proposalConfirmCancel": "تأكيد الإلغاء",
"nextRun": "التشغيل التالي: {{when}}",
"lastError": "آخر خطأ: {{error}}",
"delete": "حذف",
@@ -173,6 +190,7 @@
"delivery_none": "سيُرسل إلى {{channel}} بعد التشغيل القادم",
"delivery_pending": "الملخص بانتظار الإرسال إلى {{channel}}",
"delivery_sending": "جارٍ الإرسال إلى {{channel}}",
+ "delivery_accepted": "قَبِلَت {{channel}} الإرسال (من دون إيصال من المزوّد)",
"delivery_sent": "تم الإرسال إلى {{channel}}",
"delivery_failed": "تعذّر الإرسال إلى {{channel}}",
"verdictEmpty": "لا يوجد تقييم بعد",
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index eb506f16c..f8e790aff 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -163,6 +163,23 @@
"statusCompleted": "Abgeschlossen",
"statusFailed": "Fehlgeschlagen",
"statusCancelled": "Abgebrochen",
+ "statusExpired": "Abgelaufen",
+ "noFurtherRuns": "Keine weiteren Ausführungen",
+ "endsAt": "Endet {{when}}",
+ "proposalCreateTitle": "Bestätigung für geplante Recherche · Erstellen",
+ "proposalCancelTitle": "Bestätigung für geplante Recherche · Abbrechen",
+ "proposalConfirmed": "Bestätigt",
+ "proposalDiscarded": "Verworfen",
+ "proposalExpired": "Abgelaufen",
+ "proposalCadence": "Rhythmus",
+ "proposalTimezone": "Zeitzone",
+ "proposalEndAt": "Endzeit",
+ "proposalNoEnd": "Keine",
+ "proposalDelivery": "Ergebniszustellung",
+ "proposalInApp": "Nur in der App",
+ "proposalDiscard": "Verwerfen",
+ "proposalConfirmCreate": "Erstellung bestätigen",
+ "proposalConfirmCancel": "Abbruch bestätigen",
"nextRun": "Nächster Lauf: {{when}}",
"lastError": "Letzter Fehler: {{error}}",
"delete": "Löschen",
@@ -178,6 +195,7 @@
"delivery_none": "Wird nach dem nächsten Lauf an {{channel}} gesendet",
"delivery_pending": "Briefing wartet auf Versand an {{channel}}",
"delivery_sending": "Briefing wird an {{channel}} gesendet",
+ "delivery_accepted": "Briefing von {{channel}} angenommen (ohne Anbieterbestätigung)",
"delivery_sent": "Briefing an {{channel}} gesendet",
"delivery_failed": "Versand an {{channel}} fehlgeschlagen",
"verdictEmpty": "Noch kein Urteil",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index cf6e5d280..06705d863 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -163,6 +163,23 @@
"statusCompleted": "Completed",
"statusFailed": "Failed",
"statusCancelled": "Cancelled",
+ "statusExpired": "Expired",
+ "noFurtherRuns": "No further runs",
+ "endsAt": "Ends {{when}}",
+ "proposalCreateTitle": "Scheduled research confirmation · Create",
+ "proposalCancelTitle": "Scheduled research confirmation · Cancel",
+ "proposalConfirmed": "Confirmed",
+ "proposalDiscarded": "Discarded",
+ "proposalExpired": "Expired",
+ "proposalCadence": "Cadence",
+ "proposalTimezone": "Timezone",
+ "proposalEndAt": "End time",
+ "proposalNoEnd": "None",
+ "proposalDelivery": "Result delivery",
+ "proposalInApp": "In app only",
+ "proposalDiscard": "Discard",
+ "proposalConfirmCreate": "Confirm creation",
+ "proposalConfirmCancel": "Confirm cancellation",
"nextRun": "Next run: {{when}}",
"lastError": "Last error: {{error}}",
"delete": "Delete",
@@ -178,6 +195,7 @@
"delivery_none": "Delivering to {{channel}} after the next run",
"delivery_pending": "Briefing owed to {{channel}}",
"delivery_sending": "Sending the briefing to {{channel}}",
+ "delivery_accepted": "Briefing accepted by {{channel}} (no provider receipt)",
"delivery_sent": "Briefing delivered to {{channel}}",
"delivery_failed": "Could not deliver to {{channel}}",
"verdictEmpty": "No verdict yet",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 14b2c171c..61a12cc6a 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -163,6 +163,23 @@
"statusCompleted": "Completado",
"statusFailed": "Fallido",
"statusCancelled": "Cancelado",
+ "statusExpired": "Caducado",
+ "noFurtherRuns": "No habrá más ejecuciones",
+ "endsAt": "Finaliza {{when}}",
+ "proposalCreateTitle": "Confirmación de investigación programada · Crear",
+ "proposalCancelTitle": "Confirmación de investigación programada · Cancelar",
+ "proposalConfirmed": "Confirmado",
+ "proposalDiscarded": "Descartado",
+ "proposalExpired": "Caducado",
+ "proposalCadence": "Frecuencia",
+ "proposalTimezone": "Zona horaria",
+ "proposalEndAt": "Hora de finalización",
+ "proposalNoEnd": "Ninguna",
+ "proposalDelivery": "Entrega del resultado",
+ "proposalInApp": "Solo en la aplicación",
+ "proposalDiscard": "Descartar",
+ "proposalConfirmCreate": "Confirmar creación",
+ "proposalConfirmCancel": "Confirmar cancelación",
"nextRun": "Próxima ejecución: {{when}}",
"lastError": "Último error: {{error}}",
"delete": "Eliminar",
@@ -178,6 +195,7 @@
"delivery_none": "Se enviará a {{channel}} tras la próxima ejecución",
"delivery_pending": "Informe pendiente de envío a {{channel}}",
"delivery_sending": "Enviando el informe a {{channel}}",
+ "delivery_accepted": "Informe aceptado por {{channel}} (sin confirmación del proveedor)",
"delivery_sent": "Informe enviado a {{channel}}",
"delivery_failed": "No se pudo enviar a {{channel}}",
"verdictEmpty": "Sin veredicto aún",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 5f34e7ebd..3b3cf86e0 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -158,6 +158,23 @@
"statusCompleted": "完了",
"statusFailed": "失敗",
"statusCancelled": "キャンセル済み",
+ "statusExpired": "期限切れ",
+ "noFurtherRuns": "以後の実行はありません",
+ "endsAt": "終了: {{when}}",
+ "proposalCreateTitle": "定期リサーチの確認 · 作成",
+ "proposalCancelTitle": "定期リサーチの確認 · キャンセル",
+ "proposalConfirmed": "確認済み",
+ "proposalDiscarded": "破棄済み",
+ "proposalExpired": "期限切れ",
+ "proposalCadence": "実行間隔",
+ "proposalTimezone": "タイムゾーン",
+ "proposalEndAt": "終了時刻",
+ "proposalNoEnd": "なし",
+ "proposalDelivery": "結果の配信",
+ "proposalInApp": "アプリ内のみ",
+ "proposalDiscard": "破棄",
+ "proposalConfirmCreate": "作成を確認",
+ "proposalConfirmCancel": "キャンセルを確認",
"nextRun": "次回実行:{{when}}",
"lastError": "直近のエラー:{{error}}",
"delete": "削除",
@@ -173,6 +190,7 @@
"delivery_none": "次回の実行完了後に {{channel}} へ配信します",
"delivery_pending": "{{channel}} への配信待ちです",
"delivery_sending": "{{channel}} へ配信中です",
+ "delivery_accepted": "{{channel}} が配信を受け付けました(プロバイダー受領確認なし)",
"delivery_sent": "{{channel}} へ配信しました",
"delivery_failed": "{{channel}} へ配信できませんでした",
"verdictEmpty": "判定はまだありません",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 52066ee2a..172776101 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -158,6 +158,23 @@
"statusCompleted": "완료",
"statusFailed": "실패",
"statusCancelled": "취소됨",
+ "statusExpired": "만료됨",
+ "noFurtherRuns": "추가 실행 없음",
+ "endsAt": "종료: {{when}}",
+ "proposalCreateTitle": "예약 리서치 확인 · 생성",
+ "proposalCancelTitle": "예약 리서치 확인 · 취소",
+ "proposalConfirmed": "확인됨",
+ "proposalDiscarded": "폐기됨",
+ "proposalExpired": "만료됨",
+ "proposalCadence": "실행 주기",
+ "proposalTimezone": "시간대",
+ "proposalEndAt": "종료 시간",
+ "proposalNoEnd": "없음",
+ "proposalDelivery": "결과 전송",
+ "proposalInApp": "앱에만 보관",
+ "proposalDiscard": "폐기",
+ "proposalConfirmCreate": "생성 확인",
+ "proposalConfirmCancel": "취소 확인",
"nextRun": "다음 실행: {{when}}",
"lastError": "최근 오류: {{error}}",
"delete": "삭제",
@@ -173,6 +190,7 @@
"delivery_none": "다음 실행이 끝나면 {{channel}}(으)로 전달합니다",
"delivery_pending": "{{channel}}(으)로 전달 대기 중",
"delivery_sending": "{{channel}}(으)로 전달하는 중",
+ "delivery_accepted": "{{channel}}에서 전송을 접수했습니다(제공자 확인 없음)",
"delivery_sent": "{{channel}}(으)로 전달했습니다",
"delivery_failed": "{{channel}}(으)로 전달하지 못했습니다",
"verdictEmpty": "아직 판정 없음",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index d0b939bec..1ec3d687b 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -158,6 +158,23 @@
"statusCompleted": "已完成",
"statusFailed": "失败",
"statusCancelled": "已取消",
+ "statusExpired": "已到期",
+ "noFurtherRuns": "不再运行",
+ "endsAt": "结束时间:{{when}}",
+ "proposalCreateTitle": "定时研究确认 · 创建",
+ "proposalCancelTitle": "定时研究确认 · 取消",
+ "proposalConfirmed": "已确认",
+ "proposalDiscarded": "已放弃",
+ "proposalExpired": "已过期",
+ "proposalCadence": "运行节奏",
+ "proposalTimezone": "时区",
+ "proposalEndAt": "结束时间",
+ "proposalNoEnd": "无",
+ "proposalDelivery": "结果投递",
+ "proposalInApp": "仅应用内",
+ "proposalDiscard": "放弃",
+ "proposalConfirmCreate": "确认创建",
+ "proposalConfirmCancel": "确认取消",
"nextRun": "下次运行:{{when}}",
"lastError": "最近错误:{{error}}",
"delete": "删除",
@@ -173,6 +190,7 @@
"delivery_none": "下次运行结束后推送到 {{channel}}",
"delivery_pending": "待推送到 {{channel}}",
"delivery_sending": "正在推送到 {{channel}}",
+ "delivery_accepted": "已提交到 {{channel}}(无渠道回执)",
"delivery_sent": "已推送到 {{channel}}",
"delivery_failed": "推送到 {{channel}} 失败",
"verdictEmpty": "尚无判定",
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 26cb1473d..b70e9f027 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -383,6 +383,16 @@ export const api = {
request<ScheduledRun>("/scheduled-runs", { method: "POST", body: JSON.stringify(body) }),
deleteScheduledRun: (id: string) =>
request<void>(`/scheduled-runs/${encodeURIComponent(id)}`, { method: "DELETE" }),
+ commitScheduledResearchProposal: (proposalId: string) =>
+ request<ScheduledResearchProposal>(
+ `/scheduled-runs/proposals/${encodeURIComponent(proposalId)}/commit`,
+ { method: "POST" },
+ ),
+ discardScheduledResearchProposal: (proposalId: string) =>
+ request<ScheduledResearchProposal>(
+ `/scheduled-runs/proposals/${encodeURIComponent(proposalId)}/discard`,
+ { method: "POST" },
+ ),
sendMessage: (sid: string, content: string) => request<{ message_id: string; attempt_id: string }>(`/sessions/${sid}/messages`, { method: "POST", body: JSON.stringify({ content }) }),
cancelSession: (sid: string) => request<{ status: string }>(`/sessions/${sid}/cancel`, { method: "POST" }),
getSessionMessages: (sid: string) => request<MessageItem[]>(`/sessions/${sid}/messages`),
@@ -557,6 +567,10 @@ export interface VerdictRecord {
export interface ScheduledRun {
id: string;
prompt: string;
+ title: string;
+ source_type: "prompt" | "playbook";
+ playbook_slug: string | null;
+ end_at: number | null;
schedule: string;
next_run_at: number;
status: string;
@@ -571,9 +585,13 @@ export interface ScheduledRun {
// app, which is what every monitor created before this did.
delivery_channel: string | null;
delivery_target: string | null;
+ delivery_target_ref: string | null;
+ delivery_target_label: string | null;
delivery_status: string;
delivery_error: string | null;
delivery_updated_at: number | null;
+ delivery_attempts: number;
+ delivery_provider_message_id: string | null;
// The latest run's parsed verdict, embedded with its predecessor so the list
// renders a delta in one query. Null until a completed run records one.
last_verdict: VerdictRecord | null;
@@ -581,12 +599,45 @@ export interface ScheduledRun {
export interface CreateScheduledRunRequest {
id?: string;
+ title?: string | null;
prompt: string;
schedule: string;
timezone?: string | null;
+ end_at?: number | null;
config?: Record<string, unknown>;
delivery_channel?: string | null;
delivery_target?: string | null;
+ delivery_target_ref?: string | null;
+}
+
+export interface ScheduledResearchProposalJob {
+ id: string;
+ title: string;
+ state: string;
+ source: { kind: string; playbook_slug?: string | null; prompt?: string | null };
+ schedule: {
+ expression: string;
+ timezone: string | null;
+ next_run_at: number | null;
+ end_at: number | null;
+ };
+ delivery: {
+ channel: string | null;
+ target_ref: string | null;
+ target_label: string | null;
+ status: string;
+ };
+}
+
+export interface ScheduledResearchProposal {
+ type: "scheduled_research.proposal";
+ proposal_id: string;
+ operation: "create" | "cancel";
+ status: "pending" | "committed" | "discarded" | "expired";
+ expires_at: number;
+ job: ScheduledResearchProposalJob;
+ job_id?: string | null;
+ committed_job_id?: string | null;
}
// --- Swarm types ---
diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsx
index c87d10b68..ba7dd1e3b 100644
--- a/frontend/src/pages/Agent.tsx
+++ b/frontend/src/pages/Agent.tsx
@@ -10,7 +10,7 @@ import {
type StoredAgentMessage,
} from "@/stores/agent";
import { useSSE } from "@/hooks/useSSE";
-import { ApiError, AUTH_REQUIRED_MESSAGE, api, isAuthRequiredError, type GoalSnapshot, type MandateProposal, type MandateCommitted, type LiveAction, type LiveHalted, type LLMSettings } from "@/lib/api";
+import { ApiError, AUTH_REQUIRED_MESSAGE, api, isAuthRequiredError, type GoalSnapshot, type MandateProposal, type MandateCommitted, type ScheduledResearchProposal, type LiveAction, type LiveHalted, type LLMSettings } from "@/lib/api";
import {
extractUploadedAttachments,
prependUploadedAttachments,
@@ -25,6 +25,7 @@ import { ThinkingTimeline } from "@/components/chat/ThinkingTimeline";
import { ConversationTimeline } from "@/components/chat/ConversationTimeline";
import { ActivityLine } from "@/components/chat/ActivityLine";
import { MandateProposalCard } from "@/components/chat/MandateProposalCard";
+import { ScheduledResearchProposalCard } from "@/components/chat/ScheduledResearchProposalCard";
import { SwarmStatusCard } from "@/components/chat/SwarmStatusCard";
import {
Composer,
@@ -169,7 +170,12 @@ interface LiveActionItem {
timestamp: number;
action: LiveAction;
}
-type LiveItem = ProposalItem | LiveActionItem;
+interface ScheduledProposalItem {
+ kind: "scheduled_proposal";
+ timestamp: number;
+ proposal: ScheduledResearchProposal;
+}
+type LiveItem = ProposalItem | ScheduledProposalItem | LiveActionItem;
function isCriterionStatusMet(status: string): boolean {
return !["", "pending", "open", "unsatisfied"].includes(status.toLowerCase());
@@ -1103,6 +1109,17 @@ export function Agent() {
scrollToBottom();
},
+ "scheduled_research.proposal": (d) => {
+ touch();
+ const proposal = d as unknown as ScheduledResearchProposal;
+ if (!proposal.proposal_id || !proposal.job) return;
+ setLiveItems((items) => [
+ ...items,
+ { kind: "scheduled_proposal", timestamp: Date.now(), proposal },
+ ]);
+ scrollToBottom();
+ },
+
"live.halted": (d) => {
touch();
const halted = d as unknown as LiveHalted;
@@ -1574,7 +1591,9 @@ export function Agent() {
for (const item of liveItems) {
const key = item.kind === "proposal"
? `${sessionId ?? "draft"}_lp_${item.proposal.proposal_id}`
- : `${sessionId ?? "draft"}_la_${item.action.audit_id || item.timestamp}`;
+ : item.kind === "scheduled_proposal"
+ ? `${sessionId ?? "draft"}_srp_${item.proposal.proposal_id}`
+ : `${sessionId ?? "draft"}_la_${item.action.audit_id || item.timestamp}`;
rows.push({ sort: item.timestamp, render: "live", item, key });
}
return rows.sort((a, b) => a.sort - b.sort);
@@ -1677,6 +1696,13 @@ export function Agent() {
</div>
);
}
+ if (row.item.kind === "scheduled_proposal") {
+ return (
+ <div key={row.key} className={shouldAnimate ? "msg-enter" : undefined}>
+ <ScheduledResearchProposalCard proposal={row.item.proposal} />
+ </div>
+ );
+ }
return (
<div key={row.key} className={shouldAnimate ? "msg-enter" : undefined}>
<LiveActionChip action={row.item.action} />
diff --git a/frontend/src/pages/Scheduled.tsx b/frontend/src/pages/Scheduled.tsx
index 0c4eea585..8aa903ffa 100644
--- a/frontend/src/pages/Scheduled.tsx
+++ b/frontend/src/pages/Scheduled.tsx
@@ -269,6 +269,8 @@ export function Scheduled() {
return { label: t("scheduled.statusRunning"), tone: "warning" };
case "cancelled":
return { label: t("scheduled.statusCancelled"), tone: "neutral" };
+ case "expired":
+ return { label: t("scheduled.statusExpired", { defaultValue: "Expired" }), tone: "neutral" };
default:
return { label: t("scheduled.statusPending"), tone: "neutral" };
}
@@ -463,16 +465,27 @@ export function Scheduled() {
<li key={run.id} className="flex flex-wrap items-start gap-3 p-4">
<div className="min-w-0 flex-1 space-y-1">
<div className="flex flex-wrap items-center gap-2">
+ {run.title && <span className="font-semibold">{run.title}</span>}
<span className="font-medium">{cadenceLabel(run)}</span>
<span className={hintClass}>{zone}</span>
<StatusPill label={status.label} tone={status.tone} />
</div>
<p className="truncate text-sm text-muted-foreground">{run.prompt}</p>
<p className={hintClass}>
- {t("scheduled.nextRun", {
- when: formatInZone(run.next_run_at, zone, locale),
- })}
+ {run.status === "expired"
+ ? t("scheduled.noFurtherRuns", { defaultValue: "No further runs" })
+ : t("scheduled.nextRun", {
+ when: formatInZone(run.next_run_at, zone, locale),
+ })}
</p>
+ {run.end_at && (
+ <p className={hintClass}>
+ {t("scheduled.endsAt", {
+ defaultValue: "Ends {{when}}",
+ when: formatInZone(run.end_at, zone, locale),
+ })}
+ </p>
+ )}
{run.last_error && (
<p className="break-words text-xs text-danger">
{t("scheduled.lastError", { error: run.last_error })}