Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

Propagate Harness caller session context (#676)

Call Whiteb4e630db9ad1
diff --git a/core/caller_context.py b/core/caller_context.py
new file mode 100644
index 000000000..fc091ac20
--- /dev/null
+++ b/core/caller_context.py
@@ -0,0 +1,108 @@
+"""Avibe caller-context contract for Agent-initiated Harness calls."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import os
+from typing import Mapping, Optional
+
+AVIBE_SESSION_ID_ENV = "AVIBE_SESSION_ID"
+AVIBE_RUN_ID_ENV = "AVIBE_RUN_ID"
+AVIBE_CALLER_SOURCE_ENV = "AVIBE_CALLER_SOURCE"
+AVIBE_CALLER_BACKEND_ENV = "AVIBE_CALLER_BACKEND"
+AVIBE_NATIVE_SESSION_ID_ENV = "AVIBE_NATIVE_SESSION_ID"
+
+
+@dataclass(frozen=True)
+class CallerContext:
+ """Caller identity resolved from Avibe-owned execution context."""
+
+ session_id: str
+ run_id: Optional[str] = None
+ source: Optional[str] = None
+ backend: Optional[str] = None
+ native_session_id: Optional[str] = None
+
+ def to_env(self) -> dict[str, str]:
+ env = {AVIBE_SESSION_ID_ENV: self.session_id}
+ if self.run_id:
+ env[AVIBE_RUN_ID_ENV] = self.run_id
+ if self.source:
+ env[AVIBE_CALLER_SOURCE_ENV] = self.source
+ if self.backend:
+ env[AVIBE_CALLER_BACKEND_ENV] = self.backend
+ if self.native_session_id:
+ env[AVIBE_NATIVE_SESSION_ID_ENV] = self.native_session_id
+ return env
+
+ def to_metadata(self) -> dict[str, str]:
+ metadata = {"session_id": self.session_id}
+ if self.run_id:
+ metadata["run_id"] = self.run_id
+ if self.source:
+ metadata["source"] = self.source
+ if self.backend:
+ metadata["backend"] = self.backend
+ if self.native_session_id:
+ metadata["native_session_id"] = self.native_session_id
+ return metadata
+
+
+def _clean(value: object) -> str:
+ return str(value or "").strip()
+
+
+def caller_context_from_env(env: Mapping[str, str] | None = None) -> Optional[CallerContext]:
+ """Resolve caller context from process env.
+
+ The raw session id is authoritative only when Avibe injected it into an
+ Agent subprocess. If it is absent, callers should fail or require explicit
+ flags instead of guessing from native backend ids.
+ """
+
+ source = env if env is not None else os.environ
+ session_id = _clean(source.get(AVIBE_SESSION_ID_ENV))
+ if not session_id:
+ return None
+ return CallerContext(
+ session_id=session_id,
+ run_id=_clean(source.get(AVIBE_RUN_ID_ENV)) or None,
+ source=_clean(source.get(AVIBE_CALLER_SOURCE_ENV)) or None,
+ backend=_clean(source.get(AVIBE_CALLER_BACKEND_ENV)) or None,
+ native_session_id=_clean(source.get(AVIBE_NATIVE_SESSION_ID_ENV)) or None,
+ )
+
+
+def caller_context_from_platform_payload(payload: Mapping[str, object] | None) -> Optional[CallerContext]:
+ """Resolve caller context from an Avibe message/turn payload."""
+
+ if not payload:
+ return None
+ target = payload.get("agent_session_target")
+ session_id = ""
+ backend = ""
+ native_session_id = ""
+ if isinstance(target, Mapping):
+ session_id = _clean(target.get("id"))
+ backend = _clean(target.get("agent_backend") or target.get("backend"))
+ native_session_id = _clean(target.get("native_session_id"))
+ session_id = session_id or _clean(payload.get("agent_session_id"))
+ if not session_id:
+ return None
+ run_id = _clean(payload.get("task_execution_id"))
+ source_kind = _clean(payload.get("source_kind"))
+ trigger_kind = _clean(payload.get("task_trigger_kind"))
+ source = source_kind if source_kind == "callback" else trigger_kind or source_kind or "agent_turn"
+ backend = backend or _clean(payload.get("vibe_agent_backend"))
+ return CallerContext(
+ session_id=session_id,
+ run_id=run_id or None,
+ source=source or None,
+ backend=backend or None,
+ native_session_id=native_session_id or None,
+ )
+
+
+def caller_env_for_platform_payload(payload: Mapping[str, object] | None) -> dict[str, str]:
+ context = caller_context_from_platform_payload(payload)
+ return context.to_env() if context else {}
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 04634c1ac..3ee479fe4 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -30,6 +30,7 @@ from config.v2_config import (
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,
)
from core.avibe_cloud import avibe_cloud_url_available
+from core.caller_context import caller_env_for_platform_payload
from core.services.session_fork import pending_native_fork_source
from core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt
@@ -175,6 +176,15 @@ class SessionHandler(BaseHandler):
await self.cleanup_session(composite_key)
return None
+ caller_env = caller_env_for_platform_payload(getattr(context, "platform_specific", None))
+ if getattr(client, "_vibe_caller_env", {}) != caller_env:
+ logger.info(
+ "Recreating cached Claude SDK client for %s because caller context env changed",
+ composite_key,
+ )
+ await self.cleanup_session(composite_key)
+ return None
+
try:
await self._set_claude_model_if_needed(client, current_model)
except Exception as e:
@@ -197,12 +207,28 @@ class SessionHandler(BaseHandler):
composite_key: str,
base_session_id: str,
working_path: str,
+ context: MessageContext,
+ session_key: str,
native_session_id: Optional[str],
explicit_model: Optional[str],
) -> ClaudeSDKClient | None:
client = self.claude_sessions.get(composite_key)
if client is None:
return None
+ self.ensure_agent_session_id(
+ context,
+ session_key=session_key,
+ agent_name="claude",
+ session_anchor=base_session_id,
+ )
+ caller_env = caller_env_for_platform_payload(getattr(context, "platform_specific", None))
+ if getattr(client, "_vibe_caller_env", {}) != caller_env:
+ logger.info(
+ "Recreating cached Claude subagent SDK client for %s because caller context env changed",
+ composite_key,
+ )
+ await self.cleanup_session(composite_key)
+ return None
if explicit_model:
try:
await self._set_claude_model_if_needed(client, explicit_model)
@@ -662,6 +688,8 @@ class SessionHandler(BaseHandler):
composite_key=cached_key,
base_session_id=cached_base,
working_path=working_path,
+ context=context,
+ session_key=session_key,
native_session_id=cached_session_id,
explicit_model=explicit_model,
)
@@ -683,6 +711,8 @@ class SessionHandler(BaseHandler):
composite_key=composite_key,
base_session_id=base_session_id,
working_path=working_path,
+ context=context,
+ session_key=session_key,
native_session_id=stored_claude_session_id,
explicit_model=explicit_model,
)
@@ -817,6 +847,7 @@ class SessionHandler(BaseHandler):
from vibe.claude_config import build_claude_subprocess_env
claude_env = build_claude_subprocess_env(getattr(self.config, "claude", None))
+ claude_env.update(caller_env_for_platform_payload(getattr(context, "platform_specific", None)))
claude_env[AVIBE_CLAUDE_PROCESS_OWNER_ENV] = AVIBE_CLAUDE_SESSION_OWNER
if self._should_mark_claude_isolated_env():
claude_env["IS_SANDBOX"] = "1"
@@ -872,6 +903,7 @@ class SessionHandler(BaseHandler):
# Create new Claude client
client = ClaudeSDKClient(options=options)
+ setattr(client, "_vibe_caller_env", caller_env_for_platform_payload(getattr(context, "platform_specific", None)))
# Log the actual options being used
logger.info("ClaudeAgentOptions details:")
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index f873b0713..fde2a35ab 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -325,6 +325,7 @@ class ScheduledTask:
updated_at: str = field(default_factory=_utc_now_iso)
last_run_at: Optional[str] = None
last_error: Optional[str] = None
+ metadata: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@@ -350,6 +351,7 @@ class ScheduledTask:
updated_at=str(payload.get("updated_at") or _utc_now_iso()),
last_run_at=payload.get("last_run_at"),
last_error=payload.get("last_error"),
+ metadata=payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {},
)
@@ -623,6 +625,7 @@ class ScheduledTaskStore:
cron: Optional[str] = None,
run_at: Optional[str] = None,
timezone_name: str,
+ metadata: Optional[dict[str, Any]] = None,
) -> ScheduledTask:
task = ScheduledTask(
id=uuid4().hex[:12],
@@ -638,6 +641,7 @@ class ScheduledTaskStore:
cron=cron,
run_at=run_at,
timezone=timezone_name,
+ metadata=dict(metadata or {}),
)
return self.upsert_task(task)
diff --git a/core/services/sessions.py b/core/services/sessions.py
index f53d6d55f..2bdd290fa 100644
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@ -122,6 +122,7 @@ def reserve_agent_session(
model: Optional[str] = None,
reasoning_effort: Optional[str] = None,
workdir: Optional[str] = None,
+ metadata: Optional[dict] = None,
db_path: Optional[Path] = None,
) -> Optional[str]:
"""Reserve a new ``agent_sessions`` row keyed by an IM-style scope.
@@ -142,6 +143,7 @@ def reserve_agent_session(
model=model,
reasoning_effort=reasoning_effort,
workdir=workdir,
+ metadata=metadata,
)
finally:
service.close()
@@ -157,6 +159,7 @@ def reserve_private_agent_session(
model: Optional[str] = None,
reasoning_effort: Optional[str] = None,
workdir: Optional[str] = None,
+ metadata: Optional[dict] = None,
db_path: Optional[Path] = None,
) -> Optional[str]:
"""Reserve a private (no IM scope) session, e.g. when ``vibe agent run``
@@ -175,6 +178,7 @@ def reserve_private_agent_session(
model=model,
reasoning_effort=reasoning_effort,
workdir=workdir,
+ metadata=metadata,
)
finally:
service.close()
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index 07fa30ce3..c10ba8cac 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -184,7 +184,7 @@ 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 final result text should return to this caller Session as a follow-up Agent message.
+Use `vibe agent run --async ...` when one Agent delegates work to another Session and the final result text should return to this caller Session as a follow-up Agent message. Avibe injects this Session as the default async callback target. Pass `--no-callback` only when you intentionally want no automatic follow-up and will inspect the run later.
Use `vibe agent run --fork-session <source-session-id> --message ...` when work should branch from an existing Session's native backend context without mutating that source Session. Forks keep the source Session backend; `--agent`, `--model`, and `--reasoning-effort` may override the forked Session only when the backend stays the same. Do not combine `--fork-session` with `--session-id`, `--create-session`, `--deliver-key`, or `--post-to`.
diff --git a/core/watches.py b/core/watches.py
index b583065f2..a945c3f71 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -70,6 +70,7 @@ class ManagedWatch:
last_event_at: Optional[str] = None
last_error: Optional[str] = None
last_exit_code: Optional[int] = None
+ metadata: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@@ -103,6 +104,7 @@ class ManagedWatch:
last_event_at=payload.get("last_event_at"),
last_error=payload.get("last_error"),
last_exit_code=(int(payload["last_exit_code"]) if payload.get("last_exit_code") is not None else None),
+ metadata=payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {},
)
@@ -207,6 +209,7 @@ class ManagedWatchStore:
agent_name: Optional[str] = None,
session_policy: Optional[str] = None,
message: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
) -> ManagedWatch:
watch = ManagedWatch(
id=uuid4().hex[:12],
@@ -227,6 +230,7 @@ class ManagedWatchStore:
retry_delay_seconds=retry_delay_seconds,
post_to=post_to,
deliver_key=deliver_key,
+ metadata=dict(metadata or {}),
)
return self.upsert_watch(watch)
diff --git a/docs/CLI.md b/docs/CLI.md
index 871a3aee4..84bad6cf1 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -203,10 +203,10 @@ a scheduled task definition.
```bash
vibe 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 --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'
+vibe agent run --async --no-callback --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
+vibe agent run --async --no-callback --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'
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.'
+vibe agent run --async --no-callback --create-session --deliver-key slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'
```
Use `--fork-session <session-id>` when a new Agent Session should branch from
@@ -217,11 +217,15 @@ stays the same; a cross-backend fork is rejected. Do not combine
`--fork-session` with `--session-id`, `--create-session`, `--deliver-key`, or
`--post-to`.
-Use `--callback-session-id` when an async run should send its final result text
-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. Process messages such as system
-notes, tool calls, and intermediate assistant updates are not included.
+Async runs need an explicit callback policy unless the command is running inside
+an Avibe-injected Agent environment. Use `--callback-session-id` when the final
+result text should return to a caller Session as a follow-up Agent message; use
+`--no-callback` when you intentionally want to inspect the run later with
+`vibe runs show` or by listing/polling runs. Agent-initiated Harness calls
+default the callback to the current caller Session. The callback is independent
+from ordinary delivery: if the target run also posts to its IM scope, the caller
+Session still receives the result. Process messages such as system notes, tool
+calls, and intermediate assistant updates are not included.
`vibe hook send` is kept only as a deprecated compatibility entrypoint. New
automation should use `vibe agent run`.
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 4e03aa95c..528883912 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -184,10 +184,10 @@ vibe task remove <task-id>
```bash
vibe 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 --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'
+vibe agent run --async --no-callback --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
+vibe agent run --async --no-callback --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'
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.'
+vibe agent run --async --no-callback --create-session --deliver-key slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'
```
当一个新 Agent Session 需要从现有 Session 的 native backend 上下文分叉,而不是空白开始时,
@@ -197,10 +197,13 @@ vibe agent run --async --create-session --deliver-key slack::channel::C999 --age
不要把 `--fork-session` 和 `--session-id`、`--create-session`、`--deliver-key`
或 `--post-to` 混用。
-当异步 run 的最终结果文本需要回到调用方 Session 时,使用
-`--callback-session-id`。这个 callback 与普通投递相互独立:即使目标 run 已经把
-结果发到了自己的 IM scope,调用方 Session 仍然会收到结果并触发一次跟进
-Agent 消息。system、tool call、assistant 中间过程消息不会包含在 callback 里。
+异步 run 需要明确 callback 策略,除非命令运行在 Avibe 已注入 caller context
+的 Agent 环境内。当最终结果文本需要回到调用方 Session 时,使用
+`--callback-session-id`;当你有意不自动回调、后续会通过 `vibe runs show`
+或 runs 列表/轮询查看结果时,使用 `--no-callback`。Agent 内部发起的 Harness
+调用会默认把 callback 指向当前调用方 Session。这个 callback 与普通投递相互独立:
+即使目标 run 已经把结果发到了自己的 IM scope,调用方 Session 仍然会收到结果并触发一次
+跟进 Agent 消息。system、tool call、assistant 中间过程消息不会包含在 callback 里。
`vibe hook send` 仅作为 deprecated 兼容入口保留。新的自动化入口应使用
`vibe agent run`。
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index ba02ec46c..cc309d5d1 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -892,5 +892,5 @@ vibe
vibe status
vibe doctor
vibe task list --brief
-vibe agent run --async --session-id sesk8m4q2p7x --message 'Share the latest build summary.'
+vibe agent run --async --no-callback --session-id sesk8m4q2p7x --message 'Share the latest build summary.'
```
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index 66ab5aefe..e1cb9eb69 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -866,5 +866,5 @@ vibe
vibe status
vibe doctor
vibe task list --brief
-vibe agent run --async --session-id sesk8m4q2p7x --message 'Share the latest build summary.'
+vibe agent run --async --no-callback --session-id sesk8m4q2p7x --message 'Share the latest build summary.'
```
diff --git a/docs/plans/harness-caller-context.md b/docs/plans/harness-caller-context.md
new file mode 100644
index 000000000..3470a04fc
--- /dev/null
+++ b/docs/plans/harness-caller-context.md
@@ -0,0 +1,56 @@
+# Harness Caller Context
+
+## Goal
+
+Harness commands invoked from inside an Agent turn should know the Avibe
+Session/Run that triggered them without relying on prompt instructions. The
+first-class contract is a unified environment variable:
+
+- `AVIBE_SESSION_ID`: Avibe Agent Session that owns the current Agent turn.
+- `AVIBE_RUN_ID`: Avibe Agent Run that owns the current Agent turn, when the turn
+ came from Harness.
+- `AVIBE_CALLER_SOURCE`: coarse source kind for the turn, such as `agent_run`,
+ `task`, `watch`, or `callback`.
+- `AVIBE_CALLER_BACKEND`: backend that is executing the caller turn.
+- `AVIBE_NATIVE_SESSION_ID`: backend-native session/thread id for diagnostics.
+
+Explicit CLI flags still win. Environment caller context is the defaulting and
+provenance layer, not an override of user intent.
+
+## Existing Storage
+
+`agent_runs` already has the topology fields needed for the v1:
+
+- `source_kind`
+- `source_actor`
+- `parent_run_id`
+- `callback_session_id`
+- `metadata_json`
+
+So v1 should populate these consistently instead of adding a parallel topology
+table.
+
+## Backend Transports
+
+- Claude: inject through `ClaudeAgentOptions.env`.
+- Codex: inject through thread-scoped `shell_environment_policy.set` on
+ `thread/start`, `thread/resume`, and `thread/fork`.
+- OpenCode: inject through an Avibe-owned `shell.env` plugin. Until OpenCode has
+ first-class hidden per-run metadata, Avibe writes a short-lived file binding
+ keyed by OpenCode native session id. The plugin receives the native
+ `sessionID` from OpenCode and uses that binding to return
+ `AVIBE_SESSION_ID`/`AVIBE_RUN_ID` to the shell subprocess. This avoids
+ guessing from Avibe's many-to-one native session mappings.
+
+## CLI Semantics
+
+`vibe agent run --async`:
+
+- explicit `--callback-session-id` wins;
+- explicit `--no-callback` means intentional no callback and prints tracking
+ guidance;
+- otherwise, if caller context has `AVIBE_SESSION_ID`, default callback to that
+ session;
+- otherwise fail early with an actionable error.
+
+Synchronous `vibe agent run` does not require callback/no-callback flags.
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index eb68598fb..8b84d3f02 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -14,6 +14,7 @@ from config.v2_config import (
DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,
)
from core.avibe_cloud import avibe_cloud_url_available
+from core.caller_context import caller_env_for_platform_payload
from core.services.session_fork import fork_source_state, pending_native_fork
from core.system_prompt_injection import (
build_forked_session_correction_prompt,
@@ -83,6 +84,8 @@ class CodexAgent(BaseAgent):
self._session_locks: Dict[str, asyncio.Lock] = {}
# base_session_id → (thread_id, developer_instructions)
self._thread_developer_instructions: Dict[str, tuple[str, str]] = {}
+ # base_session_id → (thread_id, AVIBE_* caller env)
+ self._thread_caller_env_configs: Dict[str, tuple[str, dict[str, str]]] = {}
self._fork_correction_pending_base_sessions: set[str] = set()
# ------------------------------------------------------------------
@@ -725,6 +728,22 @@ class CodexAgent(BaseAgent):
# Thread management
# ------------------------------------------------------------------
+ def _caller_env_for_request(self, request: AgentRequest) -> dict[str, str]:
+ context = getattr(request, "context", None)
+ return caller_env_for_platform_payload(getattr(context, "platform_specific", None))
+
+ def _inject_caller_env_config(self, params: Dict[str, Any], request: AgentRequest) -> None:
+ env = self._caller_env_for_request(request)
+ if not env:
+ return
+ config = dict(params.get("config") or {})
+ shell_policy = dict(config.get("shell_environment_policy") or {})
+ set_env = dict(shell_policy.get("set") or {})
+ set_env.update(env)
+ shell_policy["set"] = set_env
+ config["shell_environment_policy"] = shell_policy
+ params["config"] = config
+
async def _start_thread(
self,
transport: CodexTransport,
@@ -740,6 +759,7 @@ class CodexAgent(BaseAgent):
developer_instructions = self._build_thread_developer_instructions(request)
if developer_instructions:
params["developerInstructions"] = developer_instructions
+ self._inject_caller_env_config(params, request)
resp = await transport.send_request("thread/start", params)
# thread/start returns Thread directly OR may nest under "thread"
@@ -755,6 +775,11 @@ class CodexAgent(BaseAgent):
# Also persist for resume support
self.bind_agent_session_id(request, thread_id)
self._remember_thread_developer_instructions(request.base_session_id, thread_id, developer_instructions)
+ self._remember_thread_caller_env_config(
+ request.base_session_id,
+ thread_id,
+ self._caller_env_for_request(request),
+ )
return thread_id
async def _fork_thread(
@@ -778,6 +803,7 @@ class CodexAgent(BaseAgent):
params["developerInstructions"] = developer_instructions
if effective_model:
params["model"] = effective_model
+ self._inject_caller_env_config(params, request)
self._mark_fork_correction_pending(request.base_session_id)
try:
@@ -799,6 +825,11 @@ class CodexAgent(BaseAgent):
self._session_mgr.set_thread_id(request.base_session_id, thread_id)
self.bind_agent_session_id(request, thread_id)
self._remember_thread_developer_instructions(request.base_session_id, thread_id, developer_instructions)
+ self._remember_thread_caller_env_config(
+ request.base_session_id,
+ thread_id,
+ self._caller_env_for_request(request),
+ )
logger.info("Forked Codex thread %s from %s for session %s", thread_id, source_thread_id, request.base_session_id)
return thread_id
@@ -932,6 +963,7 @@ class CodexAgent(BaseAgent):
"threadId": persisted,
"developerInstructions": self._build_thread_developer_instructions(request),
}
+ self._inject_caller_env_config(resume_params, request)
model_provider = await self._resolve_resume_model_provider_override(transport, request, persisted)
if model_provider:
resume_params["modelProvider"] = model_provider
@@ -1128,21 +1160,30 @@ class CodexAgent(BaseAgent):
) -> None:
"""Refresh thread-level instructions for already-cached Codex threads."""
self.ensure_agent_session_id(request)
+ caller_env = self._caller_env_for_request(request)
developer_instructions = self._build_thread_developer_instructions(request)
- if not developer_instructions:
+ if not developer_instructions and not caller_env:
return
if not hasattr(self, "_thread_developer_instructions"):
self._thread_developer_instructions = {}
+ if not hasattr(self, "_thread_caller_env_configs"):
+ self._thread_caller_env_configs = {}
cached = self._thread_developer_instructions.get(request.base_session_id)
- if cached == (thread_id, developer_instructions):
+ cached_caller_env = self._thread_caller_env_configs.get(request.base_session_id)
+ if cached == (thread_id, developer_instructions) and (
+ not caller_env or cached_caller_env == (thread_id, caller_env)
+ ):
return
resume_params: Dict[str, Any] = {
"threadId": thread_id,
- "developerInstructions": developer_instructions,
}
+ if cached != (thread_id, developer_instructions):
+ resume_params["developerInstructions"] = developer_instructions
+ if caller_env:
+ self._inject_caller_env_config(resume_params, request)
model_provider = await self._resolve_resume_model_provider_override(transport, request, thread_id)
if model_provider:
resume_params["modelProvider"] = model_provider
@@ -1156,6 +1197,7 @@ class CodexAgent(BaseAgent):
thread_id,
developer_instructions,
)
+ self._remember_thread_caller_env_config(request.base_session_id, thread_id, caller_env)
def _remember_thread_developer_instructions(
self,
@@ -1169,9 +1211,23 @@ class CodexAgent(BaseAgent):
self._thread_developer_instructions = {}
self._thread_developer_instructions[base_session_id] = (thread_id, developer_instructions)
+ def _remember_thread_caller_env_config(
+ self,
+ base_session_id: str,
+ thread_id: str,
+ caller_env: dict[str, str],
+ ) -> None:
+ if not caller_env:
+ return
+ if not hasattr(self, "_thread_caller_env_configs"):
+ self._thread_caller_env_configs = {}
+ self._thread_caller_env_configs[base_session_id] = (thread_id, dict(caller_env))
+
def _clear_thread_developer_instructions(self, base_session_id: str) -> None:
if hasattr(self, "_thread_developer_instructions"):
self._thread_developer_instructions.pop(base_session_id, None)
+ if hasattr(self, "_thread_caller_env_configs"):
+ self._thread_caller_env_configs.pop(base_session_id, None)
def _fork_correction_pending_sessions(self) -> set[str]:
if not hasattr(self, "_fork_correction_pending_base_sessions"):
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index ef2574bab..305c3f95a 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -17,6 +17,7 @@ from core.avibe_cloud import avibe_cloud_url_available
from core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt
from modules.agents.base import AgentRequest, BaseAgent
+from .caller_context import bind_session as bind_caller_context_session
from .client_manager import OpenCodeClientManager
from .message_processor import OpenCodeMessageProcessorMixin
from .poll_loop import OpenCodePollLoop, restored_session_key_from_poll_info
@@ -327,6 +328,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if request.vibe_agent_system_prompt:
system_prompt_injection = f"{request.vibe_agent_system_prompt}\n\n{system_prompt_injection}"
+ try:
+ bind_caller_context_session(session_id, request.context.platform_specific or {})
+ except Exception:
+ logger.warning("Failed to bind OpenCode caller context for session %s", session_id, exc_info=True)
+
+ await server.mark_run_active(session_id)
+ run_registered = True
await server.prompt_async(
session_id=session_id,
directory=request.working_path,
@@ -339,8 +347,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
get_started_at = getattr(server, "get_last_prompt_started_at", None)
prompt_started_at = get_started_at(session_id) if callable(get_started_at) else None
- await server.mark_run_active(session_id)
- run_registered = True
self.mark_runtime_turn_started(request.context)
logger.info(
diff --git a/modules/agents/opencode/caller_context.py b/modules/agents/opencode/caller_context.py
new file mode 100644
index 000000000..6fad9e1b4
--- /dev/null
+++ b/modules/agents/opencode/caller_context.py
@@ -0,0 +1,162 @@
+"""OpenCode caller-context bridge.
+
+OpenCode runs a shared ``opencode serve`` process, so per-Agent Avibe context
+cannot live in the server process environment. Instead Avibe installs a tiny
+OpenCode plugin that resolves each shell call's OpenCode session id through an
+Avibe-managed binding file and injects the AVIBE_* env vars for that call.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+import json
+import os
+from pathlib import Path
+from typing import Any, Mapping
+
+from config import paths
+from core.caller_context import caller_context_from_platform_payload
+
+PLUGIN_FILENAME = "avibe-caller-context.js"
+BINDINGS_FILENAME = "opencode_caller_context.json"
+BINDING_TTL_HOURS = 24
+
+
+PLUGIN_SOURCE = r"""
+import { readFileSync } from "node:fs"
+
+const bindingPath = process.env.AVIBE_OPENCODE_CALLER_CONTEXT_PATH
+
+function readBindings() {
+ if (!bindingPath) return {}
+ try {
+ const parsed = JSON.parse(readFileSync(bindingPath, "utf8"))
+ return parsed && typeof parsed === "object" && parsed.sessions && typeof parsed.sessions === "object"
+ ? parsed.sessions
+ : {}
+ } catch {
+ return {}
+ }
+}
+
+function applyEnv(output, env) {
+ if (!env || typeof env !== "object") return
+ output.env = output.env || {}
+ for (const [key, value] of Object.entries(env)) {
+ if (typeof value === "string" && value.length > 0) output.env[key] = value
+ }
+}
+
+export const AvibeCallerContextPlugin = async () => ({
+ "shell.env": async (input, output) => {
+ const sessionID = input && typeof input.sessionID === "string" ? input.sessionID : ""
+ if (!sessionID) return
+ const binding = readBindings()[sessionID]
+ if (!binding || typeof binding !== "object") return
+ const expiresAt = typeof binding.expires_at === "string" ? Date.parse(binding.expires_at) : 0
+ if (expiresAt && Date.now() > expiresAt) return
+ applyEnv(output, binding.env)
+ },
+})
+""".lstrip()
+
+
+@dataclass(frozen=True)
+class PluginInstallResult:
+ path: Path
+ changed: bool
+
+
+def binding_path() -> Path:
+ return paths.get_runtime_dir() / BINDINGS_FILENAME
+
+
+def _opencode_config_dir() -> Path:
+ xdg_config_home = os.environ.get("XDG_CONFIG_HOME")
+ root = Path(xdg_config_home).expanduser() if xdg_config_home else Path.home() / ".config"
+ return root / "opencode"
+
+
+def plugin_path() -> Path:
+ return _opencode_config_dir() / "plugins" / PLUGIN_FILENAME
+
+
+def ensure_plugin_installed() -> PluginInstallResult:
+ path = plugin_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ changed = not path.exists() or path.read_text(encoding="utf-8") != PLUGIN_SOURCE
+ if changed:
+ path.write_text(PLUGIN_SOURCE, encoding="utf-8")
+ return PluginInstallResult(path=path, changed=changed)
+
+
+def server_environment() -> dict[str, str]:
+ return {"AVIBE_OPENCODE_CALLER_CONTEXT_PATH": str(binding_path())}
+
+
+def _utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _load_bindings(path: Path) -> dict[str, Any]:
+ try:
+ loaded = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ return {"version": 1, "sessions": {}}
+ if not isinstance(loaded, dict):
+ return {"version": 1, "sessions": {}}
+ sessions = loaded.get("sessions")
+ if not isinstance(sessions, dict):
+ sessions = {}
+ loaded["version"] = 1
+ loaded["sessions"] = sessions
+ return loaded
+
+
+def _prune_sessions(sessions: dict[str, Any], now: datetime) -> dict[str, Any]:
+ pruned: dict[str, Any] = {}
+ for key, value in sessions.items():
+ if not isinstance(value, dict):
+ continue
+ expires_at = value.get("expires_at")
+ if isinstance(expires_at, str):
+ try:
+ if datetime.fromisoformat(expires_at) <= now:
+ continue
+ except ValueError:
+ continue
+ pruned[str(key)] = value
+ return pruned
+
+
+def bind_session(
+ opencode_session_id: str,
+ platform_payload: Mapping[str, object] | None,
+ *,
+ ttl_hours: int = BINDING_TTL_HOURS,
+) -> bool:
+ session_id = str(opencode_session_id or "").strip()
+ if not session_id:
+ return False
+ caller = caller_context_from_platform_payload(platform_payload)
+ if caller is None:
+ return False
+
+ path = binding_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ now = _utc_now()
+ expires_at = now + timedelta(hours=max(1, int(ttl_hours)))
+ data = _load_bindings(path)
+ sessions = _prune_sessions(data.get("sessions", {}), now)
+ sessions[session_id] = {
+ "env": caller.to_env(),
+ "caller_context": caller.to_metadata(),
+ "updated_at": now.isoformat(),
+ "expires_at": expires_at.isoformat(),
+ }
+ data["sessions"] = sessions
+ tmp_path = path.with_suffix(path.suffix + ".tmp")
+ tmp_path.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
+ tmp_path.replace(path)
+ return True
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 68057b8ed..6fd926d2a 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -25,6 +25,7 @@ import aiohttp
from config import paths
from core.process_isolation import isolated_subprocess_kwargs, terminate_process_tree
+from modules.agents.opencode.caller_context import ensure_plugin_installed, server_environment
from modules.agents.opencode.config_reconciler import OpenCodeConfigReconciler
from vibe import runtime
from vibe.opencode_config import (
@@ -39,6 +40,8 @@ DEFAULT_OPENCODE_PORT = 4096
DEFAULT_OPENCODE_HOST = "127.0.0.1"
SERVER_START_TIMEOUT = 15
OPENCODE_LOG_TAIL_BYTES = 2_000_000
+_USE_CURRENT_CALLER_CONTEXT_PATH = object()
+_CURRENT_OWNER_PID = os.getpid()
def _percent_encode_path(path: str) -> str:
@@ -89,9 +92,13 @@ class OpenCodeServerManager:
self._active_run_sessions: set[str] = set()
self._auth_refresh_pending = False
self._auth_refresh_pending_port: Optional[int] = None
+ self._caller_context_plugin_refresh_pending = False
self._pending_runtime_config: Optional[tuple[str, int, int]] = None
self._last_prompt_started_at: dict[str, float] = {}
+ def _caller_context_path(self) -> str:
+ return server_environment()["AVIBE_OPENCODE_CALLER_CONTEXT_PATH"]
+
def _get_lock(self) -> asyncio.Lock:
"""Get or create an asyncio.Lock bound to the current event loop."""
current_loop = asyncio.get_event_loop()
@@ -332,10 +339,12 @@ class OpenCodeServerManager:
async def mark_run_active(self, session_id: str) -> None:
async with self._get_lock():
self._active_run_sessions.add(session_id)
+ self._write_active_run_sessions_to_pid_file()
async def mark_run_inactive(self, session_id: str) -> None:
async with self._get_lock():
self._active_run_sessions.discard(session_id)
+ self._write_active_run_sessions_to_pid_file()
@asynccontextmanager
async def _request_scope(self):
@@ -366,7 +375,13 @@ class OpenCodeServerManager:
return data if isinstance(data, dict) else None
- def _write_pid_file(self, pid: int) -> None:
+ def _write_pid_file(
+ self,
+ pid: int,
+ *,
+ caller_context_path: object = _USE_CURRENT_CALLER_CONTEXT_PATH,
+ owner_pid: Optional[int] = _CURRENT_OWNER_PID,
+ ) -> None:
try:
self._pid_file.parent.mkdir(parents=True, exist_ok=True)
payload = {
@@ -374,11 +389,29 @@ class OpenCodeServerManager:
"port": self.port,
"host": self.host,
"started_at": time.time(),
+ "active_run_sessions": sorted(self._active_run_sessions),
}
+ if owner_pid is not None:
+ payload["owner_pid"] = owner_pid
+ if caller_context_path is _USE_CURRENT_CALLER_CONTEXT_PATH:
+ caller_context_path = self._caller_context_path()
+ if isinstance(caller_context_path, str) and caller_context_path:
+ payload["caller_context_path"] = caller_context_path
self._pid_file.write_text(json.dumps(payload))
except Exception as e:
logger.debug(f"Failed to write OpenCode pid file: {e}")
+ def _write_active_run_sessions_to_pid_file(self) -> None:
+ info = self._read_pid_file()
+ if not self._pid_file_references_current_server(info):
+ return
+ assert isinstance(info, dict)
+ info["active_run_sessions"] = sorted(self._active_run_sessions)
+ try:
+ self._pid_file.write_text(json.dumps(info))
+ except Exception as e:
+ logger.debug(f"Failed to update OpenCode pid active sessions: {e}")
+
def _clear_pid_file(self) -> None:
try:
if self._pid_file.exists():
@@ -386,6 +419,30 @@ class OpenCodeServerManager:
except Exception as e:
logger.debug(f"Failed to clear OpenCode pid file: {e}")
+ def _pid_file_references_current_server(self, info: Optional[Dict[str, Any]]) -> bool:
+ if not isinstance(info, dict):
+ return False
+ pid = info.get("pid")
+ if not isinstance(pid, int):
+ return False
+ if info.get("port") == self.port:
+ return True
+ cmd = self._get_pid_command(pid)
+ return bool(cmd and self._is_opencode_serve_cmd(cmd, self.port))
+
+ def _pid_file_has_caller_context_binding(self, info: Optional[Dict[str, Any]]) -> bool:
+ if not self._pid_file_references_current_server(info):
+ return False
+ return bool(isinstance(info, dict) and info.get("caller_context_path") == self._caller_context_path())
+
+ def _pid_file_was_started_by_current_process(self, info: Optional[Dict[str, Any]]) -> bool:
+ return bool(isinstance(info, dict) and info.get("owner_pid") == _CURRENT_OWNER_PID)
+
+ @staticmethod
+ def _pid_file_has_known_no_active_runs(info: Optional[Dict[str, Any]]) -> bool:
+ active = info.get("active_run_sessions") if isinstance(info, dict) else None
+ return isinstance(active, list) and not active
+
@staticmethod
def _extract_json_object(text: str, start: int) -> Optional[str]:
if start < 0 or start >= len(text) or text[start] != "{":
@@ -869,7 +926,7 @@ class OpenCodeServerManager:
actual_pid = actual_pids[0]
if actual_pid != pid:
logger.info(f"Adopting healthy OpenCode server (updating stale PID {pid} -> {actual_pid})")
- self._write_pid_file(actual_pid)
+ self._write_pid_file(actual_pid, caller_context_path=None, owner_pid=None)
else:
logger.info(f"Adopting healthy OpenCode server pid={pid} from previous run")
else:
@@ -893,11 +950,46 @@ class OpenCodeServerManager:
async def ensure_running(self) -> str:
async with self._get_lock():
+ plugin_install = ensure_plugin_installed()
+ if plugin_install.changed:
+ self._caller_context_plugin_refresh_pending = True
if self._auth_refresh_pending and self._active_requests == 0 and not self._has_active_run_sessions():
await self._restart_for_auth_refresh_locked()
await self._cleanup_orphaned_managed_server()
if await self._is_healthy():
+ pid_info = self._read_pid_file()
+ if not self._pid_file_references_current_server(pid_info):
+ raise RuntimeError(
+ f"OpenCode server is already healthy on port {self.port}, but it is not managed by Avibe. "
+ "Stop that server or configure Avibe to use another OPENCODE_PORT so caller context "
+ "environment variables can be injected safely."
+ )
+ if not self._pid_file_has_caller_context_binding(pid_info):
+ self._caller_context_plugin_refresh_pending = True
+ if (
+ self._caller_context_plugin_refresh_pending
+ and self._active_requests == 0
+ and not self._has_active_run_sessions()
+ and (
+ self._pid_file_was_started_by_current_process(pid_info)
+ or self._pid_file_has_known_no_active_runs(pid_info)
+ )
+ ):
+ logger.info(
+ "Restarting OpenCode server to load updated Avibe caller-context plugin at %s",
+ plugin_install.path,
+ )
+ await self._restart_for_auth_refresh_locked()
+ await self._start_server()
+ self._caller_context_plugin_refresh_pending = False
+ return self.base_url
+ if self._caller_context_plugin_refresh_pending:
+ raise RuntimeError(
+ "OpenCode caller-context plugin refresh is pending for an adopted or active server; "
+ "retry after the existing OpenCode turn finishes so Avibe can restart the server "
+ "with AVIBE_* env injection."
+ )
# If the server is already running (e.g., started by a previous run),
# record its PID so shutdown can clean it up.
if not self._read_pid_file():
@@ -923,6 +1015,7 @@ class OpenCodeServerManager:
)
await self._start_server()
+ self._caller_context_plugin_refresh_pending = False
return self.base_url
async def _is_healthy(self) -> bool:
@@ -988,6 +1081,7 @@ class OpenCodeServerManager:
env = os.environ.copy()
env["OPENCODE_ENABLE_EXA"] = "1"
+ env.update(server_environment())
try:
self._process = await asyncio.create_subprocess_exec(
diff --git a/storage/background.py b/storage/background.py
index 9de31a439..c610a2560 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -1146,7 +1146,7 @@ class SQLiteBackgroundTaskStore:
"last_run_id": payload.get("last_run_id"),
"last_error": payload.get("last_error"),
"last_exit_code": None,
- "metadata_json": _json_dumps({}),
+ "metadata_json": _json_dumps(payload.get("metadata") or {}),
}
def _watch_values(self, payload: dict[str, Any]) -> dict[str, Any]:
@@ -1186,7 +1186,7 @@ class SQLiteBackgroundTaskStore:
"last_run_at": None,
"last_error": payload.get("last_error"),
"last_exit_code": payload.get("last_exit_code"),
- "metadata_json": _json_dumps({}),
+ "metadata_json": _json_dumps(payload.get("metadata") or {}),
}
def _run_values(self, payload: dict[str, Any]) -> dict[str, Any]:
@@ -1259,6 +1259,7 @@ class SQLiteBackgroundTaskStore:
"last_run_at": row["last_run_at"],
"last_run_id": row["last_run_id"],
"last_error": row["last_error"],
+ "metadata": _json_loads(row["metadata_json"], {}),
}
@staticmethod
@@ -1291,6 +1292,7 @@ class SQLiteBackgroundTaskStore:
"last_event_at": row["last_event_at"],
"last_error": row["last_error"],
"last_exit_code": row["last_exit_code"],
+ "metadata": _json_loads(row["metadata_json"], {}),
}
@staticmethod
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 56f492d28..18bbca61c 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -153,6 +153,7 @@ class SQLiteSessionsService:
model: str | None = None,
reasoning_effort: str | None = None,
workdir: str | None = None,
+ metadata: dict[str, Any] | None = None,
) -> str | None:
now = _utc_now_iso()
backend = str(agent_backend or "default")
@@ -174,7 +175,7 @@ class SQLiteSessionsService:
# Explicit caller workdir (e.g. the CLI's invocation cwd) wins;
# None keeps the scope-settings snapshot fallback.
workdir=workdir,
- metadata={"legacy_scope_key": str(scope_key)},
+ metadata={"legacy_scope_key": str(scope_key), **dict(metadata or {})},
now=now,
require_workdir=False,
)
@@ -190,6 +191,7 @@ class SQLiteSessionsService:
model: str | None = None,
reasoning_effort: str | None = None,
workdir: str | None = None,
+ metadata: dict[str, Any] | None = None,
) -> str:
now = _utc_now_iso()
platform_key = str(platform or "slack").strip() or "slack"
@@ -222,7 +224,7 @@ class SQLiteSessionsService:
model=model,
reasoning_effort=reasoning_effort,
workdir=workdir,
- metadata={"legacy_scope_key": scope_key, **metadata_payload},
+ metadata={"legacy_scope_key": scope_key, **metadata_payload, **dict(metadata or {})},
now=now,
require_workdir=False,
)
diff --git a/tests/test_caller_context.py b/tests/test_caller_context.py
new file mode 100644
index 000000000..52f452403
--- /dev/null
+++ b/tests/test_caller_context.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+from core.caller_context import (
+ AVIBE_CALLER_BACKEND_ENV,
+ AVIBE_CALLER_SOURCE_ENV,
+ AVIBE_NATIVE_SESSION_ID_ENV,
+ AVIBE_RUN_ID_ENV,
+ AVIBE_SESSION_ID_ENV,
+ caller_context_from_env,
+ caller_context_from_platform_payload,
+)
+
+
+def test_caller_context_from_env_requires_session_id() -> None:
+ assert caller_context_from_env({}) is None
+
+
+def test_caller_context_from_env_round_trips_metadata_and_env() -> None:
+ context = caller_context_from_env(
+ {
+ AVIBE_SESSION_ID_ENV: "ses123",
+ AVIBE_RUN_ID_ENV: "run456",
+ AVIBE_CALLER_SOURCE_ENV: "agent_run",
+ AVIBE_CALLER_BACKEND_ENV: "codex",
+ AVIBE_NATIVE_SESSION_ID_ENV: "thread789",
+ }
+ )
+
+ assert context is not None
+ assert context.to_metadata() == {
+ "session_id": "ses123",
+ "run_id": "run456",
+ "source": "agent_run",
+ "backend": "codex",
+ "native_session_id": "thread789",
+ }
+ assert context.to_env()[AVIBE_SESSION_ID_ENV] == "ses123"
+
+
+def test_caller_context_from_platform_payload_prefers_agent_session_target() -> None:
+ context = caller_context_from_platform_payload(
+ {
+ "agent_session_id": "legacy",
+ "task_execution_id": "run123",
+ "task_trigger_kind": "agent_run",
+ "agent_session_target": {
+ "id": "ses-target",
+ "agent_backend": "opencode",
+ "native_session_id": "oc-session",
+ },
+ }
+ )
+
+ assert context is not None
+ assert context.to_metadata() == {
+ "session_id": "ses-target",
+ "run_id": "run123",
+ "source": "agent_run",
+ "backend": "opencode",
+ "native_session_id": "oc-session",
+ }
+ assert context.to_env()[AVIBE_NATIVE_SESSION_ID_ENV] == "oc-session"
+
+
+def test_caller_context_from_platform_payload_preserves_callback_source() -> None:
+ context = caller_context_from_platform_payload(
+ {
+ "agent_session_id": "ses-callback",
+ "task_execution_id": "run-callback",
+ "task_trigger_kind": "agent_run",
+ "source_kind": "callback",
+ }
+ )
+
+ assert context is not None
+ assert context.source == "callback"
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 6e1ac6b70..003044bec 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -512,6 +512,45 @@ def test_session_handler_marks_claude_sdk_session_process_owner(monkeypatch, tmp
assert registered == [{"client": client, "native_session_id": None, "owner": "session"}]
+def test_session_handler_injects_caller_context_env(monkeypatch, tmp_path: Path) -> None:
+ captured: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+
+ async def connect(self) -> None:
+ captured["connected"] = True
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ context = MessageContext(
+ user_id="U123",
+ channel_id="C123",
+ platform_specific={
+ "task_execution_id": "run-parent",
+ "task_trigger_kind": "agent_run",
+ "agent_session_target": {
+ "id": "ses-parent",
+ "agent_backend": "claude",
+ "native_session_id": "claude-native",
+ },
+ },
+ )
+
+ _run_session(handler, context)
+
+ env = captured["options"].env
+ assert env["AVIBE_SESSION_ID"] == "ses-parent"
+ assert env["AVIBE_RUN_ID"] == "run-parent"
+ assert env["AVIBE_CALLER_SOURCE"] == "agent_run"
+ assert env["AVIBE_CALLER_BACKEND"] == "claude"
+ assert env["AVIBE_NATIVE_SESSION_ID"] == "claude-native"
+
+
def test_session_handler_coalesces_concurrent_claude_client_creates(
monkeypatch, tmp_path: Path
) -> None:
@@ -755,6 +794,167 @@ def test_session_handler_does_not_repeat_claude_model_control_request(monkeypatc
assert first_client.model_calls == []
+def test_session_handler_recreates_cached_claude_client_when_caller_env_changes(
+ monkeypatch, tmp_path: Path
+) -> None:
+ captured: dict[str, Any] = {"clients": []}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ self.options = options
+ self.disconnects = 0
+ captured["clients"].append(self)
+
+ async def connect(self) -> None:
+ return None
+
+ async def disconnect(self) -> None:
+ self.disconnects += 1
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ context = MessageContext(
+ user_id="U123",
+ channel_id="C123",
+ platform_specific={
+ "task_execution_id": "run-one",
+ "task_trigger_kind": "agent_run",
+ "agent_session_target": {"id": "ses-parent", "agent_backend": "claude"},
+ },
+ )
+
+ first_client = _run_session(handler, context)
+ context.platform_specific["task_execution_id"] = "run-two"
+ second_client = _run_session(handler, context)
+
+ assert first_client is not second_client
+ assert first_client.disconnects == 1
+ assert len(captured["clients"]) == 2
+ assert first_client.options.env["AVIBE_RUN_ID"] == "run-one"
+ assert second_client.options.env["AVIBE_RUN_ID"] == "run-two"
+
+
+def test_session_handler_recreates_cached_claude_subagent_when_caller_env_changes(
+ monkeypatch, tmp_path: Path
+) -> None:
+ captured: dict[str, Any] = {"clients": []}
+
+ class _RoutingSettingsManager(_SettingsManager):
+ @staticmethod
+ def get_channel_routing(settings_key):
+ return type("Routing", (), {"claude_agent": "reviewer", "model": None, "reasoning_effort": None})()
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ self.options = options
+ self.disconnects = 0
+ captured["clients"].append(self)
+
+ async def connect(self) -> None:
+ return None
+
+ async def disconnect(self) -> None:
+ self.disconnects += 1
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+
+ controller = _Controller(tmp_path)
+ controller.settings_manager = _RoutingSettingsManager()
+ controller.platform_settings_managers = {"slack": controller.settings_manager}
+ handler = SessionHandler(controller)
+ context = MessageContext(
+ user_id="U123",
+ channel_id="C123",
+ platform_specific={
+ "routing_subagent": "reviewer",
+ "task_execution_id": "run-one",
+ "task_trigger_kind": "agent_run",
+ "agent_session_target": {"id": "ses-parent", "agent_backend": "claude"},
+ },
+ )
+
+ first_client = _run_session(handler, context)
+ context.platform_specific["task_execution_id"] = "run-two"
+ second_client = _run_session(handler, context)
+
+ assert first_client is not second_client
+ assert first_client.disconnects == 1
+ assert len(captured["clients"]) == 2
+ assert first_client.options.env["AVIBE_RUN_ID"] == "run-one"
+ assert second_client.options.env["AVIBE_RUN_ID"] == "run-two"
+
+
+def test_session_handler_reuses_cached_claude_subagent_after_ensuring_caller_env(
+ monkeypatch, tmp_path: Path
+) -> None:
+ captured: dict[str, Any] = {"clients": []}
+
+ class _RoutingSessions(_Sessions):
+ ensured: list[tuple[str, str, str]] = []
+
+ @staticmethod
+ def get_agent_session_id(settings_key, base_session_id, agent_name):
+ return None
+
+ @classmethod
+ def ensure_agent_session_id(cls, settings_key, agent_name, base_session_id):
+ cls.ensured.append((settings_key, agent_name, base_session_id))
+ return "ses-subagent"
+
+ class _RoutingSettingsManager(_SettingsManager):
+ def __init__(self) -> None:
+ super().__init__()
+ self.sessions = _RoutingSessions()
+
+ @staticmethod
+ def get_channel_routing(settings_key):
+ return type("Routing", (), {"claude_agent": "reviewer", "model": None, "reasoning_effort": None})()
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ self.options = options
+ self.disconnects = 0
+ captured["clients"].append(self)
+
+ async def connect(self) -> None:
+ return None
+
+ async def disconnect(self) -> None:
+ self.disconnects += 1
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+
+ controller = _Controller(tmp_path)
+ controller.settings_manager = _RoutingSettingsManager()
+ controller.platform_settings_managers = {"slack": controller.settings_manager}
+ handler = SessionHandler(controller)
+
+ first_context = MessageContext(
+ user_id="U123",
+ channel_id="C123",
+ platform_specific={"routing_subagent": "reviewer", "task_trigger_kind": "agent_run"},
+ )
+ first_client = _run_session(handler, first_context)
+
+ second_context = MessageContext(
+ user_id="U123",
+ channel_id="C123",
+ platform_specific={"routing_subagent": "reviewer", "task_trigger_kind": "agent_run"},
+ )
+ second_client = _run_session(handler, second_context)
+
+ assert first_client is second_client
+ assert first_client.disconnects == 0
+ assert len(captured["clients"]) == 1
+ assert first_client.options.env["AVIBE_SESSION_ID"] == "ses-subagent"
+ assert second_context.platform_specific["agent_session_id"] == "ses-subagent"
+
+
def test_session_handler_updates_cached_claude_model_only_when_changed(monkeypatch, tmp_path: Path) -> None:
captured: dict[str, Any] = {}
diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.py
index 3f2fb965c..00ccb7f88 100644
--- a/tests/test_cli_agent_run_schema.py
+++ b/tests/test_cli_agent_run_schema.py
@@ -42,11 +42,23 @@ _EXPECTED_KEYS = {
"session_id",
"deliver_key",
"callback_session_id",
+ "caller_context",
+ "callback_notice",
"async",
"run",
}
-_EXPECTED_RUN_KEYS_QUEUED = {"id", "status", "run_type", "agent_name", "session_id", "callback_session_id"}
+_EXPECTED_RUN_KEYS_QUEUED = {
+ "id",
+ "status",
+ "run_type",
+ "agent_name",
+ "session_id",
+ "callback_session_id",
+ "source_kind",
+ "source_actor",
+ "parent_run_id",
+}
def test_agent_run_async_envelope_schema(tmp_path: Path, capsys) -> None:
@@ -60,7 +72,7 @@ def test_agent_run_async_envelope_schema(tmp_path: Path, capsys) -> None:
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", "--message", "hi"])
+ args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hi"])
with (
patch("vibe.cli._agent_store", return_value=agent_store),
@@ -83,6 +95,9 @@ def test_agent_run_async_envelope_schema(tmp_path: Path, capsys) -> None:
assert payload["kind"] == "agent_run"
assert payload["async"] is True
assert payload["request_type"] == "agent_run"
+ assert payload["callback_session_id"] is None
+ assert payload["caller_context"] is None
+ assert payload["callback_notice"]["code"] == "async_run_without_callback"
run = payload["run"]
assert set(run.keys()) == _EXPECTED_RUN_KEYS_QUEUED, (
@@ -92,6 +107,9 @@ 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"]
+ assert run["source_kind"] == "cli"
+ assert run["source_actor"] is None
+ assert run["parent_run_id"] is None
def test_agent_run_async_accepts_callback_session_id(tmp_path: Path, capsys) -> None:
@@ -171,6 +189,205 @@ def test_agent_run_async_accepts_callback_session_id(tmp_path: Path, capsys) ->
assert stored["callback_status"] == "pending"
+def test_agent_run_async_requires_callback_or_no_callback_without_caller(tmp_path: Path, capsys) -> None:
+ from sqlalchemy import func, select
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions
+
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(tmp_path)}):
+ ensure_sqlite_state()
+ 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", "--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)
+
+ engine = create_sqlite_engine(db_path)
+ with engine.connect() as conn:
+ session_count = conn.execute(select(func.count()).select_from(agent_sessions)).scalar_one()
+
+ assert result == 1
+ captured = capsys.readouterr()
+ payload = json.loads(captured.out or captured.err)
+ assert payload["code"] == "missing_async_callback"
+ assert "--callback-session-id" in payload["hint"]
+ assert "--no-callback" in payload["hint"]
+ assert session_count == 0
+
+
+def test_agent_run_async_defaults_callback_from_caller_env(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", {"AVIBE_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_caller",
+ 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",
+ )
+ )
+ caller_session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="caller",
+ )
+ 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", "--message", "hi"])
+
+ with (
+ patch.dict(
+ "os.environ",
+ {
+ "AVIBE_SESSION_ID": caller_session["id"],
+ "AVIBE_RUN_ID": "run-parent",
+ "AVIBE_CALLER_SOURCE": "agent_run",
+ "AVIBE_CALLER_BACKEND": "codex",
+ "AVIBE_NATIVE_SESSION_ID": "thread-caller",
+ },
+ ),
+ 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"] == caller_session["id"]
+ assert payload["caller_context"] == {
+ "session_id": caller_session["id"],
+ "run_id": "run-parent",
+ "source": "agent_run",
+ "backend": "codex",
+ "native_session_id": "thread-caller",
+ }
+ assert payload["callback_notice"]["code"] == "callback_defaulted_to_caller_session"
+ assert payload["run"]["source_kind"] == "agent"
+ assert payload["run"]["source_actor"] == caller_session["id"]
+ assert payload["run"]["parent_run_id"] == "run-parent"
+ stored = request_store.get_run(payload["run_id"])
+ assert stored is not None
+ assert stored["callback_session_id"] == caller_session["id"]
+ assert stored["source_kind"] == "agent"
+ assert stored["source_actor"] == caller_session["id"]
+ assert stored["parent_run_id"] == "run-parent"
+ assert stored["metadata"]["caller_context"]["session_id"] == caller_session["id"]
+
+
+def test_agent_run_async_requires_explicit_policy_when_target_is_caller_session(
+ 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", {"AVIBE_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_caller",
+ 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",
+ )
+ )
+ caller_session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="caller",
+ )
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="caller", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(["--session-id", caller_session["id"], "--async", "--message", "hi"])
+
+ with (
+ patch.dict(
+ "os.environ",
+ {
+ "AVIBE_SESSION_ID": caller_session["id"],
+ "AVIBE_RUN_ID": "run-parent",
+ "AVIBE_CALLER_SOURCE": "agent_run",
+ "AVIBE_CALLER_BACKEND": "codex",
+ },
+ ),
+ 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),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 1
+ payload = json.loads(capsys.readouterr().err)
+ assert payload["code"] == "self_callback_requires_explicit_policy"
+ assert "--no-callback" in payload["hint"]
+ assert request_store.list_pending() == []
+
+
def test_agent_run_callback_session_requires_async(capsys) -> None:
args = _parse_agent_run(["--agent", "worker", "--callback-session-id", "ses1", "--message", "hi"])
@@ -182,6 +399,48 @@ def test_agent_run_callback_session_requires_async(capsys) -> None:
assert payload["code"] == "callback_requires_async"
+def test_agent_run_callback_conflict_does_not_reserve_session(tmp_path: Path, capsys) -> None:
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions
+ from sqlalchemy import select, func
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ args = _parse_agent_run(
+ [
+ "--agent",
+ "worker",
+ "--async",
+ "--callback-session-id",
+ "ses-caller",
+ "--no-callback",
+ "--message",
+ "hi",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_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)
+
+ engine = create_sqlite_engine(db_path)
+ with engine.connect() as conn:
+ session_count = conn.execute(select(func.count()).select_from(agent_sessions)).scalar_one()
+
+ assert result == 1
+ payload = json.loads(capsys.readouterr().err)
+ assert payload["code"] == "conflicting_callback_policy"
+ assert session_count == 0
+
+
def _read_session_workdir(db_path: Path, session_id: str):
from sqlalchemy import select
@@ -274,6 +533,7 @@ def test_agent_run_fork_session_reserves_new_session_and_persists_metadata(tmp_p
"--reasoning-effort",
"low",
"--async",
+ "--no-callback",
"--message",
"continue from here",
]
@@ -327,7 +587,16 @@ def test_agent_run_fork_rejects_cross_backend_agent(tmp_path: Path, capsys) -> N
agent_store.create(name="claude-worker", backend="claude")
request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
args = _parse_agent_run(
- ["--fork-session", source_session_id, "--agent", "claude-worker", "--async", "--message", "hi"]
+ [
+ "--fork-session",
+ source_session_id,
+ "--agent",
+ "claude-worker",
+ "--async",
+ "--no-callback",
+ "--message",
+ "hi",
+ ]
)
with (
@@ -361,7 +630,7 @@ def test_agent_run_private_session_workdir_follows_invocation_cwd(tmp_path: Path
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", "--message", "hi"])
+ args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hi"])
monkeypatch.chdir(invoke_dir)
expected = os.getcwd()
@@ -393,7 +662,7 @@ def test_agent_run_explicit_cwd_wins(tmp_path: Path, capsys, monkeypatch) -> Non
agent_store.create(name="worker", backend="codex")
request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
args = _parse_agent_run(
- ["--agent", "worker", "--cwd", str(picked_dir), "--async", "--message", "hi"]
+ ["--agent", "worker", "--cwd", str(picked_dir), "--async", "--no-callback", "--message", "hi"]
)
monkeypatch.chdir(invoke_dir)
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index 99e5e14d7..4e83e6b06 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import io
import json
+import os
import sqlite3
import sys
from contextlib import redirect_stderr
@@ -86,7 +87,7 @@ def test_disabled_agent_cannot_run(tmp_path: Path) -> None:
db_path = tmp_path / "state" / "vibe.sqlite"
agent_store = cli.VibeAgentStore(db_path)
agent_store.create(name="worker", backend="codex", enabled=False)
- args = _parse_agent_run(["--agent", "worker", "--async", "--message", "hello"])
+ args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hello"])
with patch("vibe.cli._agent_store", return_value=agent_store):
result, payload = _capture_stderr_json(cli.cmd_agent_run, args)
@@ -217,7 +218,8 @@ def test_hook_send_help_describes_runtime_effects(capsys) -> None:
assert "`--post-to channel` changes where the message is posted, not which session is continued." in captured.out
assert "`--message` and `--message-file` provide the one-shot async user message that will be queued immediately." in captured.out
assert "--session-id" in captured.out
- assert "vibe agent run --async --session-id sesk8m4q2p7x" in captured.out
+ assert "vibe agent run --async --session-id sesk8m4q2p7x --no-callback" in captured.out
+ assert "--callback-session-id sescaller123" in captured.out
def test_task_list_help_mentions_completed_one_shots_hidden_by_default(capsys) -> None:
@@ -260,7 +262,7 @@ def test_hook_send_help_includes_examples_and_threadless_guidance(capsys) -> Non
assert "--post-to" in captured.out
assert "--deliver-key" in captured.out
assert "--session-id" in captured.out
- assert "vibe agent run --async --session-id sesk8m4q2p7x" in captured.out
+ assert "vibe agent run --async --session-id sesk8m4q2p7x --no-callback" in captured.out
def test_agent_run_help_includes_fork_session_guidance(capsys) -> None:
@@ -274,7 +276,7 @@ def test_agent_run_help_includes_fork_session_guidance(capsys) -> None:
assert "--fork-session FORK_SESSION" in captured.out
assert "Use --fork-session to create a new Session by forking an existing Session's native backend context." in captured.out
assert "Forks keep the same backend as the source Session." in captured.out
- assert "vibe agent run --async --fork-session sesk8m4q2p7x" in captured.out
+ assert "vibe agent run --async --fork-session sesk8m4q2p7x --callback-session-id sescaller123" in captured.out
assert "Do not combine --fork-session with --session-id, --create-session, --create-session-per-run, --deliver-key, or --post-to." in captured.out
@@ -451,6 +453,52 @@ def test_task_show_missing_id_returns_guidance(tmp_path: Path) -> None:
assert payload["help_command"] == "vibe task list"
+def test_task_add_records_caller_context_metadata(tmp_path: Path, capsys) -> None:
+ store_path = tmp_path / "scheduled_tasks.json"
+ store = cli.ScheduledTaskStore(store_path)
+ args = _parse_task_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--cron",
+ "0 * * * *",
+ "--message",
+ "hello",
+ ]
+ )
+ caller_env = {
+ "AVIBE_SESSION_ID": "sesCaller",
+ "AVIBE_RUN_ID": "runCaller",
+ "AVIBE_CALLER_SOURCE": "agent_turn",
+ "AVIBE_CALLER_BACKEND": "codex",
+ "AVIBE_NATIVE_SESSION_ID": "native-codex-1",
+ }
+
+ with (
+ patch.dict(os.environ, caller_env, clear=False),
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_add(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ expected = {
+ "kind": "caller_context",
+ "caller": {
+ "session_id": "sesCaller",
+ "run_id": "runCaller",
+ "source": "agent_turn",
+ "backend": "codex",
+ "native_session_id": "native-codex-1",
+ },
+ }
+ assert payload["task"]["metadata"]["created_by"] == expected
+ stored = cli.ScheduledTaskStore(store_path).get_task(payload["task"]["id"])
+ assert stored is not None
+ assert stored.metadata["created_by"] == expected
+
+
def test_task_update_missing_id_returns_guidance(tmp_path: Path) -> None:
store_path = tmp_path / "scheduled_tasks.json"
@@ -925,7 +973,7 @@ def test_agent_run_private_async_reserves_session_and_queues_request(tmp_path: P
agent_store = cli.VibeAgentStore(db_path)
agent = agent_store.create(name="worker", backend="codex")
request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
- args = _parse_agent_run(["--agent", "worker", "--async", "--message", "hello"])
+ args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hello"])
with (
patch("vibe.cli._agent_store", return_value=agent_store),
@@ -956,6 +1004,7 @@ def test_agent_run_create_session_uses_scope_anchor_for_channel_deliver_key(tmp_
"--agent",
"worker",
"--async",
+ "--no-callback",
"--create-session",
"--deliver-key",
"slack::channel::C123",
@@ -985,7 +1034,7 @@ def test_agent_run_private_async_uses_no_delivery_channel_scope_for_lark(tmp_pat
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", "--message", "hello"])
+ args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hello"])
with (
patch("vibe.cli._agent_store", return_value=agent_store),
@@ -1169,7 +1218,7 @@ def test_agent_run_existing_session_uses_session_agent_when_agent_omitted(tmp_pa
)
finally:
service.close()
- args = _parse_agent_run(["--async", "--session-id", session_id, "--message", "hello"])
+ args = _parse_agent_run(["--async", "--no-callback", "--session-id", session_id, "--message", "hello"])
with (
patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 3ac613773..ba9fe3d48 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import io
import json
+import os
import sqlite3
import sys
from contextlib import redirect_stderr
@@ -247,6 +248,54 @@ def test_watch_add_creates_shell_watch(tmp_path: Path, capsys) -> None:
assert payload["watch"]["retry_exit_codes"] == [75]
+def test_watch_add_records_caller_context_metadata(tmp_path: Path, capsys) -> None:
+ store_path = tmp_path / "watches.json"
+ runtime_path = tmp_path / "watch_runtime.json"
+ store = ManagedWatchStore(store_path)
+ runtime_store = WatchRuntimeStateStore(runtime_path)
+ args = _parse_watch_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--shell",
+ "python3 scripts/wait.py",
+ ]
+ )
+ caller_env = {
+ "AVIBE_SESSION_ID": "sesCaller",
+ "AVIBE_RUN_ID": "runCaller",
+ "AVIBE_CALLER_SOURCE": "agent_turn",
+ "AVIBE_CALLER_BACKEND": "opencode",
+ "AVIBE_NATIVE_SESSION_ID": "native-opencode-1",
+ }
+
+ with (
+ patch.dict(os.environ, caller_env, clear=False),
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ patch("vibe.cli._wait_for_watch_startup", side_effect=lambda *args, **kwargs: _startup_ok(store, runtime_store, args[2])),
+ ):
+ result = cli.cmd_watch_add(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ expected = {
+ "kind": "caller_context",
+ "caller": {
+ "session_id": "sesCaller",
+ "run_id": "runCaller",
+ "source": "agent_turn",
+ "backend": "opencode",
+ "native_session_id": "native-opencode-1",
+ },
+ }
+ assert payload["watch"]["metadata"]["created_by"] == expected
+ stored = ManagedWatchStore(store_path).get_watch(payload["watch"]["id"])
+ assert stored is not None
+ assert stored.metadata["created_by"] == expected
+
+
def test_watch_add_accepts_message_template(tmp_path: Path, capsys) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index a71b65f3c..fd3f8fca8 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -1084,6 +1084,33 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
+ def test_inject_caller_env_config_merges_shell_environment_policy(self):
+ agent = object.__new__(CodexAgent)
+ params = {"config": {"shell_environment_policy": {"set": {"KEEP": "1"}}}}
+ request = SimpleNamespace(
+ context=SimpleNamespace(
+ platform_specific={
+ "task_execution_id": "run-parent",
+ "task_trigger_kind": "agent_run",
+ "agent_session_target": {
+ "id": "ses-parent",
+ "agent_backend": "codex",
+ "native_session_id": "thread-parent",
+ },
+ }
+ )
+ )
+
+ agent._inject_caller_env_config(params, request)
+
+ set_env = params["config"]["shell_environment_policy"]["set"]
+ self.assertEqual(set_env["KEEP"], "1")
+ self.assertEqual(set_env["AVIBE_SESSION_ID"], "ses-parent")
+ self.assertEqual(set_env["AVIBE_RUN_ID"], "run-parent")
+ self.assertEqual(set_env["AVIBE_CALLER_SOURCE"], "agent_run")
+ self.assertEqual(set_env["AVIBE_CALLER_BACKEND"], "codex")
+ self.assertEqual(set_env["AVIBE_NATIVE_SESSION_ID"], "thread-parent")
+
async def test_start_thread_requests_danger_full_access(self):
agent = object.__new__(CodexAgent)
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=False))
@@ -1262,7 +1289,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
working_path="/tmp/work",
context=SimpleNamespace(
platform="slack",
- platform_specific={"is_dm": False},
+ platform_specific={},
user_id="U1",
channel_id="C1",
thread_id="171717.123",
@@ -2472,6 +2499,53 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("Current session id: `sesk8m4q2p7x`", params["developerInstructions"])
self.assertIn("# Avibe", params["developerInstructions"])
+ async def test_refresh_thread_developer_instructions_refreshes_caller_env_when_prompt_cached(self):
+ agent = object.__new__(CodexAgent)
+ agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
+ agent.codex_config = SimpleNamespace(default_model=None)
+ agent.sessions = SimpleNamespace(ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"))
+ agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)
+ agent._thread_developer_instructions = {}
+ request = SimpleNamespace(
+ working_path="/tmp/work",
+ session_key="slack::channel::C1::thread::171717.123",
+ base_session_id="session-1",
+ context=SimpleNamespace(
+ platform="slack",
+ platform_specific={
+ "task_execution_id": "run-one",
+ "task_trigger_kind": "agent_run",
+ "agent_session_target": {
+ "id": "sesk8m4q2p7x",
+ "agent_backend": "codex",
+ "native_session_id": "thread-existing",
+ },
+ },
+ user_id="U1",
+ channel_id="C1",
+ thread_id="171717.123",
+ ),
+ subagent_name=None,
+ subagent_model=None,
+ subagent_reasoning_effort=None,
+ )
+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"thread": {"id": "thread-existing"}}))
+
+ await agent._refresh_thread_developer_instructions_if_needed(transport, request, "thread-existing")
+ request.context.platform_specific["task_execution_id"] = "run-two"
+ await agent._refresh_thread_developer_instructions_if_needed(transport, request, "thread-existing")
+
+ self.assertEqual(transport.send_request.await_count, 2)
+ first_params = transport.send_request.await_args_list[0].args[1]
+ second_params = transport.send_request.await_args_list[1].args[1]
+ self.assertIn("developerInstructions", first_params)
+ self.assertNotIn("developerInstructions", second_params)
+ self.assertEqual(
+ second_params["config"]["shell_environment_policy"]["set"]["AVIBE_RUN_ID"],
+ "run-two",
+ )
+ self.assertEqual(second_params["threadId"], "thread-existing")
+
async def test_refresh_thread_developer_instructions_preserves_resume_model_provider_override(self):
agent = object.__new__(CodexAgent)
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
diff --git a/tests/test_opencode_caller_context.py b/tests/test_opencode_caller_context.py
new file mode 100644
index 000000000..ffc6dc2d3
--- /dev/null
+++ b/tests/test_opencode_caller_context.py
@@ -0,0 +1,60 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from modules.agents.opencode import caller_context as bridge
+
+
+def test_ensure_plugin_installed_writes_global_opencode_plugin(tmp_path: Path, monkeypatch) -> None:
+ xdg_home = tmp_path / "xdg"
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(xdg_home))
+
+ result = bridge.ensure_plugin_installed()
+ path = result.path
+
+ assert path == xdg_home / "opencode" / "plugins" / bridge.PLUGIN_FILENAME
+ assert result.changed is True
+ source = path.read_text(encoding="utf-8")
+ assert '"shell.env"' in source
+ assert "AVIBE_OPENCODE_CALLER_CONTEXT_PATH" in source
+
+ assert bridge.ensure_plugin_installed().changed is False
+
+
+def test_bind_session_writes_env_binding(tmp_path: Path, monkeypatch) -> None:
+ avibe_home = tmp_path / "avibe"
+ monkeypatch.setenv("AVIBE_HOME", str(avibe_home))
+
+ ok = bridge.bind_session(
+ "oc-session",
+ {
+ "task_execution_id": "run123",
+ "task_trigger_kind": "agent_run",
+ "agent_session_target": {
+ "id": "ses123",
+ "agent_backend": "opencode",
+ "native_session_id": "oc-session",
+ },
+ },
+ )
+
+ assert ok is True
+ data = json.loads(bridge.binding_path().read_text(encoding="utf-8"))
+ entry = data["sessions"]["oc-session"]
+ assert entry["env"] == {
+ "AVIBE_SESSION_ID": "ses123",
+ "AVIBE_RUN_ID": "run123",
+ "AVIBE_CALLER_SOURCE": "agent_run",
+ "AVIBE_CALLER_BACKEND": "opencode",
+ "AVIBE_NATIVE_SESSION_ID": "oc-session",
+ }
+ assert entry["caller_context"]["session_id"] == "ses123"
+ assert "expires_at" in entry
+
+
+def test_bind_session_skips_without_resolved_caller_context(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))
+
+ assert bridge.bind_session("oc-session", {"platform": "slack"}) is False
+ assert not bridge.binding_path().exists()
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index 01c794161..9ba3fc9c9 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -131,6 +131,174 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
"/tmp/a%2520b",
)
+ async def test_ensure_running_restarts_healthy_server_when_caller_context_plugin_changes(self):
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ restarted = []
+ started = []
+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
+ manager._restart_for_auth_refresh_locked = AsyncMock(side_effect=lambda: restarted.append(True)) # type: ignore[method-assign]
+ manager._start_server = AsyncMock(side_effect=lambda: started.append(True)) # type: ignore[method-assign]
+ manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "caller_context_path": manager._caller_context_path(), "owner_pid": SERVER_MODULE._CURRENT_OWNER_PID} # type: ignore[method-assign]
+
+ with patch.object(
+ SERVER_MODULE,
+ "ensure_plugin_installed",
+ return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=True),
+ ):
+ base_url = await manager.ensure_running()
+
+ self.assertEqual(base_url, "http://127.0.0.1:4096")
+ self.assertEqual(restarted, [True])
+ self.assertEqual(started, [True])
+ self.assertFalse(manager._caller_context_plugin_refresh_pending)
+
+ async def test_ensure_running_defers_plugin_restart_while_run_active(self):
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager._active_run_sessions.add("ses-active")
+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
+ manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
+ manager._start_server = AsyncMock() # type: ignore[method-assign]
+ manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "caller_context_path": manager._caller_context_path(), "owner_pid": SERVER_MODULE._CURRENT_OWNER_PID} # type: ignore[method-assign]
+
+ with patch.object(
+ SERVER_MODULE,
+ "ensure_plugin_installed",
+ return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=True),
+ ):
+ with self.assertRaisesRegex(RuntimeError, "caller-context plugin refresh is pending"):
+ await manager.ensure_running()
+
+ manager._restart_for_auth_refresh_locked.assert_not_awaited()
+ manager._start_server.assert_not_awaited()
+ self.assertTrue(manager._caller_context_plugin_refresh_pending)
+
+ async def test_ensure_running_restarts_adopted_server_without_caller_context_env(self):
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ restarted = []
+ started = []
+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
+ manager._restart_for_auth_refresh_locked = AsyncMock(side_effect=lambda: restarted.append(True)) # type: ignore[method-assign]
+ manager._start_server = AsyncMock(side_effect=lambda: started.append(True)) # type: ignore[method-assign]
+ manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "active_run_sessions": []} # type: ignore[method-assign]
+
+ with patch.object(
+ SERVER_MODULE,
+ "ensure_plugin_installed",
+ return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
+ ):
+ base_url = await manager.ensure_running()
+
+ self.assertEqual(base_url, "http://127.0.0.1:4096")
+ self.assertEqual(restarted, [True])
+ self.assertEqual(started, [True])
+ self.assertFalse(manager._caller_context_plugin_refresh_pending)
+
+ async def test_ensure_running_defers_adopted_server_without_caller_context_env(self):
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
+ manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
+ manager._start_server = AsyncMock() # type: ignore[method-assign]
+ manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "active_run_sessions": ["ses-active"]} # type: ignore[method-assign]
+
+ with patch.object(
+ SERVER_MODULE,
+ "ensure_plugin_installed",
+ return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
+ ):
+ with self.assertRaisesRegex(RuntimeError, "adopted or active server"):
+ await manager.ensure_running()
+
+ manager._restart_for_auth_refresh_locked.assert_not_awaited()
+ manager._start_server.assert_not_awaited()
+ self.assertTrue(manager._caller_context_plugin_refresh_pending)
+
+ async def test_ensure_running_defers_adopted_server_with_unknown_active_state(self):
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
+ manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
+ manager._start_server = AsyncMock() # type: ignore[method-assign]
+ manager._read_pid_file = lambda: {"pid": 123, "port": 4096} # type: ignore[method-assign]
+
+ with patch.object(
+ SERVER_MODULE,
+ "ensure_plugin_installed",
+ return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
+ ):
+ with self.assertRaisesRegex(RuntimeError, "adopted or active server"):
+ await manager.ensure_running()
+
+ manager._restart_for_auth_refresh_locked.assert_not_awaited()
+ manager._start_server.assert_not_awaited()
+ self.assertTrue(manager._caller_context_plugin_refresh_pending)
+
+ async def test_mark_run_active_persists_pid_file_active_sessions(self):
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ manager._pid_file = Path(tmp_dir) / "opencode_server.json"
+ manager._write_pid_file(123)
+
+ await manager.mark_run_active("ses-active")
+
+ payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
+ self.assertEqual(payload["active_run_sessions"], ["ses-active"])
+
+ await manager.mark_run_inactive("ses-active")
+
+ payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))
+ self.assertEqual(payload["active_run_sessions"], [])
+
+ async def test_cleanup_stale_managed_pid_does_not_inherit_caller_context_for_new_pid(self):
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ pid_info = {"pid": 111, "port": 4096, "caller_context_path": manager._caller_context_path()}
+ writes = []
+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ manager._read_pid_file = lambda: pid_info # type: ignore[method-assign]
+ manager._find_opencode_serve_pids = lambda port: [222] # type: ignore[method-assign]
+
+ def _write_pid_file(
+ pid,
+ *,
+ caller_context_path=SERVER_MODULE._USE_CURRENT_CALLER_CONTEXT_PATH,
+ owner_pid=SERVER_MODULE._CURRENT_OWNER_PID,
+ ):
+ writes.append((pid, caller_context_path, owner_pid))
+ pid_info.clear()
+ pid_info.update({"pid": pid, "port": 4096})
+ if isinstance(caller_context_path, str) and caller_context_path:
+ pid_info["caller_context_path"] = caller_context_path
+
+ manager._write_pid_file = _write_pid_file # type: ignore[method-assign]
+
+ await manager._cleanup_orphaned_managed_server()
+
+ self.assertEqual(writes, [(222, None, None)])
+ self.assertNotIn("caller_context_path", pid_info)
+
+ async def test_ensure_running_rejects_unmanaged_healthy_server(self):
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]
+ manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
+ manager._start_server = AsyncMock() # type: ignore[method-assign]
+ manager._read_pid_file = lambda: None # type: ignore[method-assign]
+ manager._write_pid_file = lambda pid: self.fail("unmanaged server must not be adopted as Avibe-managed") # type: ignore[method-assign]
+
+ with patch.object(
+ SERVER_MODULE,
+ "ensure_plugin_installed",
+ return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),
+ ):
+ with self.assertRaisesRegex(RuntimeError, "not managed by Avibe"):
+ await manager.ensure_running()
+
+ manager._restart_for_auth_refresh_locked.assert_not_awaited()
+ manager._start_server.assert_not_awaited()
+
async def test_prompt_async_percent_encodes_directory_header(self):
manager = OpenCodeServerManager(binary="opencode", port=4096)
fake_session = _FakeSession()
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index bb7b73979..b4b5e350c 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -336,7 +336,9 @@ 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("Use `vibe agent run --async ...` when one Agent delegates work", prompt)
+ self.assertIn("Avibe injects this Session as the default async callback target", prompt)
+ self.assertIn("Pass `--no-callback` only when you intentionally want no automatic follow-up", prompt)
self.assertIn("final result text should return to this caller Session", prompt)
self.assertIn("vibe agent run --fork-session <source-session-id> --message ...", prompt)
self.assertIn("Forks keep the source Session backend", prompt)
diff --git a/vibe/cli.py b/vibe/cli.py
index 23e3275d0..ce0ae725a 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -35,6 +35,7 @@ from core.scheduled_tasks import (
resolve_session_id_target,
session_anchor_for_target,
)
+from core.caller_context import caller_context_from_env
from core.vibe_agents import VibeAgent, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
from core.watches import (
DEFAULT_RETRY_EXIT_CODE,
@@ -332,8 +333,8 @@ def _hook_send_examples_text() -> str:
`--message` and `--message-file` provide the one-shot async user message that will be queued immediately.
Examples:
- vibe agent run --async --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
- vibe agent run --async --session-id sesk8m4q2p7x --message 'Share the benchmark result.'
+ vibe agent run --async --session-id sesk8m4q2p7x --no-callback --message 'The export finished. Share the summary.'
+ vibe agent run --async --session-id sesk8m4q2p7x --callback-session-id sescaller123 --message 'Share the benchmark result.'
"""
)
@@ -642,8 +643,8 @@ def _agent_run_examples_text() -> str:
Examples:
vibe 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 --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'
+ vibe agent run --async --session-id sesk8m4q2p7x --no-callback --message 'The export finished. Share the summary.'
+ vibe agent run --async --fork-session sesk8m4q2p7x --callback-session-id sescaller123 --message 'Explore this alternate fix from the current context.'
vibe agent run --fork-session sesk8m4q2p7x --agent reviewer --model gpt-5.4 --reasoning-effort high --message 'Review the forked context.'
"""
)
@@ -1674,6 +1675,7 @@ def _wait_for_watch_startup(
def cmd_task_add(args):
try:
+ caller_context = caller_context_from_env()
schedule_type = "cron" if args.cron else "at"
session_policy = _validate_definition_session_policy(
args,
@@ -1749,6 +1751,7 @@ def cmd_task_add(args):
session_policy=session_policy,
cron=args.cron,
timezone_name=timezone_name,
+ metadata=_definition_creation_metadata_from_caller(caller_context),
)
else:
try:
@@ -1774,6 +1777,7 @@ def cmd_task_add(args):
session_policy=session_policy,
run_at=run_at,
timezone_name=timezone_name,
+ metadata=_definition_creation_metadata_from_caller(caller_context),
)
warnings = _collect_target_warnings(session_target, delivery_target)
task_payload = _task_payload(task)
@@ -2590,6 +2594,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 bool(getattr(args, "no_callback", False)):
+ raise TaskCliError(
+ "use either --callback-session-id or --no-callback, not both",
+ code="conflicting_callback_policy",
+ hint="Pass --callback-session-id to receive a follow-up, or --no-callback to intentionally inspect the run later.",
+ 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",
@@ -2597,6 +2608,13 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:
hint="Callback delivery happens after an asynchronous run completes.",
help_command=help_command,
)
+ if bool(getattr(args, "no_callback", False)) and not bool(getattr(args, "async_run", False)):
+ raise TaskCliError(
+ "--no-callback requires --async",
+ code="no_callback_requires_async",
+ hint="Only asynchronous runs need an explicit callback or no-callback policy.",
+ help_command=help_command,
+ )
if fork_session and (session_id or create_session or create_per_run):
raise TaskCliError(
"use --fork-session without --session-id or session creation flags",
@@ -2787,7 +2805,84 @@ def _resolve_run_cwd(args, *, session_policy: str, help_command: str) -> Optiona
return os.getcwd()
-def _reserve_cli_session(*, agent, deliver_key: Optional[str], workdir: Optional[str] = None) -> str:
+def _session_creation_metadata_from_caller(caller_context) -> dict:
+ if caller_context is None:
+ return {}
+ return {
+ "created_by": {
+ "kind": "caller_context",
+ "caller": caller_context.to_metadata(),
+ }
+ }
+
+
+def _definition_creation_metadata_from_caller(caller_context) -> dict:
+ return _session_creation_metadata_from_caller(caller_context)
+
+
+def _agent_run_source_from_caller(caller_context) -> tuple[str, Optional[str], Optional[str], dict]:
+ if caller_context is None:
+ return "cli", None, None, {}
+ metadata = {"caller_context": caller_context.to_metadata()}
+ return "agent", caller_context.session_id, caller_context.run_id, metadata
+
+
+def _resolve_async_callback_session_id(args, caller_context, *, target_session_id: Optional[str] = None):
+ explicit_callback = (getattr(args, "callback_session_id", None) or "").strip() or None
+ no_callback = bool(getattr(args, "no_callback", False))
+ if not bool(getattr(args, "async_run", False)):
+ return explicit_callback, None
+ if explicit_callback:
+ return explicit_callback, None
+ if no_callback:
+ return None, {
+ "code": "async_run_without_callback",
+ "message": (
+ "Started async Agent Run without a callback. This run will not post its final result back into a "
+ "Session automatically. Track it with `vibe runs show <run-id>` or by polling/listing runs for the "
+ "target Session. To receive a follow-up message next time, use `--callback-session-id <session-id>` "
+ "or run from a resolved caller context so Avibe can default the callback to the current Session."
+ ),
+ }
+ if caller_context is not None:
+ caller_session_id = caller_context.session_id
+ if target_session_id and target_session_id == caller_session_id:
+ raise TaskCliError(
+ "This async Agent Run targets the caller Session itself, so Avibe cannot safely default a callback.",
+ code="self_callback_requires_explicit_policy",
+ hint=(
+ "Pass --no-callback when continuing the same Session asynchronously, or pass "
+ "--callback-session-id <session-id> to send the final result to a different caller Session. "
+ "Default callbacks are only inferred when the delegated run targets a different Session."
+ ),
+ help_command="vibe agent run --help",
+ )
+ return caller_context.session_id, {
+ "code": "callback_defaulted_to_caller_session",
+ "message": "Async callback defaulted to the caller Session from AVIBE_SESSION_ID.",
+ "callback_session_id": caller_session_id,
+ }
+ raise TaskCliError(
+ "This async Agent Run has no callback target.",
+ code="missing_async_callback",
+ hint=(
+ "Pass --callback-session-id <session-id> to send the final result back to a specific Agent Session, "
+ "or pass --no-callback to run without an automatic follow-up and inspect the result later with "
+ "`vibe runs show <run-id>` or by polling/listing runs for the target Session. "
+ "`--callback-session-id` identifies the Session that should receive the delegated run's final result; "
+ "when Avibe can resolve the caller context, this defaults to the current caller Session."
+ ),
+ help_command="vibe agent run --help",
+ )
+
+
+def _reserve_cli_session(
+ *,
+ agent,
+ deliver_key: Optional[str],
+ workdir: Optional[str] = None,
+ metadata: Optional[dict] = None,
+) -> str:
# Route through ``core.services.sessions`` so the CLI shares the same
# business API as the UI server and the future N3 internal endpoint;
# see docs/plans/workbench-dispatch-architecture.md §6 (C2).
@@ -2805,6 +2900,7 @@ def _reserve_cli_session(*, agent, deliver_key: Optional[str], workdir: Optional
model=agent.model,
reasoning_effort=agent.reasoning_effort,
workdir=workdir,
+ metadata=metadata,
)
else:
platform = _primary_platform()
@@ -2818,6 +2914,7 @@ def _reserve_cli_session(*, agent, deliver_key: Optional[str], workdir: Optional
model=agent.model,
reasoning_effort=agent.reasoning_effort,
workdir=workdir,
+ metadata=metadata,
)
if not session_id:
raise TaskCliError(
@@ -2893,6 +2990,7 @@ def _reserve_definition_session(*, agent_name: Optional[str], deliver_key: str,
def cmd_agent_run(args):
try:
+ caller_context = caller_context_from_env()
message = _resolve_message_input(
args,
help_command="vibe agent run --help",
@@ -2926,10 +3024,42 @@ def cmd_agent_run(args):
run_cwd = _resolve_run_cwd(args, session_policy=session_policy, help_command="vibe agent run --help")
agent = _agent_store().require_enabled(agent_name) if agent_name else None
fork_result = None
+ session_metadata = _session_creation_metadata_from_caller(caller_context)
+ if session_policy in {"existing", "fork"} and session_id:
+ target = resolve_session_id_target(session_id)
+ session_key = target.session_key.to_key()
+ agent = _resolve_agent_for_target(
+ agent_name=agent_name or None,
+ session_id=session_id,
+ session_key=session_key,
+ help_command="vibe agent run --help",
+ )
+ if session_policy == "existing" and (args.post_to or args.deliver_key):
+ _validate_delivery_args(
+ session_id=session_id,
+ session_key=session_key,
+ post_to=args.post_to,
+ deliver_key=args.deliver_key,
+ help_command="vibe agent run --help",
+ )
+ elif session_policy == "create" and args.deliver_key:
+ _parse_validated_session_key(args.deliver_key, help_command="vibe agent run --help")
+ callback_session_id, callback_notice = _resolve_async_callback_session_id(
+ args,
+ caller_context,
+ target_session_id=session_id,
+ )
+ if callback_session_id:
+ resolve_session_id_target(callback_session_id)
if session_policy == "create":
- session_id = _reserve_cli_session(agent=agent, deliver_key=args.deliver_key, workdir=run_cwd)
+ session_id = _reserve_cli_session(
+ agent=agent,
+ deliver_key=args.deliver_key,
+ workdir=run_cwd,
+ metadata=session_metadata,
+ )
elif session_policy == "none":
- session_id = _reserve_cli_session(agent=agent, deliver_key=None, workdir=run_cwd)
+ session_id = _reserve_cli_session(agent=agent, deliver_key=None, workdir=run_cwd, metadata=session_metadata)
elif session_policy == "fork":
fork_result = _reserve_forked_cli_session(
source_session_id=(args.fork_session or "").strip(),
@@ -2940,7 +3070,7 @@ def cmd_agent_run(args):
session_id = fork_result.session_id
if agent_name:
agent = _agent_store().require_enabled(agent_name)
- if session_id:
+ if session_id and not session_key:
target = resolve_session_id_target(session_id)
session_key = target.session_key.to_key()
agent = _resolve_agent_for_target(
@@ -2949,7 +3079,9 @@ def cmd_agent_run(args):
session_key=session_key,
help_command="vibe agent run --help",
)
- if session_policy != "none" or args.post_to or args.deliver_key:
+ if (session_policy in {"create", "none"} or fork_result) and (
+ session_policy != "none" or args.post_to or args.deliver_key
+ ):
_validate_delivery_args(
session_id=session_id,
session_key=session_key,
@@ -2957,9 +3089,12 @@ 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)
+ source_kind, source_actor, parent_run_id, provenance_metadata = _agent_run_source_from_caller(caller_context)
+ if fork_result:
+ provenance_metadata = {
+ **provenance_metadata,
+ "session_fork": fork_result.fork.to_metadata(),
+ }
request_store = _task_request_store()
request = request_store.enqueue_agent_run(
agent_name=agent.name if agent else None,
@@ -2975,12 +3110,11 @@ def cmd_agent_run(args):
post_to=args.post_to,
deliver_key=args.deliver_key,
message=message,
+ source_kind=source_kind,
+ source_actor=source_actor,
+ parent_run_id=parent_run_id,
callback_session_id=callback_session_id,
- metadata={
- "session_fork": fork_result.fork.to_metadata(),
- }
- if fork_result
- else None,
+ metadata=provenance_metadata or None,
)
payload = {
"accepted": True,
@@ -2993,6 +3127,8 @@ def cmd_agent_run(args):
"deliver_key": args.deliver_key,
"callback_session_id": callback_session_id,
"async": bool(args.async_run),
+ "caller_context": caller_context.to_metadata() if caller_context else None,
+ "callback_notice": callback_notice,
"run": {
"id": request.id,
"status": "queued",
@@ -3000,6 +3136,9 @@ def cmd_agent_run(args):
"agent_name": agent.name if agent else None,
"session_id": session_id,
"callback_session_id": callback_session_id,
+ "source_kind": source_kind,
+ "source_actor": source_actor,
+ "parent_run_id": parent_run_id,
},
}
if fork_result:
@@ -4053,6 +4192,7 @@ def cmd_vault_key_import(args):
def cmd_watch_add(args):
try:
+ caller_context = caller_context_from_env()
session_policy = _validate_definition_session_policy(
args,
schedule_type="watch",
@@ -4123,6 +4263,7 @@ def cmd_watch_add(args):
deliver_key=args.deliver_key,
agent_name=agent_name,
session_policy=session_policy,
+ metadata=_definition_creation_metadata_from_caller(caller_context),
)
runtime_store = _watch_runtime_store()
watch, runtime_entry = _wait_for_watch_startup(store, runtime_store, watch.id)
@@ -6750,6 +6891,11 @@ def build_parser():
)
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(
+ "--no-callback",
+ action="store_true",
+ help="For async runs, intentionally skip automatic callback delivery and inspect the run later.",
+ )
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)