Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
Add async agent run callback sessions (#550)
Call White5d3558e3c63c
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 0c866921f..e808a77d9 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -98,6 +98,9 @@ def _normalize_file_run_status(payload: dict[str, Any], state: str) -> str:return raw_status or state+TERMINAL_RUN_STATUSES = {"succeeded", "failed", "canceled"}++@dataclass(frozen=True)class ParsedSessionKey:platform: str@@ -368,6 +371,8 @@ class TaskExecutionRequest:model: Optional[str] = Nonereasoning_effort: Optional[str] = Nonesession_policy: Optional[str] = None+ callback_session_id: Optional[str] = None+ callback_status: Optional[str] = Nonedef to_dict(self) -> Dict[str, Any]:return asdict(self)@@ -394,6 +399,8 @@ class TaskExecutionRequest:model=payload.get("model"),reasoning_effort=payload.get("reasoning_effort"),session_policy=payload.get("session_policy"),+ callback_session_id=payload.get("callback_session_id"),+ callback_status=payload.get("callback_status"),)@@ -764,6 +771,7 @@ class TaskExecutionStore:source_kind: str = "cli",source_actor: Optional[str] = None,parent_run_id: Optional[str] = None,+ callback_session_id: Optional[str] = None,) -> TaskExecutionRequest:return self.enqueue(TaskExecutionRequest(@@ -778,6 +786,8 @@ class TaskExecutionStore:source_kind=source_kind,source_actor=source_actor,parent_run_id=parent_run_id,+ callback_session_id=callback_session_id,+ callback_status="pending" if callback_session_id else None,agent_name=agent_name,agent_id=agent_id,agent_backend=agent_backend,@@ -813,6 +823,67 @@ class TaskExecutionStore:return self._sqlite.list_runs(status=status)return self._list_file_runs(status=status)+ def list_pending_callbacks(self, *, limit: int = 20) -> list[dict[str, Any]]:+ if self._sqlite is not None:+ return self._sqlite.list_pending_callbacks(limit=limit)+ runs = [+ item+ for item in self._list_file_runs()+ if item.get("callback_session_id")+ and item.get("callback_status") == "pending"+ and item.get("completed_at")+ and (_normalize_requested_run_status(item.get("status")) or item.get("status")) in TERMINAL_RUN_STATUSES+ ]+ return sorted(runs, key=lambda item: (item.get("completed_at") or "", item.get("id") or ""))[:limit]++ def update_callback_status(+ self,+ run_id: str,+ *,+ status: str,+ error: Optional[str] = None,+ callback_run_id: Optional[str] = None,+ ) -> None:+ if self._sqlite is not None:+ self._sqlite.update_callback_status(+ run_id,+ status=status,+ error=error,+ callback_run_id=callback_run_id,+ )+ return+ now = _utc_now_iso()+ for state in ("pending", "processing", "completed"):+ path = self._request_path(run_id, state=state)+ if not path.exists():+ continue+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ payload = {"id": run_id}+ if not isinstance(payload, dict):+ payload = {"id": run_id}+ payload.update(+ {+ "callback_status": status,+ "callback_error": error,+ "callback_run_id": callback_run_id if callback_run_id is not None else payload.get("callback_run_id"),+ "callback_completed_at": now,+ "updated_at": now,+ }+ )+ with tempfile.NamedTemporaryFile(+ mode="w",+ dir=path.parent,+ suffix=".tmp",+ delete=False,+ encoding="utf-8",+ ) as handle:+ json.dump(payload, handle, indent=2)+ tmp_path = Path(handle.name)+ tmp_path.replace(path)+ return+def list_runs_page(self,*,@@ -1032,6 +1103,7 @@ class TaskExecutionStore:"task_id": task_id if task_id is not None else request.task_id,"session_key": session_key if session_key is not None else request.session_key,"session_id": session_id if session_id is not None else request.session_id,+ "callback_session_id": request.callback_session_id,})with tempfile.NamedTemporaryFile(@@ -1156,6 +1228,7 @@ class ScheduledTaskService:if self.store.maybe_reload():self.reconcile_jobs()await self._drain_requests()+ await self._drain_callbacks()await asyncio.sleep(2)except asyncio.CancelledError:raise@@ -1256,6 +1329,83 @@ class ScheduledTaskService:continueself._spawn_execution(request, lock_key)+ async def _drain_callbacks(self) -> None:+ for run in self.request_store.list_pending_callbacks():+ run_id = str(run.get("id") or "")+ if not run_id:+ continue+ try:+ callback_run = self._enqueue_callback_run(run)+ except Exception as exc:+ logger.error("Agent run callback failed for %s: %s", run_id, exc, exc_info=True)+ self.request_store.update_callback_status(run_id, status="failed", error=str(exc))+ continue+ if callback_run is None:+ self.request_store.update_callback_status(run_id, status="skipped")+ continue+ self.request_store.update_callback_status(run_id, status="sent", callback_run_id=callback_run.id)++ def _enqueue_callback_run(self, run: dict[str, Any]) -> Optional[TaskExecutionRequest]:+ callback_session_id = str(run.get("callback_session_id") or "").strip()+ if not callback_session_id:+ return None+ target_info = resolve_session_id_target(callback_session_id)+ message = self._build_callback_message(run)+ if not message.strip():+ return None+ return self.request_store.enqueue_agent_run(+ session_id=callback_session_id,+ session_key=target_info.session_key.to_key(),+ message=message,+ agent_name=target_info.agent_name,+ agent_id=target_info.agent_id,+ agent_backend=target_info.agent_backend,+ model=target_info.model,+ reasoning_effort=target_info.reasoning_effort,+ session_policy="existing",+ source_kind="callback",+ source_actor=str(run.get("id") or ""),+ parent_run_id=str(run.get("id") or "") or None,+ )++ def _build_callback_message(self, run: dict[str, Any]) -> str:+ status = _normalize_requested_run_status(run.get("status")) or str(run.get("status") or "")+ lines = [+ "Async Agent Run completed.",+ "",+ f"Run ID: {run.get('id') or ''}",+ f"Status: {status}",+ ]+ agent = run.get("agent_name") or run.get("agent_backend")+ if agent:+ lines.append(f"Agent: {agent}")+ target_session = run.get("session_id")+ if target_session:+ lines.append(f"Target Session: {target_session}")+ result_text = str(run.get("result_text") or "").strip()+ if not result_text:+ result_text = self._fallback_callback_result(run, status=status)+ if result_text:+ lines.extend(["", result_text])+ return "\n".join(lines).strip()++ @staticmethod+ def _fallback_callback_result(run: dict[str, Any], *, status: str) -> str:+ parts: list[str] = []+ if run.get("error"):+ parts.append(f"Error: {run['error']}")+ if run.get("stderr"):+ parts.append(str(run["stderr"]))+ if run.get("stdout") and status != "succeeded":+ parts.append(str(run["stdout"]))+ if parts:+ return "\n\n".join(part.strip() for part in parts if part and part.strip())+ if status == "canceled":+ return "The run was canceled before producing a result."+ if status == "failed":+ return "The run failed before producing a result."+ return ""+def _execution_lock_key(self, request: TaskExecutionRequest) -> Optional[str]:"""Canonical conversation identity for per-session single-flight.@@ -1425,6 +1575,7 @@ class ScheduledTaskService:session_key=session_key,session_id=session_id,)+ await self._drain_callbacks()async def _execute_task(self,diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex 17277aac9..11864639d 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -177,6 +177,8 @@ Useful Harness queries include schema discovery, current session lookup, existin`vibe watch add` creates a managed monitor, usually backed by a small script or command, for any observable condition that must be watched until true: product signals, business events, files, logs, CI/reviews/deploys, service health, data freshness, and similar signals.+Use `vibe agent run --async --callback-session-id {default_session_id}` when one Agent delegates work to another Session and the completed run result should return to this caller Session as a follow-up Agent message.+`--post-to` changes the delivery target, not the session scope. Use `--post-to channel` when the session should stay thread-scoped but the follow-up message should be posted to the parent channel. For tasks, use `--message "..."` or `--message-file <path>` as the stored message. For watches, use `--prefix "..."` for the follow-up instruction prepended before waiter stdout.Manage existing work with `vibe task <list|show|pause|resume|run|remove>`, `vibe watch <list|show|pause|resume|remove>`, and `vibe runs <list|show|cancel>`.diff --git a/docs/CLI.md b/docs/CLI.mdindex 6f2653ff8..cf907925e 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -204,9 +204,15 @@ a scheduled task definition.```bashvibe agent run --agent release-reviewer --message 'Review the latest deployment result.'vibe agent run --async --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'+vibe agent run --async --session-id sesworker123 --callback-session-id sescaller456 --message 'Run the delegated investigation.'vibe agent run --async --create-session --deliver-key slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'```+Use `--callback-session-id` when an async run should send its full terminal+result back into a caller Session as a follow-up Agent message. The callback is+independent from ordinary delivery: if the target run also posts to its IM scope,+the caller Session still receives the result.+`vibe hook send` is kept only as a deprecated compatibility entrypoint. Newautomation should use `vibe agent run`.diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex f6b5b3201..ca3e53c40 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -185,9 +185,15 @@ vibe task remove <task-id>```bashvibe agent run --agent release-reviewer --message 'Review the latest deployment result.'vibe agent run --async --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'+vibe agent run --async --session-id sesworker123 --callback-session-id sescaller456 --message 'Run the delegated investigation.'vibe agent run --async --create-session --deliver-key slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'```+当异步 run 的完整终态结果需要回到调用方 Session 时,使用+`--callback-session-id`。这个 callback 与普通投递相互独立:即使目标 run 已经把+结果发到了自己的 IM scope,调用方 Session 仍然会收到完整结果并触发一次跟进+Agent 消息。+`vibe hook send` 仅作为 deprecated 兼容入口保留。新的自动化入口应使用`vibe agent run`。diff --git a/docs/plans/agent-run-callback-session.md b/docs/plans/agent-run-callback-session.mdnew file mode 100644index 000000000..aad525c77--- /dev/null+++ b/docs/plans/agent-run-callback-session.md@@ -0,0 +1,261 @@+# Agent Run Callback Session++Status: proposal.++## Background++`vibe agent run --async` already lets one Agent queue work that continues in the+background. The missing piece is a first-class way for the completed run to+return its full result to the Session that initiated or is waiting for that+work.++This is especially important for Agent-to-Agent delegation:++```text+caller Session -> async Agent Run -> target Session/scope+ |+ v+ full result callback+ |+ v+ caller Session continues+```++Terminology:++- **Target Session**: the Session where the async run executes.+- **Caller Session**: the Session that should receive the completed run result.+- **Callback**: a follow-up Agent message created from the completed run result+ and delivered to the Caller Session.++Avoid "parent Session" / "parent Agent" in user-facing naming because that can+confuse run lineage with message delivery.++## Product Semantics++Add a callback option to direct Agent Runs:++```bash+vibe agent run \+ --async \+ --session-id <target-session-id> \+ --callback-session-id <caller-session-id> \+ --message "Run this delegated task."+```++Rules:++- `--callback-session-id` names the Caller Session.+- The async run still executes in its own Target Session or target scope exactly+ as it does today.+- When the async run reaches a terminal state, Avibe sends the full execution+ result as a new message to the Caller Session.+- Callback delivery is independent from ordinary output delivery. If the target+ run also posts to its IM scope, the callback still happens.+- Callback sends all terminal outcomes for v1: success, failure, cancellation,+ and terminal errors. Do not add filtering flags yet.+- The callback message should enter the Caller Session through the same+ scheduled/watch-style turn path, so it queues behind any active turn instead+ of interrupting it.+- The callback message should trigger the Caller Session Agent as a normal+ follow-up message. It is not just passive transcript decoration.++## Message Content++The callback message should contain the completed run result, not a tiny status+notification.++Priority:++1. Use `agent_runs.result_text` when present.+2. If the run failed and has no `result_text`, construct a full failure result+ from `error`, `stderr`, and relevant run metadata.+3. If the run was canceled and has no `result_text`, construct a cancellation+ result.+4. If there is truly no result content, skip sending an empty callback but+ persist the callback state as skipped.++Recommended wrapper format:++```text+Async Agent Run completed.++Run ID: <run-id>+Status: <succeeded|failed|canceled>+Agent: <agent-name>+Target Session: <target-session-id>++<full result text or failure details>+```++The wrapper is intentionally small. The result text remains the main payload.++## CLI/API Shape++### CLI++Add to `vibe agent run`:++```bash+--callback-session-id <session-id>+```++Validation:++- v1 requires `--async` when `--callback-session-id` is passed.+- The callback session id must resolve to an active `agent_sessions` row.+- Archived sessions are invalid.+- Callback to the same Session is allowed but should be documented as a loop+ risk for automation authors.+- `--callback-session-id` is orthogonal to `--post-to` and `--deliver-key`.++Output payload should include:++```json+{+ "callback_session_id": "ses...",+ "run": {+ "callback_session_id": "ses..."+ }+}+```++### Internal/API Payload++Carry `callback_session_id` through the same run-spec path as `session_id`,+`post_to`, and `deliver_key`, so CLI, future UI/API creation, and persisted run+history do not drift.++## Data Model++Add persisted callback fields to `agent_runs`.++Minimum v1 columns:++- `callback_session_id text null`+- `callback_status text null`+- `callback_error text null`+- `callback_run_id text null`+- `callback_completed_at text null`++Suggested callback statuses:++- `pending`: callback requested but not attempted.+- `sent`: callback run/message was queued successfully.+- `skipped`: no callback was sent because no callback was requested or there+ was no content to send.+- `failed`: callback dispatch failed.++Why explicit columns instead of only `metadata_json`:++- callback state is user-visible run state;+- it needs to be queryable in `vibe runs show/list`;+- retries/debugging should not depend on parsing opaque metadata.++Also update:++- SQLAlchemy model definition.+- Alembic migration.+- lightweight local migration path in `storage/migrations.py`.+- import/export or state-backfill paths that enumerate `agent_runs` columns.++## Execution Design++Callback should happen in the Harness execution layer after the target run is+terminal and after `result_text` has been recorded.++High-level flow:++1. `vibe agent run --async ... --callback-session-id ses_calling` enqueues an+ `agent_run` row with `callback_session_id=ses_calling` and+ `callback_status=pending`.+2. The scheduler/request drain executes the target run as today.+3. Terminal output is recorded on the target `agent_runs` row.+4. The Harness layer builds callback message content from the terminal run row.+5. The Harness layer enqueues a new callback Agent Run into the Caller Session+ using the same scheduled/watch Agent turn path.+6. The original run persists the callback update as `sent`, `skipped`, or+ `failed`, including `callback_run_id` when a follow-up run is created.++Important boundary:++- Do not implement callback in the CLI process. `--async` returns immediately,+ and callback must survive CLI exit and service restart.++## Turn/Queue Semantics++For Workbench/Avibe Sessions:++- callback enters `SessionTurnManager.submit_scheduled(...)`;+- if the Caller Session is busy, callback is queued;+- if idle, callback starts a normal scheduled-source turn;+- callback must not interrupt the active turn.++For IM-backed Sessions:++- callback uses the existing scheduled-message path and delivery context for+ that Session.++This mirrors watch follow-up behavior and keeps callback behavior consistent+with existing Harness semantics.++## Failure Handling++The target run can succeed while callback fails. These are separate outcomes.++Run status remains the target execution result:++- target succeeded + callback failed => run status `succeeded`,+ `callback_status=failed`.+- target failed + callback sent => run status `failed`, callback still records+ `sent`.++Retries:++- v1 can be manual: `vibe runs show <run-id>` exposes callback failure details.+- A later `vibe runs callback <run-id>` or `vibe runs retry-callback <run-id>`+ can be added if needed.++## Tests++Focused test coverage:++- CLI parser accepts `--callback-session-id` only for async direct Agent Runs.+- CLI payload and persisted row include `callback_session_id`.+- unresolved/archived callback Session is rejected.+- completed successful run dispatches full `result_text` into Caller Session.+- failed run without `result_text` dispatches constructed failure content.+- target IM delivery and callback both happen when both are configured.+- busy Workbench Caller Session queues callback instead of interrupting.+- callback failure does not overwrite target run status.+- `vibe runs show` includes callback state.++## Documentation++Update:++- CLI docs for `vibe agent run`.+- Chinese CLI docs.+- `skills/use-avibe/SKILL.md` if command guidance mentions async Agent Runs.++Docs should use "Caller Session" / "调用方 Session" consistently.++## Non-Goals For v1++- No `--callback-on success|failure|always` filter.+- No result summarization/compression.+- No callback retry command unless implementation reveals the need.+- No special "parent run" behavior.+- No automatic loop prevention beyond normal session serialization.++## Implementation Sequence++1. Add schema/model/store support for callback fields.+2. Extend `TaskExecutionRequest` and `enqueue_agent_run(...)` to carry+ `callback_session_id`.+3. Add CLI flag, validation, and JSON output.+4. Add callback message builder from terminal run rows.+5. Dispatch callback through the scheduled/watch-style Session path.+6. Expose callback state in `vibe runs show/list`.+7. Add focused unit tests.+8. Update CLI docs and Avibe skill docs.diff --git a/skills/use-avibe/SKILL.md b/skills/use-avibe/SKILL.mdindex 8b58cd05d..9f393007b 100644--- a/skills/use-avibe/SKILL.md+++ b/skills/use-avibe/SKILL.md@@ -770,6 +770,7 @@ Preferred CLI shape:- one-shot direct run: `vibe agent run --agent '<agent-name>' --message '...'`- one-shot async run: `vibe agent run --async --session-id '<session-id>' --message '...'`+- delegated async run that reports back: `vibe agent run --async --session-id '<target-session-id>' --callback-session-id '<caller-session-id>' --message '...'`- recurring task: `vibe task add --session-id '<session-id>' --cron '<expr>' --message '...'`- one-off task: `vibe task add --session-id '<session-id>' --at '<ISO-8601>' --message '...'`- immediate rerun: `vibe task run <id>`@@ -789,6 +790,7 @@ Delivery controls (apply to `vibe agent run --create-session`, `vibe task add`,- `--message` and `--message-file` are the current user-message flags for task, watch, and agent-run commands- `vibe task add` stores the message template and creates Agent Runs when the time trigger fires- `vibe agent run --async` queues one Agent Run immediately without storing a task definition+- `--callback-session-id` on an async Agent Run sends the completed run result back into the caller Session as a follow-up Agent message; it is independent from `--post-to` and `--deliver-key`- `vibe watch add` uses `--message` as the instruction template for the Agent Run created after the waiter reaches a reportable stateLegacy compatibility:diff --git a/storage/alembic/versions/20260522_0003_agent_runs_schema.py b/storage/alembic/versions/20260522_0003_agent_runs_schema.pyindex d3694d3f3..a3f581db2 100644--- a/storage/alembic/versions/20260522_0003_agent_runs_schema.py+++ b/storage/alembic/versions/20260522_0003_agent_runs_schema.py@@ -116,6 +116,11 @@ def upgrade() -> None:_add_column_if_missing("agent_runs", "result_text", sa.Column("result_text", sa.Text(), nullable=True))_add_column_if_missing("agent_runs", "result_payload_json", sa.Column("result_payload_json", sa.Text(), nullable=True))_add_column_if_missing("agent_runs", "message_ids_json", sa.Column("message_ids_json", sa.Text(), nullable=True))+ _add_column_if_missing("agent_runs", "callback_session_id", sa.Column("callback_session_id", sa.String(), nullable=True))+ _add_column_if_missing("agent_runs", "callback_status", sa.Column("callback_status", sa.String(), nullable=True))+ _add_column_if_missing("agent_runs", "callback_error", sa.Column("callback_error", sa.Text(), nullable=True))+ _add_column_if_missing("agent_runs", "callback_run_id", sa.Column("callback_run_id", sa.String(), nullable=True))+ _add_column_if_missing("agent_runs", "callback_completed_at", sa.Column("callback_completed_at", sa.String(), nullable=True))_add_column_if_missing("agent_runs","cancel_requested",@@ -133,6 +138,7 @@ def upgrade() -> None:)op.create_index("ix_agent_runs_session_created", "agent_runs", ["session_id", "created_at"], if_not_exists=True)op.create_index("ix_agent_runs_agent_created", "agent_runs", ["agent_name", "created_at"], if_not_exists=True)+ op.create_index("ix_agent_runs_callback_status", "agent_runs", ["callback_status", "completed_at"], if_not_exists=True)def downgrade() -> None:diff --git a/storage/alembic/versions/20260610_0022_agent_run_callback_session.py b/storage/alembic/versions/20260610_0022_agent_run_callback_session.pynew file mode 100644index 000000000..acef4b613--- /dev/null+++ b/storage/alembic/versions/20260610_0022_agent_run_callback_session.py@@ -0,0 +1,42 @@+"""agent run callback session fields++Revision ID: 20260610_0022+Revises: 20260608_0021+Create Date: 2026-06-10+"""++from __future__ import annotations++import sqlalchemy as sa+from alembic import op++revision = "20260610_0022"+down_revision = "20260608_0021"+branch_labels = None+depends_on = None+++def _columns(table_name: str) -> set[str]:+ bind = op.get_bind()+ return {row[1] for row in bind.exec_driver_sql(f'pragma table_info("{table_name}")')}+++def _add_column_if_missing(table_name: str, column_name: str, column: sa.Column) -> None:+ if column_name not in _columns(table_name):+ op.add_column(table_name, column)+++def upgrade() -> None:+ _add_column_if_missing("agent_runs", "callback_session_id", sa.Column("callback_session_id", sa.String(), nullable=True))+ _add_column_if_missing("agent_runs", "callback_status", sa.Column("callback_status", sa.String(), nullable=True))+ _add_column_if_missing("agent_runs", "callback_error", sa.Column("callback_error", sa.Text(), nullable=True))+ _add_column_if_missing("agent_runs", "callback_run_id", sa.Column("callback_run_id", sa.String(), nullable=True))+ _add_column_if_missing("agent_runs", "callback_completed_at", sa.Column("callback_completed_at", sa.String(), nullable=True))+ op.create_index("ix_agent_runs_callback_status", "agent_runs", ["callback_status", "completed_at"], if_not_exists=True)+++def downgrade() -> None:+ op.drop_index("ix_agent_runs_callback_status", table_name="agent_runs", if_exists=True)+ # SQLite cannot drop columns without table rebuild; keep additive fields on downgrade.+ return None+diff --git a/storage/background.py b/storage/background.pyindex 8b64d9fa4..895e2323d 100644--- a/storage/background.py+++ b/storage/background.py@@ -525,6 +525,23 @@ class SQLiteBackgroundTaskStore:row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()return self._run_from_row(row) if row else None+ def list_pending_callbacks(self, *, limit: int = 20) -> list[dict[str, Any]]:+ terminal_statuses = _status_query_values("succeeded") + _status_query_values("failed") + _status_query_values("canceled")+ with self.engine.connect() as conn:+ rows = list(+ conn.execute(+ select(agent_runs)+ .where(agent_runs.c.callback_session_id.is_not(None))+ .where(agent_runs.c.callback_session_id != "")+ .where(agent_runs.c.callback_status == "pending")+ .where(agent_runs.c.completed_at.is_not(None))+ .where(agent_runs.c.status.in_(terminal_statuses))+ .order_by(agent_runs.c.completed_at, agent_runs.c.id)+ .limit(limit)+ ).mappings()+ )+ return [self._run_from_row(row) for row in rows]+def cancel_run(self, run_id: str, *, requested_at: Optional[str] = None) -> bool:now = requested_at or _utc_now_iso()with self.engine.begin() as conn:@@ -593,6 +610,10 @@ class SQLiteBackgroundTaskStore:cancel_requested: Optional[bool] = None,cancel_requested_at: Optional[str] = None,metadata: Optional[dict[str, Any]] = None,+ callback_status: Optional[str] = None,+ callback_error: Optional[str] = None,+ callback_run_id: Optional[str] = None,+ callback_completed_at: Optional[str] = None,) -> None:values: dict[str, Any] = {"status": status,@@ -631,6 +652,35 @@ class SQLiteBackgroundTaskStore:values["cancel_requested_at"] = cancel_requested_atif metadata is not None:values["metadata_json"] = _json_dumps(metadata)+ if callback_status is not None:+ values["callback_status"] = callback_status+ if callback_error is not None:+ values["callback_error"] = callback_error+ if callback_run_id is not None:+ values["callback_run_id"] = callback_run_id+ if callback_completed_at is not None:+ values["callback_completed_at"] = callback_completed_at+ with self.engine.begin() as conn:+ conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))++ def update_callback_status(+ self,+ run_id: str,+ *,+ status: str,+ error: Optional[str] = None,+ callback_run_id: Optional[str] = None,+ completed_at: Optional[str] = None,+ ) -> None:+ now = completed_at or _utc_now_iso()+ values: dict[str, Any] = {+ "callback_status": status,+ "callback_error": error,+ "callback_completed_at": now,+ "updated_at": now,+ }+ if callback_run_id is not None:+ values["callback_run_id"] = callback_run_idwith self.engine.begin() as conn:conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))@@ -897,6 +947,11 @@ class SQLiteBackgroundTaskStore:"result_text": payload.get("result_text"),"result_payload_json": self._payload_json(payload, "result_payload", "result_payload_json"),"message_ids_json": self._payload_json(payload, "message_ids", "message_ids_json"),+ "callback_session_id": payload.get("callback_session_id"),+ "callback_status": payload.get("callback_status") or ("pending" if payload.get("callback_session_id") else None),+ "callback_error": payload.get("callback_error"),+ "callback_run_id": payload.get("callback_run_id"),+ "callback_completed_at": payload.get("callback_completed_at"),"cancel_requested": 1 if payload.get("cancel_requested") else 0,"cancel_requested_at": payload.get("cancel_requested_at"),"pid": payload.get("pid"),@@ -997,6 +1052,11 @@ class SQLiteBackgroundTaskStore:"result_text": row["result_text"],"result_payload": _json_loads(row["result_payload_json"], None),"message_ids": _json_loads(row["message_ids_json"], []),+ "callback_session_id": row["callback_session_id"],+ "callback_status": row["callback_status"],+ "callback_error": row["callback_error"],+ "callback_run_id": row["callback_run_id"],+ "callback_completed_at": row["callback_completed_at"],"cancel_requested": bool(row["cancel_requested"]),"cancel_requested_at": row["cancel_requested_at"],"pid": row["pid"],diff --git a/storage/migrations.py b/storage/migrations.pyindex 105a01123..1f0beda97 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -12,7 +12,7 @@ from config import pathsfrom storage.db import create_sqlite_engine, sqlite_urlINITIAL_REVISION = "20260501_0001"-LATEST_SCHEMA_REVISION = "20260608_0021"+LATEST_SCHEMA_REVISION = "20260610_0022"REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"INITIAL_TABLES = {"state_meta",@@ -69,6 +69,11 @@ HEAD_REQUIRED_COLUMNS = {"result_text","result_payload_json","message_ids_json",+ "callback_session_id",+ "callback_status",+ "callback_error",+ "callback_run_id",+ "callback_completed_at","cancel_requested","cancel_requested_at",},@@ -351,6 +356,11 @@ def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) ->"result_text": "TEXT","result_payload_json": "TEXT","message_ids_json": "TEXT",+ "callback_session_id": "VARCHAR",+ "callback_status": "VARCHAR",+ "callback_error": "TEXT",+ "callback_run_id": "VARCHAR",+ "callback_completed_at": "VARCHAR","cancel_requested": "INTEGER not null default 0","cancel_requested_at": "VARCHAR",}.items():@@ -476,6 +486,7 @@ def _ensure_new_background_indexes(conn: sqlite3.Connection) -> None:conn.execute('create index if not exists ix_agent_runs_type_status_created on agent_runs (run_type, status, created_at)')conn.execute('create index if not exists ix_agent_runs_session_created on agent_runs (session_id, created_at)')conn.execute('create index if not exists ix_agent_runs_agent_created on agent_runs (agent_name, created_at)')+ conn.execute('create index if not exists ix_agent_runs_callback_status on agent_runs (callback_status, completed_at)')def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:diff --git a/storage/models.py b/storage/models.pyindex ee48aac95..a1b958b55 100644--- a/storage/models.py+++ b/storage/models.py@@ -224,6 +224,11 @@ agent_runs = Table(Column("result_text", Text, nullable=True),Column("result_payload_json", Text, nullable=True),Column("message_ids_json", Text, nullable=True),+ Column("callback_session_id", String, nullable=True),+ Column("callback_status", String, nullable=True),+ Column("callback_error", Text, nullable=True),+ Column("callback_run_id", String, nullable=True),+ Column("callback_completed_at", String, nullable=True),Column("cancel_requested", Integer, nullable=False, default=0),Column("cancel_requested_at", String, nullable=True),Column("pid", Integer, nullable=True),@@ -241,6 +246,7 @@ agent_runs = Table(Index("ix_agent_runs_type_status_created", "run_type", "status", "created_at"),Index("ix_agent_runs_session_created", "session_id", "created_at"),Index("ix_agent_runs_agent_created", "agent_name", "created_at"),+ Index("ix_agent_runs_callback_status", "callback_status", "completed_at"),)# Backwards-compatible Python aliases for legacy callers. The physical tablediff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.pyindex 2b14c793d..72decc930 100644--- a/tests/test_cli_agent_run_schema.py+++ b/tests/test_cli_agent_run_schema.py@@ -41,11 +41,12 @@ _EXPECTED_KEYS = {"session_policy","session_id","deliver_key",+ "callback_session_id","async","run",}-_EXPECTED_RUN_KEYS_QUEUED = {"id", "status", "run_type", "agent_name", "session_id"}+_EXPECTED_RUN_KEYS_QUEUED = {"id", "status", "run_type", "agent_name", "session_id", "callback_session_id"}def test_agent_run_async_envelope_schema(tmp_path: Path, capsys) -> None:@@ -70,7 +71,8 @@ def test_agent_run_async_envelope_schema(tmp_path: Path, capsys) -> None:result = cli.cmd_agent_run(args)assert result == 0- payload = json.loads(capsys.readouterr().out)+ captured = capsys.readouterr()+ payload = json.loads(captured.out or captured.err)# Envelope shape — these are the public keys that downstream tooling# parses; any rename / drop is a breaking change.assert set(payload.keys()) == _EXPECTED_KEYS, (@@ -90,3 +92,91 @@ def test_agent_run_async_envelope_schema(tmp_path: Path, capsys) -> None:assert run["run_type"] == "agent_run"assert run["agent_name"] == "worker"assert run["id"] == payload["run_id"]+++def test_agent_run_async_accepts_callback_session_id(tmp_path: Path, capsys) -> None:+ from core.services import sessions as sessions_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.models import scope_settings+ from storage.settings_service import upsert_scope++ state_home = tmp_path / "home"+ with patch.dict("os.environ", {"VIBE_REMOTE_HOME": str(state_home)}):+ ensure_sqlite_state()+ db_path = state_home / "state" / "vibe.sqlite"+ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_callback",+ now="2026-06-10T00:00:00Z",+ )+ conn.execute(+ scope_settings.insert().values(+ scope_id=scope_id,+ enabled=1,+ role=None,+ workdir=str(tmp_path),+ agent_name=None,+ agent_backend=None,+ agent_variant=None,+ model=None,+ reasoning_effort=None,+ require_mention=None,+ settings_version=1,+ settings_json="{}",+ created_at="2026-06-10T00:00:00Z",+ updated_at="2026-06-10T00:00:00Z",+ )+ )+ callback_session = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="codex",+ agent_name="worker",+ )+ agent_store = cli.VibeAgentStore(db_path)+ agent_store.create(name="worker", backend="codex")+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")+ args = _parse_agent_run(+ [+ "--agent",+ "worker",+ "--async",+ "--callback-session-id",+ callback_session["id"],+ "--message",+ "hi",+ ]+ )++ with (+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._task_request_store", return_value=request_store),+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),+ patch("vibe.cli._primary_platform", return_value="slack"),+ ):+ result = cli.cmd_agent_run(args)++ assert result == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["callback_session_id"] == callback_session["id"]+ assert payload["run"]["callback_session_id"] == callback_session["id"]+ stored = request_store.get_run(payload["run_id"])+ assert stored is not None+ assert stored["callback_session_id"] == callback_session["id"]+ assert stored["callback_status"] == "pending"+++def test_agent_run_callback_session_requires_async(capsys) -> None:+ args = _parse_agent_run(["--agent", "worker", "--callback-session-id", "ses1", "--message", "hi"])++ result = cli.cmd_agent_run(args)++ assert result == 1+ captured = capsys.readouterr()+ payload = json.loads(captured.out or captured.err)+ assert payload["code"] == "callback_requires_async"diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.pyindex 2b755ea29..576390387 100644--- a/tests/test_reply_enhancer_platform.py+++ b/tests/test_reply_enhancer_platform.py@@ -335,6 +335,8 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertIn("`vibe task add` creates a time-triggered saved Agent message", prompt)self.assertIn("`vibe watch add` creates a managed monitor", prompt)self.assertIn("product signals, business events, files, logs, CI/reviews/deploys", prompt)+ self.assertIn("vibe agent run --async --callback-session-id sesk8m4q2p7x", prompt)+ self.assertIn("completed run result should return to this caller Session", prompt)self.assertIn("`--post-to` changes the delivery target, not the session scope. Use `--post-to channel` when the session should stay thread-scoped but the follow-up message should be posted to the parent channel.",prompt,diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 238f7562d..0886a4dcb 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -1346,6 +1346,91 @@ def test_agent_run_preserves_failed_terminal_status(tmp_path: Path, monkeypatch)assert completed["result_text"] == "terminal failed"+def test_agent_run_callback_enqueues_full_result_to_caller_session(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ caller_session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ request = request_store.enqueue_agent_run(+ session_id="target-session",+ message="delegated work",+ agent_name="codex",+ callback_session_id=caller_session_id,+ )+ request_store.complete(request, ok=True, session_id="target-session")+ store = SQLiteBackgroundTaskStore()+ try:+ store.record_run_message(+ request.id,+ text="complete delegated result",+ message_id=f"suppressed:{request.id}",+ terminal_status="succeeded",+ )+ finally:+ store.close()++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ return None++ controller = _avibe_controller_double(+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),+ handle_scheduled_message=_handle_scheduled_message,+ )+ service = ScheduledTaskService(+ controller=controller,+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )++ asyncio.run(service._drain_callbacks())++ original = request_store.get_run(request.id)+ assert original is not None+ assert original["callback_status"] == "sent"+ callback_run_id = original["callback_run_id"]+ assert callback_run_id+ callback_run = request_store.get_run(callback_run_id)+ assert callback_run is not None+ assert callback_run["session_id"] == caller_session_id+ assert callback_run["source_kind"] == "callback"+ assert callback_run["parent_run_id"] == request.id+ assert "Async Agent Run completed." in callback_run["message"]+ assert f"Run ID: {request.id}" in callback_run["message"]+ assert "Status: succeeded" in callback_run["message"]+ assert "Target Session: target-session" in callback_run["message"]+ assert "complete delegated result" in callback_run["message"]+++def test_agent_run_callback_builds_failure_message_without_result_text(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ caller_session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ request = request_store.enqueue_agent_run(+ session_id="target-session",+ message="delegated work",+ agent_name="codex",+ callback_session_id=caller_session_id,+ )+ request_store.complete(request, ok=False, error="agent crashed", session_id="target-session")+ service = ScheduledTaskService(+ controller=_avibe_controller_double(+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),+ handle_scheduled_message=lambda *_args, **_kwargs: None,+ ),+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )++ asyncio.run(service._drain_callbacks())++ original = request_store.get_run(request.id)+ assert original is not None+ assert original["callback_status"] == "sent"+ callback_run = request_store.get_run(original["callback_run_id"])+ assert callback_run is not None+ assert "Status: failed" in callback_run["message"]+ assert "Error: agent crashed" in callback_run["message"]++def test_agent_run_synchronous_dispatch_error_marks_failed(tmp_path: Path, monkeypatch) -> None:monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))request_store = TaskExecutionStore()diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 131e51b99..2a6758603 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -16,7 +16,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260608_0021"+HEAD_REVISION = "20260610_0022"def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:diff --git a/vibe/cli.py b/vibe/cli.pyindex b78d9bcaf..c70f54410 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -1585,6 +1585,9 @@ def _run_payload(run: dict, *, brief: bool = False) -> dict:"started_at": normalized.get("started_at"),"completed_at": normalized.get("completed_at"),"error": normalized.get("error"),+ "callback_session_id": normalized.get("callback_session_id"),+ "callback_status": normalized.get("callback_status"),+ "callback_run_id": normalized.get("callback_run_id"),}return normalized@@ -2570,6 +2573,13 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:hint="--async returns immediately. Remove --wait-timeout, or run synchronously without --async.",help_command=help_command,)+ if (getattr(args, "callback_session_id", None) or "").strip() and not bool(getattr(args, "async_run", False)):+ raise TaskCliError(+ "--callback-session-id requires --async",+ code="callback_requires_async",+ hint="Callback delivery happens after an asynchronous run completes.",+ help_command=help_command,+ )if session_id and (create_session or create_per_run):raise TaskCliError("use either --session-id or --create-session, not both",@@ -2819,6 +2829,9 @@ def cmd_agent_run(args):deliver_key=args.deliver_key,help_command="vibe agent run --help",)+ callback_session_id = (getattr(args, "callback_session_id", None) or "").strip() or None+ if callback_session_id:+ resolve_session_id_target(callback_session_id)request_store = _task_request_store()request = request_store.enqueue_agent_run(agent_name=agent.name if agent else None,@@ -2832,6 +2845,7 @@ def cmd_agent_run(args):post_to=args.post_to,deliver_key=args.deliver_key,message=message,+ callback_session_id=callback_session_id,)payload = {"accepted": True,@@ -2842,6 +2856,7 @@ def cmd_agent_run(args):"session_policy": session_policy,"session_id": session_id,"deliver_key": args.deliver_key,+ "callback_session_id": callback_session_id,"async": bool(args.async_run),"run": {"id": request.id,@@ -2849,6 +2864,7 @@ def cmd_agent_run(args):"run_type": request.request_type,"agent_name": agent.name if agent else None,"session_id": session_id,+ "callback_session_id": callback_session_id,},}if not args.async_run:@@ -5736,6 +5752,7 @@ def build_parser():agent_run_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID for each definition run")agent_run_parser.add_argument("--deliver-key", help="Scope ID used as delivery target when creating or sending to a target")agent_run_parser.add_argument("--post-to", choices=("thread", "channel"))+ agent_run_parser.add_argument("--callback-session-id", help="Caller Session ID to receive the completed async run result")agent_run_parser.add_argument("--async", dest="async_run", action="store_true", help="Queue the run and return immediately")agent_run_parser.add_argument("--wait-timeout", type=float, help="Maximum seconds the CLI waits for a synchronous run result")agent_message_group = agent_run_parser.add_mutually_exclusive_group(required=True)