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
feat(tasks): separate session and delivery targets
cyh2b7819eea021
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex d930eb6ac..054c48e65 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -63,41 +63,66 @@ class SessionHandler(BaseHandler):*,source_base_session_id: str,alias_base_session_id: str,+ target_session_key: Optional[str] = None,+ source_session_key: Optional[str] = None,clear_source: bool = False,) -> bool:if not source_base_session_id or not alias_base_session_id:return False- session_key = self._get_session_key(context)- changed = self.sessions.alias_session_base(- session_key,- source_base_session_id,- alias_base_session_id,- )+ resolved_source_key = source_session_key or self._get_session_key(context)+ resolved_target_key = target_session_key or resolved_source_key+ if resolved_target_key == resolved_source_key:+ changed = self.sessions.alias_session_base(+ resolved_target_key,+ source_base_session_id,+ alias_base_session_id,+ )+ else:+ changed = self.sessions.alias_session_base_across_scopes(+ resolved_source_key,+ resolved_target_key,+ source_base_session_id,+ alias_base_session_id,+ )if changed and clear_source and source_base_session_id != alias_base_session_id:- self.sessions.clear_session_base(session_key, source_base_session_id)+ self.sessions.clear_session_base(resolved_source_key, source_base_session_id)return changeddef finalize_scheduled_delivery(self, context: MessageContext, sent_message_id: Optional[str]) -> None:payload = context.platform_specific or {}if payload.get("turn_source") != "scheduled":return- if context.thread_id or not payload.get("scheduled_anchor_required"):+ source_base_session_id = payload.get("turn_base_session_id") or ""+ strategy = payload.get("scheduled_delivery_alias") or {}+ mode = strategy.get("mode") or "none"+ if not source_base_session_id or mode == "none":return- if not sent_message_id:++ alias_base_session_id: Optional[str] = None+ if mode == "sent_message":+ if not sent_message_id:+ return+ alias_base_session_id = self.build_message_anchor_base(context, sent_message_id)+ elif mode == "fixed_base":+ alias_base_session_id = strategy.get("base_session_id")+ if not alias_base_session_id:return- source_base_session_id = payload.get("turn_base_session_id") or ""- alias_base_session_id = self.build_message_anchor_base(context, sent_message_id)+ target_session_key = strategy.get("session_key") or self._get_session_key(context)+ clear_source = bool(strategy.get("clear_source", False))self.alias_session_base(context,source_base_session_id=source_base_session_id,alias_base_session_id=alias_base_session_id,- clear_source=True,+ target_session_key=target_session_key,+ clear_source=clear_source,)- platform = self._get_context_platform(context)- if platform in {"slack", "lark"}:- self.sessions.mark_thread_active("scheduled", context.channel_id, sent_message_id)+ if mode == "sent_message" and sent_message_id:+ platform = self._get_context_platform(context)+ if platform in {"slack", "lark"}:+ delivery_channel_id = payload.get("delivery_override", {}).get("channel_id") or context.channel_id+ self.sessions.mark_thread_active("scheduled", delivery_channel_id, sent_message_id)def _supports_threaded_session(self, context: MessageContext, *, is_dm: bool) -> bool:getter = getattr(self.controller, "get_im_client_for_context", None)diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 7a9c47996..100096781 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -40,6 +40,19 @@ class ConsolidatedMessageDispatcher:return self.controller.im_clientdef _get_target_context(self, context: MessageContext) -> MessageContext:+ payload = dict(context.platform_specific or {})+ delivery_override = payload.get("delivery_override")+ if isinstance(delivery_override, dict):+ next_payload = dict(payload)+ next_payload["is_dm"] = delivery_override.get("is_dm", next_payload.get("is_dm", False))+ return MessageContext(+ user_id=str(delivery_override.get("user_id") or context.user_id),+ channel_id=str(delivery_override.get("channel_id") or context.channel_id),+ platform=delivery_override.get("platform") or context.platform,+ thread_id=delivery_override.get("thread_id"),+ message_id=context.message_id,+ platform_specific=next_payload,+ )if self._get_im_client(context).should_use_thread_for_reply() and context.thread_id:return MessageContext(user_id=context.user_id,diff --git a/core/reply_enhancer.py b/core/reply_enhancer.pyindex af58dc1fb..0dc86f6de 100644--- a/core/reply_enhancer.py+++ b/core/reply_enhancer.py@@ -200,6 +200,7 @@ Current conversation targeting:Rules:- The default session key intentionally does not include a thread ID.- Only append `::thread::<thread_id>` to `--session-key` when the user explicitly wants replies to stay in the current thread.+- Use `--post-to channel` when the task or hook should keep thread context but publish to the parent channel.- Use `--cron "<expr>"` for recurring tasks or `--at "<ISO-8601>"` for one-off stored tasks.- If `--timezone` is omitted, the task uses the local system timezone at creation time.- Use `--prompt "..."` or `--prompt-file <path>` for task and hook content.diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 2e034591b..f904ba2cb 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -100,6 +100,8 @@ class ScheduledTask:session_key: strprompt: strschedule_type: str+ post_to: Optional[str] = None+ deliver_key: Optional[str] = Nonecron: Optional[str] = Nonerun_at: Optional[str] = Nonetimezone: str = "UTC"@@ -119,6 +121,8 @@ class ScheduledTask:session_key=str(payload.get("session_key") or ""),prompt=str(payload.get("prompt") or ""),schedule_type=str(payload.get("schedule_type") or ""),+ post_to=payload.get("post_to"),+ deliver_key=payload.get("deliver_key"),cron=payload.get("cron"),run_at=payload.get("run_at"),timezone=str(payload.get("timezone") or "UTC"),@@ -137,6 +141,8 @@ class TaskExecutionRequest:created_at: str = field(default_factory=_utc_now_iso)task_id: Optional[str] = Nonesession_key: Optional[str] = None+ post_to: Optional[str] = None+ deliver_key: Optional[str] = Noneprompt: Optional[str] = Nonedef to_dict(self) -> Dict[str, Any]:@@ -150,6 +156,8 @@ class TaskExecutionRequest:created_at=str(payload.get("created_at") or _utc_now_iso()),task_id=payload.get("task_id"),session_key=payload.get("session_key"),+ post_to=payload.get("post_to"),+ deliver_key=payload.get("deliver_key"),prompt=payload.get("prompt"),)@@ -233,6 +241,8 @@ class ScheduledTaskStore:session_key: str,prompt: str,schedule_type: str,+ post_to: Optional[str] = None,+ deliver_key: Optional[str] = None,cron: Optional[str] = None,run_at: Optional[str] = None,timezone_name: str,@@ -242,6 +252,8 @@ class ScheduledTaskStore:session_key=session_key,prompt=prompt,schedule_type=schedule_type,+ post_to=post_to,+ deliver_key=deliver_key,cron=cron,run_at=run_at,timezone=timezone_name,@@ -328,12 +340,21 @@ class TaskExecutionStore:def enqueue_task_run(self, task_id: str) -> TaskExecutionRequest:return self.enqueue(TaskExecutionRequest(id=uuid4().hex[:12], request_type="task_run", task_id=task_id))- def enqueue_hook_send(self, *, session_key: str, prompt: str) -> TaskExecutionRequest:+ def enqueue_hook_send(+ self,+ *,+ session_key: str,+ prompt: str,+ post_to: Optional[str] = None,+ deliver_key: Optional[str] = None,+ ) -> TaskExecutionRequest:return self.enqueue(TaskExecutionRequest(id=uuid4().hex[:12],request_type="hook_send",session_key=session_key,+ post_to=post_to,+ deliver_key=deliver_key,prompt=prompt,))@@ -547,6 +568,8 @@ class ScheduledTaskService:raise ValueError("hook request requires both session_key and prompt")error = await self._execute_request(session_key=request.session_key,+ post_to=request.post_to,+ deliver_key=request.deliver_key,prompt=request.prompt,execution_id=request.id,trigger_kind="hook",@@ -581,6 +604,8 @@ class ScheduledTaskService:try:error = await self._execute_request(session_key=task.session_key,+ post_to=task.post_to,+ deliver_key=task.deliver_key,prompt=task.prompt,execution_id=execution_id,task_id=task.id,@@ -601,14 +626,22 @@ class ScheduledTaskService:self,*,session_key: str,+ post_to: Optional[str],+ deliver_key: Optional[str],prompt: str,execution_id: str,task_id: Optional[str] = None,trigger_kind: str,) -> Optional[str]:target = parse_session_key(session_key)+ delivery_target = self._resolve_delivery_target(+ session_target=target,+ post_to=post_to,+ deliver_key=deliver_key,+ )context = await self._build_context(target,+ delivery_target=delivery_target,execution_id=execution_id,task_id=task_id,trigger_kind=trigger_kind,@@ -623,30 +656,26 @@ class ScheduledTaskService:self,target: ParsedSessionKey,*,+ delivery_target: Optional[ParsedSessionKey] = None,execution_id: str,task_id: Optional[str] = None,trigger_kind: str = "scheduled",) -> MessageContext:platform = target.platformself.validate_platform(platform)- settings_manager = self.controller.platform_settings_managers[platform]-- channel_id = target.scope_id- user_id = "scheduled"- if target.is_dm:- user_id = target.scope_id- bound_user = settings_manager.get_store().get_user(target.scope_id, platform=platform)- if platform == "lark":- dm_chat_id = getattr(bound_user, "dm_chat_id", "") if bound_user else ""- if not dm_chat_id:- raise ValueError(f"lark user {target.scope_id} is missing dm_chat_id binding")- channel_id = dm_chat_id- elif bound_user and getattr(bound_user, "dm_chat_id", ""):- channel_id = bound_user.dm_chat_id+ delivery_target = delivery_target or target+ session_target_context = self._resolve_target_context(target)+ delivery_target_context = self._resolve_target_context(delivery_target)+ delivery_strategy = self._build_delivery_alias_strategy(+ session_target=target,+ delivery_target=delivery_target,+ session_context=session_target_context,+ delivery_context=delivery_target_context,+ )return MessageContext(- user_id=user_id,- channel_id=channel_id,+ user_id=session_target_context["user_id"],+ channel_id=session_target_context["channel_id"],platform=platform,thread_id=target.thread_id,message_id=self._build_message_id(@@ -659,11 +688,128 @@ class ScheduledTaskService:"is_dm": target.is_dm,"turn_source": "scheduled","session_key_external": target.to_key(),+ "delivery_key_external": delivery_target.to_key(),+ "delivery_scope_session_key": delivery_target.session_scope,+ "delivery_override": {+ "user_id": delivery_target_context["user_id"],+ "channel_id": delivery_target_context["channel_id"],+ "thread_id": delivery_target.thread_id,+ "platform": platform,+ "is_dm": delivery_target.is_dm,+ },+ "scheduled_delivery_alias": delivery_strategy,"task_execution_id": execution_id,"task_trigger_kind": trigger_kind,},)+ def _resolve_target_context(self, target: ParsedSessionKey) -> Dict[str, Any]:+ platform = target.platform+ settings_manager = self.controller.platform_settings_managers[platform]++ channel_id = target.scope_id+ user_id = "scheduled"+ if target.is_dm:+ user_id = target.scope_id+ bound_user = settings_manager.get_store().get_user(target.scope_id, platform=platform)+ if platform == "lark":+ dm_chat_id = getattr(bound_user, "dm_chat_id", "") if bound_user else ""+ if not dm_chat_id:+ raise ValueError(f"lark user {target.scope_id} is missing dm_chat_id binding")+ channel_id = dm_chat_id+ elif bound_user and getattr(bound_user, "dm_chat_id", ""):+ channel_id = bound_user.dm_chat_id++ return {+ "user_id": user_id,+ "channel_id": channel_id,+ }++ def _resolve_delivery_target(+ self,+ *,+ session_target: ParsedSessionKey,+ post_to: Optional[str],+ deliver_key: Optional[str],+ ) -> ParsedSessionKey:+ if deliver_key:+ delivery_target = parse_session_key(deliver_key)+ if delivery_target.platform != session_target.platform:+ raise ValueError("--deliver-key must stay on the same platform as --session-key")+ return delivery_target+ if post_to == "channel":+ return ParsedSessionKey(+ platform=session_target.platform,+ scope_type=session_target.scope_type,+ scope_id=session_target.scope_id,+ thread_id=None,+ )+ if post_to == "thread":+ if not session_target.thread_id:+ raise ValueError("--post-to thread requires a thread-bound --session-key or an explicit --deliver-key")+ return session_target+ return session_target++ def _supports_threaded_delivery(self, target: ParsedSessionKey) -> bool:+ getter = getattr(self.controller, "get_im_client_for_context", None)+ context = MessageContext(+ user_id=target.scope_id if target.is_dm else "scheduled",+ channel_id=target.scope_id,+ platform=target.platform,+ platform_specific={"platform": target.platform, "is_dm": target.is_dm},+ )+ if callable(getter):+ im_client = getter(context)+ else:+ im_client = getattr(self.controller, "im_client", None)+ if im_client is None:+ return False+ if target.is_dm:+ return bool(getattr(im_client, "should_use_thread_for_dm_session", lambda: False)())+ return bool(getattr(im_client, "should_use_thread_for_reply", lambda: False)())++ def _build_delivery_alias_strategy(+ self,+ *,+ session_target: ParsedSessionKey,+ delivery_target: ParsedSessionKey,+ session_context: Dict[str, Any],+ delivery_context: Dict[str, Any],+ ) -> Dict[str, Any]:+ source_session_key = session_target.session_scope+ target_session_key = delivery_target.session_scope+ same_scope = source_session_key == target_session_key++ if delivery_target.thread_id:+ alias_base = f"{delivery_target.platform}_{delivery_target.thread_id}"+ if same_scope and alias_base == f"{session_target.platform}_{session_target.thread_id}":+ return {"mode": "none"}+ return {+ "mode": "fixed_base",+ "session_key": target_session_key,+ "base_session_id": alias_base,+ "clear_source": False,+ }++ if self._supports_threaded_delivery(delivery_target):+ clear_source = same_scope and session_target.thread_id is None+ return {+ "mode": "sent_message",+ "session_key": target_session_key,+ "clear_source": clear_source,+ }++ delivery_base_id = delivery_context["channel_id"]+ source_base_id = session_context["channel_id"]+ if same_scope and session_target.thread_id is None and delivery_base_id == source_base_id:+ return {"mode": "none"}+ return {+ "mode": "fixed_base",+ "session_key": target_session_key,+ "base_session_id": f"{delivery_target.platform}_{delivery_base_id}",+ "clear_source": False,+ }+@staticmethoddef _build_message_id(*, execution_id: str, task_id: Optional[str], trigger_kind: str) -> str:if trigger_kind == "hook":diff --git a/docs/plans/task-delivery-key.md b/docs/plans/task-delivery-key.mdnew file mode 100644index 000000000..8d0ba581c--- /dev/null+++ b/docs/plans/task-delivery-key.md@@ -0,0 +1,41 @@+# Task Delivery Target Split++## Background++`vibe task add` and `vibe hook send` currently use one `session_key` for both:++- session continuity+- outbound delivery target++That breaks cases where the agent should keep a thread-backed session for memory, but publish each result to the parent channel.++## Goal++Keep command usage simple while allowing delivery to be decoupled from session reuse:++- keep `--session-key` as the memory/session target+- add `--post-to thread|channel` for the common delivery choice+- add `--deliver-key <session-key>` for advanced delivery overrides++`--deliver-key` should be documented in CLI help and skill docs, but not in injected prompt guidance.++## Solution++1. Extend stored task/request payloads with delivery fields.+2. Resolve two targets at runtime:+ - session target from `session_key`+ - delivery target from `deliver_key` or `post_to`+3. Preserve the original thread-backed base session when running the turn.+4. Apply delivery override only in dispatcher send contexts.+5. When a scheduled result is delivered as a top-level message, alias that sent message back to the same native session so follow-up replies continue the session.++## Todo++- Add `post_to` / `deliver_key` to task models, queue requests, CLI, and JSON output.+- Implement delivery override context building in `ScheduledTaskService`.+- Update dispatcher/session finalization to use delivery override without breaking session reuse.+- Add focused tests for:+ - CLI parsing and persistence+ - delivery override context building+ - scheduled finalization alias behavior for top-level deliveries+- Update help text and skill docs.diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex cccfc9d39..8d89ca51b 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -142,6 +142,50 @@ class SessionsFacade:self.sessions_store.save()return changed+ def alias_session_base_across_scopes(+ self,+ source_user_id: Union[int, str],+ target_user_id: Union[int, str],+ source_base_session_id: str,+ alias_base_session_id: str,+ ) -> bool:+ source_key = self._normalize_user_id(source_user_id)+ target_key = self._normalize_user_id(target_user_id)+ self.sessions_store._ensure_user_namespace(source_key)+ self.sessions_store._ensure_user_namespace(target_key)++ source_agent_maps = self.sessions_store.state.session_mappings.get(source_key, {})+ target_agent_maps = self.sessions_store.state.session_mappings.get(target_key, {})+ changed = False++ for agent_name, source_agent_map in source_agent_maps.items():+ target_agent_map = self.sessions_store.get_agent_map(target_key, agent_name)+ additions: Dict[str, str] = {}+ for mapping_key, native_session_id in list(source_agent_map.items()):+ if not self._matches_base_prefix(mapping_key, source_base_session_id):+ continue+ suffix = mapping_key[len(source_base_session_id) :]+ alias_key = f"{alias_base_session_id}{suffix}"+ if alias_key in target_agent_map or alias_key in additions:+ continue+ additions[alias_key] = native_session_id+ if additions:+ target_agent_map.update(additions)+ changed = True+ logger.info(+ "Aliased %s session base across scopes: %s/%s -> %s/%s (%s keys)",+ agent_name,+ source_key,+ source_base_session_id,+ target_key,+ alias_base_session_id,+ len(additions),+ )++ if changed:+ self.sessions_store.save()+ return changed+def clear_session_base(self, user_id: Union[int, str], base_session_id: str) -> int:user_key = self._normalize_user_id(user_id)self.sessions_store._ensure_user_namespace(user_key)diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.mdindex 97236120c..bf3a2ec52 100644--- a/skills/use-vibe-remote/SKILL.md+++ b/skills/use-vibe-remote/SKILL.md@@ -248,6 +248,8 @@ Each task includes:- `id`- `session_key`+- `post_to`+- `deliver_key`- `prompt`- `schedule_type`- `cron` or `run_at`@@ -311,6 +313,12 @@ Preferred CLI shape:- immediate rerun: `vibe task run <id>`- one-shot async hook: `vibe hook send --session-key '<key>' --prompt '...'`+Delivery controls:++- use `--post-to channel` when the task should keep session context from a thread-bound `session_key` but publish to the parent channel+- use `--deliver-key '<key>'` only when delivery must go to a different explicit target than `session_key`+- do not combine `--post-to` and `--deliver-key` in the same command+Session key format:- channel scope: `<platform>::channel::<channel_id>`diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.pyindex d48cf85b5..17bb72189 100644--- a/tests/test_cli_task_command.py+++ b/tests/test_cli_task_command.py@@ -116,6 +116,8 @@ def test_task_add_help_includes_examples_and_threadless_guidance(capsys) -> Noneassert exc.value.code == 0captured = capsys.readouterr()assert "Prefer a threadless session key by default." in captured.out+ assert "--post-to" in captured.out+ assert "--deliver-key" in captured.outassert "<platform>::channel::<channel_id>" in captured.outassert "vibe task add --session-key 'slack::channel::C123'" in captured.out@@ -141,6 +143,8 @@ def test_hook_send_help_includes_examples_and_threadless_guidance(capsys) -> Nonassert exc.value.code == 0captured = capsys.readouterr()assert "`vibe hook send` queues one asynchronous turn" in captured.out+ assert "--post-to" in captured.out+ assert "--deliver-key" in captured.outassert "<platform>::channel::<channel_id>" in captured.outassert "vibe hook send --session-key 'slack::channel::C123'" in captured.out@@ -191,6 +195,80 @@ def test_task_add_rejects_invalid_session_key_with_hint() -> None:assert payload["example"] == "slack::channel::C123"+def test_task_add_rejects_conflicting_delivery_target_flags(capsys) -> None:+ parser = cli.build_parser()++ with pytest.raises(SystemExit) as exc:+ parser.parse_args(+ [+ "task",+ "add",+ "--session-key",+ "slack::channel::C123",+ "--post-to",+ "channel",+ "--deliver-key",+ "slack::channel::C999",+ "--cron",+ "0 * * * *",+ "--prompt",+ "hello",+ ]+ )++ assert exc.value.code == 2+ payload = json.loads(capsys.readouterr().err)+ assert payload["code"] == "invalid_arguments"+ assert "not allowed with argument --post-to" in payload["error"]+ assert payload["help_command"] == "vibe task add --help"+++def test_task_add_rejects_post_to_thread_without_thread_session_key() -> None:+ args = _parse_task_add(+ [+ "--session-key",+ "slack::channel::C123",+ "--post-to",+ "thread",+ "--cron",+ "0 * * * *",+ "--prompt",+ "hello",+ ]+ )++ with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):+ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "invalid_delivery_target"+++def test_task_add_rejects_cross_platform_deliver_key() -> None:+ args = _parse_task_add(+ [+ "--session-key",+ "slack::channel::C123",+ "--deliver-key",+ "discord::channel::C999",+ "--cron",+ "0 * * * *",+ "--prompt",+ "hello",+ ]+ )++ with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack", "discord"})):+ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "invalid_delivery_target"+ assert payload["details"] == {+ "session_platform": "slack",+ "delivery_platform": "discord",+ }++def test_task_add_rejects_invalid_cron_with_example() -> None:args = _parse_task_add([@@ -340,8 +418,66 @@ def test_hook_send_rejects_invalid_session_key_with_hint() -> None:assert payload["help_command"] == "vibe hook send --help"+def test_hook_send_rejects_conflicting_delivery_target_flags(capsys) -> None:+ parser = cli.build_parser()++ with pytest.raises(SystemExit) as exc:+ parser.parse_args(+ [+ "hook",+ "send",+ "--session-key",+ "slack::channel::C123",+ "--post-to",+ "channel",+ "--deliver-key",+ "slack::channel::C999",+ "--prompt",+ "hello",+ ]+ )++ assert exc.value.code == 2+ payload = json.loads(capsys.readouterr().err)+ assert payload["code"] == "invalid_arguments"+ assert "not allowed with argument --post-to" in payload["error"]+ assert payload["help_command"] == "vibe hook send --help"+++def test_hook_send_rejects_cross_platform_deliver_key() -> None:+ args = _parse_hook_send(+ [+ "--session-key",+ "slack::channel::C123",+ "--deliver-key",+ "discord::channel::C999",+ "--prompt",+ "hello",+ ]+ )++ with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack", "discord"})):+ result, payload = _capture_stderr_json(cli.cmd_hook_send, args)++ assert result == 1+ assert payload["code"] == "invalid_delivery_target"+ assert payload["details"] == {+ "session_platform": "slack",+ "delivery_platform": "discord",+ }++def test_hook_send_enqueues_request(tmp_path: Path, capsys) -> None:- args = _parse_hook_send(["--session-key", "slack::channel::C123", "--prompt", "hello"])+ args = _parse_hook_send(+ [+ "--session-key",+ "slack::channel::C123::thread::171717.123",+ "--post-to",+ "channel",+ "--prompt",+ "hello",+ ]+ )request_root = tmp_path / "task_requests"with (@@ -353,7 +489,8 @@ def test_hook_send_enqueues_request(tmp_path: Path, capsys) -> None:assert result == 0payload = json.loads(capsys.readouterr().out)assert payload["ok"] is True- assert payload["session_key"] == "slack::channel::C123"+ assert payload["session_key"] == "slack::channel::C123::thread::171717.123"+ assert payload["post_to"] == "channel"assert (request_root / "pending" / f"{payload['execution_id']}.json").exists()diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pyindex ea980b326..c66de626e 100644--- a/tests/test_message_dispatcher_scheduled.py+++ b/tests/test_message_dispatcher_scheduled.py@@ -11,10 +11,14 @@ from modules.im import MessageContextclass _StubIMClient:+ def __init__(self):+ self.sent = []+def should_use_thread_for_reply(self):return Falseasync def send_message(self, context, text, parse_mode=None, reply_to=None):+ self.sent.append((context.channel_id, context.thread_id, text))return "bot-msg-1"async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):@@ -34,13 +38,14 @@ class _StubSessionHandler:self.calls = []def finalize_scheduled_delivery(self, context, sent_message_id):- self.calls.append((context.channel_id, sent_message_id))+ self.calls.append((context.channel_id, context.thread_id, sent_message_id))class _StubController:def __init__(self):self.config = type("Config", (), {"platform": "slack", "reply_enhancements": False})()self.session_handler = _StubSessionHandler()+ self.im_client = _StubIMClient()def _get_settings_key(self, context):return context.channel_id@@ -52,7 +57,7 @@ class _StubController:return _StubSettingsManager()def get_im_client_for_context(self, context):- return _StubIMClient()+ return self.im_clientclass MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):@@ -73,4 +78,37 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):message_id = await dispatcher.emit_agent_message(context, "result", "hello")self.assertEqual(message_id, "bot-msg-1")- self.assertEqual(controller.session_handler.calls, [("C123", "bot-msg-1")])+ self.assertEqual(controller.im_client.sent, [("C123", None, "hello")])+ self.assertEqual(controller.session_handler.calls, [("C123", None, "bot-msg-1")])++ async def test_delivery_override_sends_result_to_parent_channel(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ thread_id="171717.123",+ platform="slack",+ platform_specific={+ "turn_source": "scheduled",+ "turn_base_session_id": "slack_171717.123",+ "delivery_override": {+ "user_id": "scheduled",+ "channel_id": "C123",+ "thread_id": None,+ "platform": "slack",+ "is_dm": False,+ },+ "scheduled_delivery_alias": {+ "mode": "sent_message",+ "session_key": "slack::C123",+ "clear_source": False,+ },+ },+ )++ message_id = await dispatcher.emit_agent_message(context, "result", "hello")++ self.assertEqual(message_id, "bot-msg-1")+ self.assertEqual(controller.im_client.sent, [("C123", None, "hello")])+ self.assertEqual(controller.session_handler.calls, [("C123", "171717.123", "bot-msg-1")])diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.pyindex 705d3b9b7..c8a401f61 100644--- a/tests/test_reply_enhancer_platform.py+++ b/tests/test_reply_enhancer_platform.py@@ -95,6 +95,10 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertIn("Use `vibe task add` for actions that should recur or remain saved.", prompt)self.assertIn("Default session key: `slack::channel::C1`", prompt)self.assertIn("Current thread ID: `171717.123`", prompt)+ self.assertIn(+ "Use `--post-to channel` when the task or hook should keep thread context but publish to the parent channel.",+ prompt,+ )self.assertIn("If `--timezone` is omitted, the task uses the local system timezone at creation time.", prompt)self.assertIn("Run `vibe task add --help` or `vibe hook send --help` for the full command reference.", prompt)self.assertIn("A shared user context and preferences file is available at ", prompt)diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 3e0a39f7e..438803b3c 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -94,6 +94,8 @@ def test_store_round_trip_persists_task(tmp_path: Path) -> None:store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")task = store.add_task(session_key="discord::channel::123",+ post_to="channel",+ deliver_key="discord::channel::456",prompt="send digest",schedule_type="cron",cron="0 * * * *",@@ -106,6 +108,8 @@ def test_store_round_trip_persists_task(tmp_path: Path) -> None:assert payload["tasks"][0]["id"] == task.idassert reloaded.get_task(task.id) is not Noneassert reloaded.get_task(task.id).session_key == "discord::channel::123"+ assert reloaded.get_task(task.id).post_to == "channel"+ assert reloaded.get_task(task.id).deliver_key == "discord::channel::456"def test_store_reload_detects_deleted_task_file(tmp_path: Path) -> None:@@ -159,7 +163,13 @@ def test_service_rejects_unsupported_platform_at_runtime() -> None:def test_build_context_assigns_unique_scheduled_message_ids() -> None:settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))- controller = SimpleNamespace(platform_settings_managers={"slack": settings_manager})+ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ )service = ScheduledTaskService(controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json")))target = parse_session_key("slack::channel::C123")@@ -173,7 +183,13 @@ def test_build_context_assigns_unique_scheduled_message_ids() -> None:def test_build_context_assigns_hook_message_id() -> None:settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))- controller = SimpleNamespace(platform_settings_managers={"slack": settings_manager})+ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ )service = ScheduledTaskService(controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json")))target = parse_session_key("slack::channel::C123")@@ -183,6 +199,35 @@ def test_build_context_assigns_hook_message_id() -> None:assert context.platform_specific["task_trigger_kind"] == "hook"+def test_build_context_separates_delivery_target_from_session_target() -> None:+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))+ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ )+ service = ScheduledTaskService(controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json")))+ session_target = parse_session_key("slack::channel::C123::thread::171717.123")+ delivery_target = parse_session_key("slack::channel::C123")++ context = asyncio.run(+ service._build_context(+ session_target,+ delivery_target=delivery_target,+ execution_id="exec-1",+ task_id="task-1",+ )+ )++ assert context.thread_id == "171717.123"+ assert context.platform_specific["delivery_override"]["thread_id"] is None+ assert context.platform_specific["delivery_scope_session_key"] == "slack::C123"+ assert context.platform_specific["scheduled_delivery_alias"]["mode"] == "sent_message"+ assert context.platform_specific["scheduled_delivery_alias"]["clear_source"] is False++def test_run_task_records_scheduled_handler_error(tmp_path: Path) -> None:path = tmp_path / "scheduled_tasks.json"store = ScheduledTaskStore(path)@@ -358,7 +403,11 @@ def test_drain_requests_requeues_cancelled_task_run(tmp_path: Path) -> None:def test_drain_requests_executes_hook_send(tmp_path: Path) -> None:request_store = TaskExecutionStore(tmp_path / "task_requests")- request = request_store.enqueue_hook_send(session_key="slack::channel::C123", prompt="ship it")+ request = request_store.enqueue_hook_send(+ session_key="slack::channel::C123::thread::171717.123",+ post_to="channel",+ prompt="ship it",+ )settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))calls = []@@ -381,8 +430,10 @@ def test_drain_requests_executes_hook_send(tmp_path: Path) -> None:assert len(calls) == 1context, message, parsed = calls[0]assert message == "ship it"- assert parsed.to_key() == "slack::channel::C123"+ assert parsed.to_key() == "slack::channel::C123::thread::171717.123"assert context.message_id == f"hook:{request.id}"+ assert context.thread_id == "171717.123"+ assert context.platform_specific["delivery_override"]["thread_id"] is Nonepayload = json.loads((request_store.completed_dir / f"{request.id}.json").read_text(encoding="utf-8"))assert payload["ok"] is Truediff --git a/tests/test_session_handler_base_id.py b/tests/test_session_handler_base_id.pyindex b33321d6b..256678497 100644--- a/tests/test_session_handler_base_id.py+++ b/tests/test_session_handler_base_id.py@@ -18,6 +18,7 @@ class _Config:class _FakeSessions:def __init__(self) -> None:self.alias_calls = []+ self.cross_scope_alias_calls = []self.clear_calls = []self.thread_marks = []@@ -29,6 +30,18 @@ class _FakeSessions:self.clear_calls.append((user_id, base_session_id))return 1+ def alias_session_base_across_scopes(+ self,+ source_user_id,+ target_user_id,+ source_base_session_id,+ alias_base_session_id,+ ):+ self.cross_scope_alias_calls.append(+ (source_user_id, target_user_id, source_base_session_id, alias_base_session_id)+ )+ return True+def mark_thread_active(self, user_id, channel_id, thread_ts):self.thread_marks.append((user_id, channel_id, thread_ts))@@ -169,7 +182,12 @@ def test_finalize_scheduled_delivery_aliases_provisional_base_and_marks_thread()"is_dm": False,"turn_source": "scheduled","turn_base_session_id": "slack_scheduled-abc",- "scheduled_anchor_required": True,+ "delivery_override": {"channel_id": "C123"},+ "scheduled_delivery_alias": {+ "mode": "sent_message",+ "session_key": "slack::C123",+ "clear_source": True,+ },},)@@ -178,3 +196,34 @@ def test_finalize_scheduled_delivery_aliases_provisional_base_and_marks_thread()assert controller.sessions.alias_calls == [("slack::C123", "slack_scheduled-abc", "slack_171717.123")]assert controller.sessions.clear_calls == [("slack::C123", "slack_scheduled-abc")]assert controller.sessions.thread_marks == [("scheduled", "C123", "171717.123")]+++def test_finalize_scheduled_delivery_can_alias_into_delivery_scope() -> None:+ controller = _Controller(platform="slack", dm_threads=False)+ handler = SessionHandler(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ thread_id="171717.123",+ platform_specific={+ "is_dm": False,+ "turn_source": "scheduled",+ "turn_base_session_id": "slack_171717.123",+ "scheduled_delivery_alias": {+ "mode": "sent_message",+ "session_key": "slack::C999",+ "clear_source": False,+ },+ "delivery_override": {"channel_id": "C999"},+ },+ )++ handler.finalize_scheduled_delivery(context, "181818.456")++ assert controller.sessions.alias_calls == []+ assert controller.sessions.cross_scope_alias_calls == [+ ("slack::C123", "slack::C999", "slack_171717.123", "slack_181818.456")+ ]+ assert controller.sessions.clear_calls == []+ assert controller.sessions.thread_marks == [("scheduled", "C999", "181818.456")]diff --git a/vibe/cli.py b/vibe/cli.pyindex d490281ae..aa5ee1ac9 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -10,6 +10,7 @@ import timefrom datetime import datetimefrom pathlib import Pathfrom textwrap import dedent+from typing import Optionalfrom zoneinfo import ZoneInfofrom apscheduler.triggers.cron import CronTrigger@@ -104,6 +105,7 @@ def _task_examples_text() -> str:vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *' --prompt 'Share the hourly summary.'vibe task run 12ab34cd56efvibe task add --session-key 'discord::user::123456789' --at '2026-03-31T09:00:00+08:00' --prompt-file briefing.md+ vibe task add --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --cron '*/5 * * * *' --prompt 'Tell a new joke each time.'vibe task add --session-key 'lark::channel::oc_abc::thread::om_123' --cron '30 9 * * 1-5' --prompt 'Post the daily standup reminder in this thread.'""")@@ -121,11 +123,15 @@ def _task_add_examples_text() -> str:Guidance:Prefer a threadless session key by default.Only append ::thread::<thread_id> when the task must continue inside a specific thread.+ Use --post-to channel when the task should keep thread context but publish to the parent channel.+ Use --deliver-key only when delivery must go to a different explicit target.Use --cron for recurring jobs and --at for one-shot jobs.--timezone controls how --cron and naive --at timestamps are interpreted.Examples:vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *' --prompt 'Share the hourly summary.'+ vibe task add --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --cron '*/5 * * * *' --prompt 'Tell a new joke each time.'+ vibe task add --session-key 'slack::channel::C123::thread::171717.123' --deliver-key 'slack::channel::C999' --cron '0 9 * * *' --prompt 'Post the daily summary in the announcements channel.'vibe task add --session-key 'discord::user::123456789' --at '2026-03-31T09:00:00+08:00' --prompt 'Send the release reminder.'vibe task add --session-key 'lark::channel::oc_abc::thread::om_123' --cron '30 9 * * 1-5' --timezone 'Asia/Shanghai' --prompt-file standup.txt"""@@ -145,9 +151,13 @@ def _hook_send_examples_text() -> str:`vibe hook send` queues one asynchronous turn without persisting a scheduled task.Prefer a threadless session key by default.Only append ::thread::<thread_id> when the hook must continue in one specific thread.+ Use --post-to channel when the hook should keep thread context but publish to the parent channel.+ Use --deliver-key only when delivery must go to a different explicit target.Examples:vibe hook send --session-key 'slack::channel::C123' --prompt 'The export finished. Share the summary.'+ vibe hook send --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --prompt 'Share the benchmark result in the channel.'+ vibe hook send --session-key 'slack::channel::C123' --deliver-key 'slack::channel::C999' --prompt 'Post the deployment summary in announcements.'vibe hook send --session-key 'discord::user::123456789' --prompt-file release-note.txtvibe hook send --session-key 'lark::channel::oc_abc::thread::om_123' --prompt 'Post the benchmark result in this thread.'"""@@ -419,9 +429,55 @@ def _parse_validated_session_key(return parsed+def _validate_delivery_args(+ *,+ session_key: str,+ post_to: Optional[str],+ deliver_key: Optional[str],+ help_command: str,+):+ if post_to and deliver_key:+ raise TaskCliError(+ "use either --post-to or --deliver-key, not both",+ code="conflicting_delivery_target",+ hint="Use --post-to for the common thread/channel delivery choice, or --deliver-key for an explicit delivery target.",+ help_command=help_command,+ )++ session_target = _parse_validated_session_key(session_key, help_command=help_command)+ delivery_target = None+ if deliver_key:+ delivery_target = _parse_validated_session_key(deliver_key, help_command=help_command)+ if delivery_target.platform != session_target.platform:+ raise TaskCliError(+ "--deliver-key must use the same platform as --session-key",+ code="invalid_delivery_target",+ hint="Keep session memory and delivery on the same IM platform. Change only the channel, user, or thread target.",+ help_command=help_command,+ details={+ "session_platform": session_target.platform,+ "delivery_platform": delivery_target.platform,+ },+ )+ elif post_to == "thread" and not session_target.thread_id:+ raise TaskCliError(+ "--post-to thread requires a thread-bound --session-key or an explicit --deliver-key",+ code="invalid_delivery_target",+ hint="Append ::thread::<thread_id> to --session-key, or use --deliver-key with a thread target.",+ help_command=help_command,+ details={"session_key": session_key, "post_to": post_to},+ )+ return session_target, delivery_target++def cmd_task_add(args):try:- _parse_validated_session_key(args.session_key, help_command="vibe task add --help")+ _validate_delivery_args(+ session_key=args.session_key,+ post_to=getattr(args, "post_to", None),+ deliver_key=getattr(args, "deliver_key", None),+ help_command="vibe task add --help",+ )prompt = _resolve_prompt_input(args,help_command="vibe task add --help",@@ -455,6 +511,8 @@ def cmd_task_add(args):) from exctask = store.add_task(session_key=args.session_key,+ post_to=args.post_to,+ deliver_key=args.deliver_key,prompt=prompt,schedule_type="cron",cron=args.cron,@@ -474,6 +532,8 @@ def cmd_task_add(args):) from exctask = store.add_task(session_key=args.session_key,+ post_to=args.post_to,+ deliver_key=args.deliver_key,prompt=prompt,schedule_type="at",run_at=run_at,@@ -583,13 +643,23 @@ def cmd_task_run(task_id: str):def cmd_hook_send(args):try:- _parse_validated_session_key(args.session_key, help_command="vibe hook send --help")+ _validate_delivery_args(+ session_key=args.session_key,+ post_to=getattr(args, "post_to", None),+ deliver_key=getattr(args, "deliver_key", None),+ help_command="vibe hook send --help",+ )prompt = _resolve_prompt_input(args,help_command="vibe hook send --help",example_command="vibe hook send --session-key 'slack::channel::C123'",)- request = _task_request_store().enqueue_hook_send(session_key=args.session_key, prompt=prompt)+ request = _task_request_store().enqueue_hook_send(+ session_key=args.session_key,+ post_to=args.post_to,+ deliver_key=args.deliver_key,+ prompt=prompt,+ )print(json.dumps({@@ -598,6 +668,8 @@ def cmd_hook_send(args):"execution_id": request.id,"request_type": request.request_type,"session_key": args.session_key,+ "post_to": args.post_to,+ "deliver_key": args.deliver_key,},indent=2,)@@ -1157,13 +1229,23 @@ def build_parser():epilog=_task_add_examples_text(),formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe task add --help",- error_hint="Use --session-key together with exactly one schedule flag and one prompt input flag.",+ error_hint="Use --session-key together with exactly one schedule flag and one prompt input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",)task_add_parser.add_argument("--session-key",required=True,help="Target session key. Prefer a threadless key unless the task must stay in one thread.",)+ delivery_group = task_add_parser.add_mutually_exclusive_group()+ delivery_group.add_argument(+ "--post-to",+ choices=("thread", "channel"),+ help="Delivery location override. Omit to follow --session-key directly.",+ )+ delivery_group.add_argument(+ "--deliver-key",+ help="Explicit delivery target key. Use this only when messages must be delivered to a different target.",+ )schedule_group = task_add_parser.add_mutually_exclusive_group(required=True)schedule_group.add_argument("--cron", help="Recurring schedule in 5-field crontab format")schedule_group.add_argument("--at", help="One-shot timestamp in ISO 8601 format")@@ -1256,13 +1338,23 @@ def build_parser():epilog=_hook_send_examples_text(),formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe hook send --help",- error_hint="Use --session-key together with exactly one prompt input flag.",+ error_hint="Use --session-key together with exactly one prompt input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",)hook_send_parser.add_argument("--session-key",required=True,help="Target session key. Prefer a threadless key unless the hook must stay in one thread.",)+ hook_delivery_group = hook_send_parser.add_mutually_exclusive_group()+ hook_delivery_group.add_argument(+ "--post-to",+ choices=("thread", "channel"),+ help="Delivery location override. Omit to follow --session-key directly.",+ )+ hook_delivery_group.add_argument(+ "--deliver-key",+ help="Explicit delivery target key. Use this only when messages must be delivered to a different target.",+ )hook_prompt_group = hook_send_parser.add_mutually_exclusive_group(required=True)hook_prompt_group.add_argument("--prompt", help="Prompt text to send")hook_prompt_group.add_argument("--prompt-file", help="Read prompt text from a UTF-8 text file")