Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(debug): preview session model requests read-only (#3104)
Call White8f1f3b2253b9
diff --git a/core/agent_session_context.py b/core/agent_session_context.pyindex 945bc4bc4..e7110ef13 100644--- a/core/agent_session_context.py+++ b/core/agent_session_context.py@@ -2,7 +2,26 @@from __future__ import annotations-from typing import Any, Optional+from typing import Any, Mapping, Optional+++def session_model_settings(+ target: Mapping[str, Any] | None,+ *,+ fallback_model: str | None = None,+ fallback_reasoning_effort: str | None = None,+) -> tuple[str | None, str | None, set[str]]:+ """Resolve a Session's settings without materializing them; explicit null is a pin, not inheritance."""+ from storage.session_reclaim import explicit_override_names++ target = target or {}+ explicit = explicit_override_names(target.get("metadata"))+ model = target.get("model") if "model" in explicit else target.get("model") or fallback_model+ effort = (+ target.get("reasoning_effort") if "reasoning_effort" in explicit+ else target.get("reasoning_effort") or fallback_reasoning_effort+ )+ return model, effort, explicitdef resolve_context_agent_session_target(context: Any) -> Optional[dict[str, Any]]:diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 6cd80cfb5..2812dde7b 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -440,19 +440,16 @@ class MessageHandler(BaseHandler):# the VibeAgent's own defaults — otherwise the header's model /# effort picker would be cosmetic: persisted and displayed but never# actually routed to the backend.- session_target_model = (- session_target.get("model") if isinstance(session_target, dict) else None- ) or resolved_target.get("model")- session_target_reasoning = (- session_target.get("reasoning_effort") if isinstance(session_target, dict) else None- ) or resolved_target.get("reasoning_effort")- # The model / effort this turn ACTUALLY runs with — the same- # precedence the request is built on below.- effective_model = session_target_model or scope_model_override or (- vibe_agent.model if vibe_agent else None- )- effective_reasoning_effort = session_target_reasoning or scope_reasoning_override or (- vibe_agent.reasoning_effort if vibe_agent else None+ from core.agent_session_context import session_model_settings++ effective_model, effective_reasoning_effort, explicit_overrides = session_model_settings(+ session_target if isinstance(session_target, dict) else None,+ fallback_model=resolved_target.get("model") or scope_model_override or (+ vibe_agent.model if vibe_agent else None+ ),+ fallback_reasoning_effort=resolved_target.get("reasoning_effort") or scope_reasoning_override or (+ vibe_agent.reasoning_effort if vibe_agent else None+ ),)materialized_agent_identity = bool(vibe_agent@@ -460,23 +457,6 @@ class MessageHandler(BaseHandler):and not session_target.get("agent_id")and not session_target.get("agent_name"))- # A session may pin a setting to NOTHING on purpose. The cascade above- # cannot express that: every `or` reads NULL as "inherit", which is the- # correct reading for the whole existing table and the WRONG one for a- # preserved `create_once` rebind, whose whole point is that the session- # it replaced pinned no model and must keep pinning none (D3). Only- # sessions carrying the explicit-override marker are re-read here, so- # the global meaning of NULL is untouched -- reinterpreting it would- # silently re-route every session that is merely inheriting.- explicit_overrides: set[str] = set()- if isinstance(session_target, dict):- from storage.session_reclaim import explicit_override_names-- explicit_overrides = explicit_override_names(session_target.get("metadata"))- if "model" in explicit_overrides:- effective_model = session_target.get("model")- if "reasoning_effort" in explicit_overrides:- effective_reasoning_effort = session_target.get("reasoning_effort")# Materialize the resolved route into EMPTY Workbench session# columns at turn start. A session created on an inherited default# carries NULLs (dispatch resolves the live Agent default); withoutdiff --git a/core/handlers/request_preview.py b/core/handlers/request_preview.pynew file mode 100644index 000000000..8c461414d--- /dev/null+++ b/core/handlers/request_preview.py@@ -0,0 +1,179 @@+"""Owner-only, private-IPC Session request reconstruction. Never a dispatch entry point."""+from __future__ import annotations++import asyncio+import json+import os+import shutil+import stat+import tempfile+from dataclasses import asdict+from pathlib import Path+from typing import Any, Mapping++from config import paths+from core.agent_core.agent.preview import RequestPreview+from core.agent_session_context import session_model_settings+from core.private_fs import ensure_private_directory, is_private+from modules.agents.base import AgentRequest+from storage.resource_access_service import (+ RESOURCE_USER_CONTEXT_METADATA_KEY,+ metadata_with_resource_user_context,+ resource_user_context_from_metadata,+)+from vibe.authorization import (+ AuthorizationContext,+ InstanceAuthorizationError,+ instance_owner_context,+ require_instance_role,+)+++def preview_caller() -> dict[str, Any]:+ """Carry this CLI invocation's authority, not a daemon's or the target Session's."""+ authority = require_instance_role(None, "owner")+ if not authority.is_remote:+ return {"kind": "local"}+ metadata = metadata_with_resource_user_context({}, authority)+ return {"kind": "remote", RESOURCE_USER_CONTEXT_METADATA_KEY: metadata[RESOURCE_USER_CONTEXT_METADATA_KEY]}+++def require_preview_owner(caller: object) -> AuthorizationContext:+ """Recheck mandatory provenance across IPC. Missing/invalid remote provenance never means local."""+ if caller == {"kind": "local"}:+ # The existing host-local Owner path, behind owner-private control IPC.+ return require_instance_role(instance_owner_context(), "owner")+ if not isinstance(caller, dict) or set(caller) != {"kind", RESOURCE_USER_CONTEXT_METADATA_KEY}:+ raise InstanceAuthorizationError("owner")+ if caller.get("kind") != "remote" or not isinstance(caller.get(RESOURCE_USER_CONTEXT_METADATA_KEY), dict):+ raise InstanceAuthorizationError("owner")+ authority = resource_user_context_from_metadata(caller)+ if authority is None:+ raise InstanceAuthorizationError("owner")+ return require_instance_role(authority, "owner")+++def build_preview_request(controller: Any, context: Any) -> AgentRequest:+ """Read the same durable Agent and setting defaults as dispatch, without materializing any of them."""+ from sqlalchemy import select++ from core.services.agent_run_target import session_project_base_from_row+ from storage.models import agent_sessions, scope_settings++ target = (context.platform_specific or {}).get("agent_session_target")+ if not isinstance(target, dict) or target.get("agent_backend") != "vibey":+ raise ValueError("request_preview_requires_vibey")+ session_id = target["id"]+ agent = controller.resolve_vibe_agent_for_context(+ context, override_agent_id=target.get("agent_id"), override_agent_name=target.get("agent_name"), required=True,+ )+ if agent is None or agent.backend != "vibey":+ raise ValueError("request_preview_requires_vibey")+ cwd = target.get("workdir")+ cwd = os.path.abspath(os.path.expanduser(cwd)) if isinstance(cwd, str) and cwd else ""+ if not cwd or not Path(cwd).is_dir():+ # get_cwd()/resolve_agent_run_target() can create a missing workdir, even with create_session=False.+ raise ValueError("request_preview_workdir_unavailable")+ model, effort, explicit = session_model_settings(+ target, fallback_model=agent.model, fallback_reasoning_effort=agent.reasoning_effort,+ )+ project_base = None+ from storage.db import get_cached_sqlite_engine++ with get_cached_sqlite_engine().connect() as conn:+ row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == session_id)).mappings().one_or_none()+ if row is None:+ raise ValueError("request_preview_session_missing")+ row = dict(row)+ row["_scope_workdir"] = conn.execute(+ select(scope_settings.c.workdir).where(scope_settings.c.scope_id == row.get("scope_id"))+ ).scalar_one_or_none()+ project_base = session_project_base_from_row(row, cwd)+ # Bind only this detached context, so shared Skill discovery uses the production project boundary.+ context.platform_specific["agent_run_target"] = {**target, "agent_session_id": session_id, "project_base": project_base}+ return AgentRequest(+ context=context, message="", user_message="", working_path=cwd,+ base_session_id=session_id, composite_session_id=session_id, session_key="",+ vibe_agent_id=agent.id, vibe_agent_name=agent.name, vibe_agent_backend=agent.backend,+ vibe_agent_model=model, vibe_agent_reasoning_effort=effort,+ vibe_agent_model_explicit="model" in explicit, vibe_agent_reasoning_effort_explicit="reasoning_effort" in explicit,+ vibe_agent_system_prompt=agent.system_prompt,+ )+++def _private_write(path: Path, content: bytes) -> None:+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)+ fd = os.open(path, flags, 0o600)+ with os.fdopen(fd, "wb") as stream:+ if not is_private(path, os.fstat(stream.fileno()).st_mode, fd=stream.fileno()):+ raise PermissionError("request_preview_artifact_not_private")+ stream.write(content)+++def export_preview(preview: RequestPreview, *, requested_context_seq: int | None) -> dict[str, Any]:+ """Only this artifact writer has effects. Its return value is safe for CLI stdout and IPC."""+ status = (+ "ready" if preview.status == "ready" else+ "transition_required" if preview.status == "needs_context_transition" else "not_model_ready"+ )+ summary: dict[str, Any] = {+ "kind": "request_preview", "status": status,+ "reason": preview.status, "mode": "current_config_reconstruction", "auth": "unbound",+ "session_id": preview.snapshot.session_id,+ "context_seq": preview.snapshot.context_seq, "requested_context_seq": requested_context_seq,+ "transition_required": preview.transition is not None,+ "missing_tool_results": preview.status == "pending_tools",+ "wire_prepared": preview.wire is not None,+ }+ if preview.transition is not None:+ summary["transition"] = preview.transition+ if preview.wire is not None:+ summary.update(body_bytes=len(preview.wire.body), body_sha256=preview.wire.body_sha256)+ from vibe import __version__++ manifest = {+ "schema_version": 1, "avibe_version": __version__, **summary,+ "limitations": [+ "Current configuration, not historical system/tools/route capture or a running Turn's volatile retry state.",+ "Unconsumed inputs are excluded; no new input or environment block is appended.",+ "Authentication and gateway routing are unbound; this artifact cannot be sent as-is.",+ ],+ }+ if preview.budget is not None:+ manifest["budget"] = asdict(preview.budget)+ if preview.request is not None:+ endpoint = preview.request.endpoint+ manifest["route"] = {"protocol": endpoint.protocol, "model": endpoint.model_id, "source_id": endpoint.source_id}+ # Never serialize ModelRequest, snapshot state, WireRequest headers/URL, or ProviderError text.+ root = paths.get_state_dir() / "request-previews"+ ensure_private_directory(root, repair=False)+ info = root.lstat()+ if stat.S_ISLNK(info.st_mode) or (hasattr(os, "getuid") and info.st_uid != os.getuid()):+ raise PermissionError("request_preview_artifact_not_private")+ directory = Path(tempfile.mkdtemp(prefix="preview-", dir=root))+ try:+ directory_mode = directory.lstat().st_mode+ if stat.S_ISLNK(directory_mode) or not stat.S_ISDIR(directory_mode) or not is_private(directory, directory_mode):+ raise PermissionError("request_preview_artifact_not_private")+ _private_write(directory / "manifest.json", (json.dumps(manifest, ensure_ascii=False, indent=2) + "\n").encode())+ if preview.wire is not None:+ _private_write(directory / "request.body.json", preview.wire.body)+ except BaseException:+ shutil.rmtree(directory)+ raise+ summary.update(artifact_dir=str(directory), manifest_path=str(directory / "manifest.json"))+ if preview.wire is not None:+ summary["request_body_path"] = str(directory / "request.body.json")+ return summary+++async def preview_session_request(controller: Any, context: Any, *, context_seq: int | None) -> Mapping[str, Any]:+ """The private controller boundary; caller authority must already be installed for this operation."""+ require_instance_role(None, "owner")+ request = await asyncio.to_thread(build_preview_request, controller, context)+ backend = getattr(getattr(controller, "agent_service", None), "agents", {}).get("vibey")+ if backend is None:+ raise ValueError("request_preview_backend_unavailable")+ session_id = (context.platform_specific or {})["agent_session_target"]["id"]+ preview = await backend.preview_request(session_id, request, context_seq=context_seq)+ return await asyncio.to_thread(export_preview, preview, requested_context_seq=context_seq)diff --git a/core/internal_server.py b/core/internal_server.pyindex b154743f2..2f16717c9 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -1263,6 +1263,37 @@ def create_app((FSM, Phase 1b). A reconnected Chat page asks this to restore working/Stop."""return manager.turn_state(session_id)+ @app.post("/internal/debug/request/preview")+ async def _request_preview(request: Request) -> Any:+ from core.handlers.request_preview import preview_session_request, require_preview_owner+ from vibe.authorization import InstanceAuthorizationError, invocation_authority++ try:+ payload = await _bounded_json_object(request, limit=32 * 1024)+ except _RequestBodyTooLarge:+ return JSONResponse({"error": "request_preview_payload_too_large"}, status_code=413)+ # Provenance is mandatory. An omitted caller must never inherit the controller's Owner identity.+ try:+ authority = await asyncio.to_thread(require_preview_owner, payload.get("caller"))+ except (InstanceAuthorizationError, ValueError, TypeError):+ return JSONResponse({"error": "instance_access_forbidden"}, status_code=403)+ session_id, cut = payload.get("session_id"), payload.get("context_seq")+ if (+ set(payload) != {"caller", "session_id", "context_seq"}+ or not isinstance(session_id, str) or not session_id.strip() or len(session_id) > 200+ or (cut is not None and (type(cut) is not int or cut < 0))+ ):+ return JSONResponse({"error": "request_preview_invalid_parameters"}, status_code=400)+ try:+ with invocation_authority(authority):+ context = await asyncio.to_thread(_build_session_context, session_id.strip())+ return await preview_session_request(controller, context, context_seq=cut)+ except InstanceAuthorizationError:+ return JSONResponse({"error": "instance_access_forbidden"}, status_code=403)+ except Exception:+ # Preparation failures may contain paths, prompts or signed provider content. Do not log or echo them.+ return JSONResponse({"error": "request_preview_failed"}, status_code=409)+@app.get("/internal/running-agents")async def _running_agents() -> Any:"""Read-only snapshot of currently-running agent instances across alldiff --git a/core/services/agent_run_target.py b/core/services/agent_run_target.pyindex d10a11954..be2e8e4d7 100644--- a/core/services/agent_run_target.py+++ b/core/services/agent_run_target.py@@ -13,7 +13,7 @@ import jsonimport osfrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Optional+from typing import Any, Mapping, Optionalfrom sqlalchemy import Engine, select, update@@ -719,7 +719,7 @@ def _target_from_session_row(session_anchor=str(row.get("session_anchor") or fallback_anchor),workdir=workdir,source=source,- project_base=_session_project_base(row, workdir),+ project_base=session_project_base_from_row(row, workdir),scope_id=_optional_str(row.get("scope_id")),scope_type=_optional_str(row.get("_scope_type")),agent_session_id=_optional_str(row.get("id")),@@ -788,7 +788,8 @@ def _project_base_for_workdir(workdir: str, candidate: Any) -> Optional[str]:return normalize_session_project_base(workdir, candidate)-def _session_project_base(row: dict[str, Any], workdir: str) -> Optional[str]:+def session_project_base_from_row(row: Mapping[str, Any], workdir: str) -> Optional[str]:+ """Read a Session's durable project boundary without resolving or creating its workdir."""try:metadata = json.loads(str(row.get("metadata_json") or "{}"))except (TypeError, ValueError):diff --git a/docs/plans/session-request-preview.md b/docs/plans/session-request-preview.mdnew file mode 100644index 000000000..6a09695f2--- /dev/null+++ b/docs/plans/session-request-preview.md@@ -0,0 +1,40 @@+# Session request preview++## Change contract++Add the Owner-only `vibe debug request preview --session-id ID [--context-seq N]` command over private controller IPC; do not expose a Web/API forwarding route. Existing CLI invocation authority, including remote Owner Agent callers, must be preserved and revalidated by the controller. Missing/malformed remote authority must not become local Owner authority.++The preview reconstructs a committed transcript prefix using current Agent/system/tools/Model Hub configuration. Production and preview share Agent construction, model/effort override semantics, and route description. A preview cannot dispatch work, resolve/activate a gateway credential, call a provider, execute a tool, consume input, settle a call, record an observation, or write Session state. Only owner-private diagnostic artifacts may be created. Context cut precedes projection. Report context transitions, pending tools, reconstruction limitations, and unbound authentication explicitly.++Output is a private artifact directory (POSIX 0700, files 0600; equivalent Windows owner-only ACLs). Standard output contains only bounded structural metadata and artifact paths, never the prompt, canonical history, opaque/signed provider content, or credentials. Body bytes use the merged Agent.dry_tick contract and its production provider wire encoder. No real-session probes or replay, no model-error root-cause changes, deployment, or release.++## Usage++```sh+vibe debug request preview --session-id SESSION_ID+vibe debug request preview --session-id SESSION_ID --context-seq 12+```++Requires a running local controller and an existing, unarchived Vibey Session. Both standalone host CLI and existing remote Owner Agent CLI invocations are supported; Viewer, Editor and Member invocations are refused. This command does not start a Session or consume its queue.++The command prints a JSON summary and paths below Avibe's configured state directory (`<state>/request-previews/preview-*/`). `manifest.json` describes the effective context cut, current-code reconstruction, unbound authentication, budget and readiness. A `ready` result also contains `request.body.json`: complete UTF-8 JSON bytes prepared by the production provider encoder, including private conversation and potentially opaque provider history. Keep that directory private and remove it manually when the diagnostic task is complete. No automatic retention or upload is added by this command.++`transition_required` means the loop would first clear results, checkpoint or relieve context; no body is exported. `not_model_ready` with `missing_tool_results: true` means a committed tool call has no result at that cut; the preview does not synthesize a completed execution. These are successful diagnostic results, not permission to send. Authentication, gateway turn routing and retries are deliberately not activated. Missing/disabled supply or unsupported Sessions fail safely without exposing a raw exception.++## Validation++- Owner-boundary tests reject lower-role and malformed IPC authority before reading a Session, while permitting the existing local and remote Owner paths.+- Adapter-boundary tests load real SQLite transcript/fork prefixes, compare production construction, fail on DML/session/run/tool/provider/observation/credential activation, and check explicit-null settings and blocked statuses.+- Router tests compare description with the activated production launch facts while proving description never allocates credentials or emits transitions.+- Artifact/CLI tests check permissions, no overwrite/symlink acceptance, safe output, and parser/admission classification.++Existing core dry-tick tests own request bytes and context-transition selection; integration tests exercise the new host/IPC/CLI boundaries instead of duplicating those algorithms.++## Known by design++- This is current-configuration reconstruction, not historical transport capture or a prediction of a running Turn's volatile retry state.+- Queued/unconsumed inputs are excluded; no fake input or environment block is appended.+- Pending client tool outcomes and required context transitions produce metadata only, not a sendable HTTP body.+- Authentication and gateway route activation remain unbound. The output must not be sent as-is.+- Private IPC is an OS-user trust boundary. Explicit caller provenance is mandatory in this new endpoint; remote snapshots are revalidated, never replaced by daemon authority. An explicit local declaration represents the existing standalone host Owner path, not remote anonymous fallback.+- PR #3103 independently adds model-request artifact capture and `list|show|export` capabilities. Debug replay with preview is a separate follow-up; reconcile parser changes only after #3103 merges.diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex 756055be5..499374333 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -839,14 +839,19 @@ class ModelHubRuntimeRouter:*,supply_channel: Literal["hub"] | None = None,) -> tuple[ModelHubConfig, ModelHubTurnResolution]:- resolution = resolve_model_hub_turn(- config,- backend,- requested_model,- now=self.service.now(),- unavailable_source_ids=self._unavailable_native_source_ids(config, backend),- supply_channel=supply_channel,- live_recovery=self.service.recovery_annotations(config),+ now = self.service.now()+ unavailable_source_ids = self._unavailable_native_source_ids(config, backend)+ live_recovery = self.service.recovery_annotations(config)+ resolution = await asyncio.to_thread(+ lambda: resolve_model_hub_turn(+ config,+ backend,+ requested_model,+ now=now,+ unavailable_source_ids=unavailable_source_ids,+ supply_channel=supply_channel,+ live_recovery=live_recovery,+ ))waitable = resolution.self_healing_hops("hub")if self.turn_gateway is not None and resolution.source is None and waitable:@@ -1201,6 +1206,61 @@ class ModelHubRuntimeRouter:config = config if config is not None else self.service.store.load()return cast(TurnMode, config.agents[backend].mode)+ def _describe_launch(+ self, config: ModelHubConfig, backend: BackendName, requested_model: str,+ resolution: ModelHubTurnResolution,+ ) -> ModelHubLaunch:+ """Route facts only, shared by production activation and read-only diagnostics."""+ source = resolution.source+ if source is None:+ raise ModelHubError("mapping_target_unavailable", status=409)+ model = next((model for model in config.agents[backend].models if model.id == requested_model), None)+ hub = source.supply_channel != "native_cli"+ return ModelHubLaunch(+ backend=backend, channel="hub" if hub else "native_cli",+ requested_model=requested_model, target_model=resolution.target_model,+ runtime_model=resolution.target_model, source_id=source.id,+ context_window=model.context_window if model is not None else None,+ max_output_tokens=model.max_output_tokens if model is not None else None,+ supports_tools=model.supports_tools if model is not None else None,+ supports_reasoning=model.supports_reasoning if model is not None else None,+ reasoning_efforts=(+ tuple(model.reasoning_efforts) if model is not None and model.supports_reasoning is not False else ()+ ),+ protocol=source.protocol if hub else None,+ provider=source.vendor if hub else None,+ cache_ttl=resolution.cache_ttl if hub else None,+ cache_ttl_wire=resolution.cache_ttl_wire if hub else False,+ supports_images=(+ "image" in model.input_modalities if hub and model is not None and model.input_modalities else None+ ),+ source_identity=identity_digest(source) if hub else None,+ context_price_steps=(self.service.context_price_steps(resolution.target_model) if backend == "vibey" else ()),+ )++ async def describe_vibey_request(self, requested_model: str) -> ModelHubLaunch:+ """Describe current supply without activating a gateway, issuing credentials or emitting events.++ The inert address and token are explicit unbound placeholders for wire preparation, not credentials.+ Unlike resolve(), an unavailable route does not update supply state or hold a Session's input.+ """+ config = await asyncio.to_thread(self.snapshot)+ if config.agents["vibey"].mode != "hub" or self.turn_gateway is None:+ raise ModelHubError("mapping_target_unavailable", status=409)+ requested_model = str(requested_model or "").strip()+ config, resolution = await self._resolve_turn(config, "vibey", requested_model)+ if resolution.source is None or resolution.source.supply_channel != "hub":+ raise ModelHubError("mapping_target_unavailable", status=409)+ description = self._describe_launch(config, "vibey", requested_model, resolution)+ frozen = await asyncio.to_thread(self.service.freeze_turn_hosted_tools, config)+ hosted = await asyncio.to_thread(+ self.service.hosted_tools_for_hop, resolution.source, resolution.target_model, frozen,+ )+ return replace(+ description, hosted_tools=hosted,+ gateway_base_url="http://request-preview.invalid/vibey", gateway_token="auth-unbound",+ )+async def resolve(self,backend: BackendName,@@ -1240,32 +1300,7 @@ class ModelHubRuntimeRouter:target_model = resolution.target_modelsource = resolution.source- backend_model = next(- (- model- for model in config.agents[backend].models- if model.id == requested_model- ),- None,- )- context_window = (- backend_model.context_window if backend_model is not None else None- )- max_output_tokens = (- backend_model.max_output_tokens if backend_model is not None else None- )- supports_tools = (- backend_model.supports_tools if backend_model is not None else None- )- supports_reasoning = (- backend_model.supports_reasoning if backend_model is not None else None- )- reasoning_efforts = (- tuple(backend_model.reasoning_efforts)- if backend_model is not None- and backend_model.supports_reasoning is not False- else ()- )+ description = self._describe_launch(config, backend, requested_model, resolution)self._last_supply_state[(backend, requested_model)] = ("ok", None)if source.supply_channel == "native_cli":if self.service.revocations.list():@@ -1274,21 +1309,9 @@ class ModelHubRuntimeRouter:except ModelHubError:# Native launch is independent; the durable journal retries later.pass- launch = ModelHubLaunch(- backend=backend,- channel="native_cli",- requested_model=requested_model,- target_model=target_model,- runtime_model=target_model,- source_id=source.id,- context_window=context_window,- max_output_tokens=max_output_tokens,- supports_tools=supports_tools,- supports_reasoning=supports_reasoning,- reasoning_efforts=reasoning_efforts,- settlement_generation=self.service._reserve_settlement_generation(- source.id- ),+ launch = replace(+ description,+ settlement_generation=self.service._reserve_settlement_generation(source.id),)if self.turn_gateway is not None:self.turn_gateway.correlation.begin_native_attempt(@@ -1366,35 +1389,13 @@ class ModelHubRuntimeRouter:elif self.turn_gateway is not None and backend == "vibey" and str(turn_id or "").strip():# Vibey names its turn on every gateway request (HopResolution.request_headers).request_metadata = {VIBEY_TURN_HEADER: str(turn_id).strip()}- launch = ModelHubLaunch(- backend=backend,- channel="hub",- requested_model=requested_model,- target_model=target_model,+ launch = replace(+ description,runtime_model=runtime_model,- source_id=source.id,gateway_base_url=gateway_base_url,gateway_token=gateway_token,gateway_request_metadata=request_metadata,- context_window=context_window,- max_output_tokens=max_output_tokens,- supports_tools=supports_tools,- supports_reasoning=supports_reasoning,- reasoning_efforts=reasoning_efforts,- protocol=source.protocol,- provider=source.vendor,- cache_ttl=resolution.cache_ttl,- cache_ttl_wire=resolution.cache_ttl_wire,- supports_images=(- "image" in backend_model.input_modalities- if backend_model is not None and backend_model.input_modalities- else None- ),hosted_tools=hosted_tools,- source_identity=identity,- context_price_steps=(- self.service.context_price_steps(target_model) if backend == "vibey" else ()- ),)self._emit_transition(launch, config)return launchdiff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 994f0c854..f6f549967 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -57,6 +57,7 @@ from core.agent_core.agent.events import ()from core.agent_core.agent.hooks import AgentInputfrom core.agent_core.agent.loop import Agent+from core.agent_core.agent.preview import RequestPreviewfrom core.agent_core.agent.models import ModelSelection, RetryPolicyfrom core.agent_core.agent.recovery import settle_open_callsfrom core.agent_core.harness.context import ContextConfig@@ -951,17 +952,32 @@ class VibeyAgent(BaseAgent):builtin_agent: bool,instructions: str = "",) -> None:- """The Turn's loop, over its router, tools, system prompt, and the environment its commands run in.+ turn.agent = self._build_agent(+ turn.request, turn.session_id, turn.router, cwd, sections, environment,+ builtin_agent=builtin_agent, instructions=instructions,+ )+ turn.cwd = cwd++ def _build_agent(+ self,+ request: AgentRequest,+ session_id: str,+ router: HubModelRouter,+ cwd: str,+ sections: str,+ environment: Mapping[str, str],+ *,+ builtin_agent: bool,+ instructions: str = "",+ ) -> Agent:+ """Production construction shared with detached previews; this does not register or start a Turn.- The bash rule names ``rg`` only when that environment's PATH finds it. That PATH is the service's- PATH plus the installed managed tools, which change only on an install or upgrade, so a Session's- Turns keep one system prompt, which changes only when ripgrep's availability or an instruction file does.+ The bash rule names ``rg`` only when the command environment's PATH finds it."""- request, session_id = turn.request, turn.session_idsuite = self._tools()agent = Agent(session_id=session_id,- models=turn.router,+ models=router,tools=(),hooks=(),store=self.store,@@ -980,7 +996,7 @@ class VibeyAgent(BaseAgent):# Job-backed tools receive the loop's tracking wrapper, so Stop kills foreground commands.tools = mark_skill_loads((- *hosted_tools(turn.router, self._gateway_client, self.media, language=self._language),+ *hosted_tools(router, self._gateway_client, self.media, language=self._language),*suite.create_tools(agent.jobs, self.media.image_sink(session_id)),))@@ -993,7 +1009,34 @@ class VibeyAgent(BaseAgent):rg=finds_rg,project_context=instructions,)- turn.agent, turn.cwd = agent, cwd+ return agent++ async def preview_request(+ self, session_id: str, request: AgentRequest, *, context_seq: int | None = None,+ ) -> RequestPreview:+ """Reconstruct from current configuration without binding a runtime, consuming input, or activating supply."""+ model = request.subagent_model or request.vibe_agent_model+ if not model:+ raise ValueError("request_preview_model_unset")+ launch = await self.controller.model_hub_runtime.describe_vibey_request(model)+ selected = budgeted(selection_from_hop(launch.to_hop_resolution()))++ async def no_resolve() -> ModelSelection:+ raise RuntimeError("A preview must not resolve a model route")++ router = HubModelRouter(no_resolve, self._providers, first=selected)+ cwd = request.working_path+ sections, _ = await self._avibe_sections(request, cwd)+ builtin_agent = await asyncio.to_thread(self._is_builtin_agent, request)+ environment = await asyncio.to_thread(self._turn_environment, request, cwd)+ instructions = await asyncio.to_thread(_project_instructions, cwd)+ agent = self._build_agent(+ request, session_id, router, cwd, sections, environment,+ builtin_agent=builtin_agent, instructions=instructions,+ )+ return await agent.dry_tick(+ selected=selected, context_seq=context_seq, gateway=True, media_loader=self.media,+ )async def _on_event(self, run: _Run, event: AgentEvent) -> None:if isinstance(event, MessageCommitted):diff --git a/tests/test_session_request_preview.py b/tests/test_session_request_preview.pynew file mode 100644index 000000000..513706b7a--- /dev/null+++ b/tests/test_session_request_preview.py@@ -0,0 +1,338 @@+"""Session preview's owning boundaries: real transcript/config reads, no execution, safe private output.++Core dry-tick tests already cover provider encoding and transition decisions. These tests catch+integration accidentally entering dispatch, activating supply, losing caller authority, or leaking+request data through the IPC/CLI result; those risks are outside the core's dependencies.+"""+from __future__ import annotations++import json+import os+from copy import deepcopy+from dataclasses import replace+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock++import httpx+import pytest+from sqlalchemy import event, select, update+from sqlalchemy.engine import Engine++from config import paths+from core.agent_core.agent.loop import Agent+from core.agent_core.messages import ToolCallBlock, UserMessage, text+from core.handlers import request_preview+from core.internal_server import _build_session_context, create_app+from core.vibe_agents import VibeAgentStore+from modules.agents.model_hub import ModelHubRuntimeRouter+from storage import messages_service+from storage.models import agent_sessions, messages, scope_settings+from tests.agent_core.fakes import assistant+from tests.test_internal_server import _build_controller_double+from tests.test_model_hub_l3 import _source+from tests.test_model_hub_vibey_consumer import _vibey_service+from tests.test_vibey_agent import SESSION, _Harness, _insert_session, engine, session # noqa: F401+from vibe import cli, internal_client+from vibe.authorization import AuthorizationContext, invocation_authority+++def forbidden(*args, **kwargs):+ raise AssertionError("preview entered an effectful dependency")+++def preview_host(engine, session, tmp_path, monkeypatch):+ harness = _Harness(engine, tmp_path, "avibe", [])+ request = harness.request("sensitive committed input")+ harness.controller._native_start(request.context)+ # The ordinary adapter writes the first input; all assertions begin after fixture construction.+ store = VibeAgentStore()+ agent = store.create(name="preview-agent", backend="vibey", model="menu-alias", system_prompt="private agent instructions")+ with engine.begin() as conn:+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == SESSION).values(+ agent_id=agent.id, agent_name=agent.name, model="menu-alias", workdir=str(tmp_path),+ metadata_json=json.dumps({"project_base": str(tmp_path)}),+ ))+ controller = _build_controller_double()+ controller.config = harness.controller.config+ controller.vibe_agent_store = store+ controller.resolve_vibe_agent_for_context = lambda *args, **kwargs: store.require_reference_by_id(agent.id)+ source = _source("src_preview01", "Preview fixture")+ service = _vibey_service(tmp_path / "hub", [source])+ service.store.config.agents["vibey"].models[0].supports_tools = True+ router = ModelHubRuntimeRouter(service=service, turn_gateway=SimpleNamespace())+ controller.model_hub_runtime = router+ controller.agent_service.agents = {"vibey": harness.agent}+ harness.agent.controller = controller+ app = create_app(controller)+ yield SimpleNamespace(+ harness=harness, controller=controller, app=app, request=request, router=router, service=service, store=store,+ )+ store.close()+++async def commit_input(host):+ await host.harness.agent.store.consume_input(+ SESSION, host.request.context.platform_specific["delivery_id"], UserMessage((text("sensitive committed input"),)),+ )+++def deny_effects(host, monkeypatch):+ for name in ("_preflight", "_resume", "_accept_native_start", "handle_message", "recover_runtime_state"):+ monkeypatch.setattr(host.harness.agent, name, forbidden)+ monkeypatch.setattr(host.harness.agent, "_providers", forbidden)+ monkeypatch.setattr(host.router, "resolve", forbidden)+ monkeypatch.setattr(host.router, "_gateway_credentials", forbidden)+ monkeypatch.setattr(host.router, "_emit_transition", forbidden)+ monkeypatch.setattr(Agent, "run", forbidden)+ monkeypatch.setattr(Agent, "resume", forbidden)+ monkeypatch.setattr("modules.agents.vibey.agent.accept_catalog", forbidden)++ def no_dml(conn, cursor, statement, parameters, context, executemany):+ assert statement.lstrip().split()[0].upper() not in {+ "INSERT", "UPDATE", "DELETE", "REPLACE", "CREATE", "ALTER", "DROP",+ }, "request preview wrote database state"++ event.listen(Engine, "before_cursor_execute", no_dml)+ return lambda: event.remove(Engine, "before_cursor_execute", no_dml)+++async def invoke(host, cut=None, caller=None):+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=host.app), base_url="http://internal") as client:+ return await client.post("/internal/debug/request/preview", json={+ "session_id": SESSION, "context_seq": cut, "caller": {"kind": "local"} if caller is None else caller,+ })+++async def test_real_session_preview_exports_only_committed_cut_without_any_execution(preview_host, engine, monkeypatch, tmp_path):+ host = preview_host+ await commit_input(host)+ await host.harness.agent.store.append_payload(SESSION, "agent_state", {"version": 1, "state": {"secret": "opaque state"}})+ await host.harness.agent.store.append_payload(SESSION, "replay_refusal", {+ "version": 1, "source_identity": "identity", "payloads": ["hosted"],+ })+ with engine.begin() as conn:+ # This is queued, not committed model context. Preview cannot admit it.+ queued = messages_service.append(conn, scope_id=None, session_id=SESSION, platform="avibe", author="user", text="queued secret")+ (tmp_path / "AGENTS.md").write_text("project instructions marker")+ before = deepcopy(host.router._last_supply_state)+ remove = deny_effects(host, monkeypatch)+ try:+ response = await invoke(host, 2)+ finally:+ remove()+ assert response.status_code == 200, response.text+ result = response.json()+ assert result["status"] == "ready" and result["mode"] == "current_config_reconstruction"+ assert result["auth"] == "unbound" and result["context_seq"] == 2+ assert all(secret not in response.text for secret in ("sensitive committed", "opaque state", "private agent", "queued secret"))+ body = Path(result["request_body_path"]).read_bytes()+ assert b"sensitive committed input" in body and b"private agent instructions" in body+ assert b"project instructions marker" in body and b"queued secret" not in body+ assert b"auth-unbound" not in body+ assert host.router._last_supply_state == before and host.router._last_launch == {}+ assert host.harness.agent._runtimes == {} and host.harness.provider.requests == []+ assert all(not tool.calls for tool in host.harness.tools)+ with engine.connect() as conn:+ assert conn.execute(select(messages.c.context_seq).where(messages.c.id == queued["id"])).scalar_one() is None+ directory = Path(result["artifact_dir"])+ if os.name != "nt":+ assert directory.stat().st_mode & 0o777 == 0o700+ assert all(file.stat().st_mode & 0o777 == 0o600 for file in directory.iterdir())+ assert set(directory.iterdir()) == {Path(result["manifest_path"]), Path(result["request_body_path"])}+ assert "headers" not in Path(result["manifest_path"]).read_text()+++async def test_fork_prefix_and_open_call_are_not_repaired(preview_host, engine, monkeypatch):+ host = preview_host+ await commit_input(host)+ with engine.begin() as conn:+ scope = conn.execute(select(agent_sessions.c.scope_id).where(agent_sessions.c.id == SESSION)).scalar_one()+ _insert_session(conn, "ses_preview_fork", scope, {"fork_source_session_id": SESSION, "fork_source_context_seq": 1})+ await host.harness.agent.store.append_response(+ SESSION, assistant("", calls=(ToolCallBlock("missing", "echo", {}),)), final=False,+ )+ request = request_preview.build_preview_request(host.controller, _build_session_context(SESSION))+ remove = deny_effects(host, monkeypatch)+ try:+ blocked = await invoke(host)+ earlier = await host.harness.agent.preview_request(SESSION, request, context_seq=1)+ fork = await host.harness.agent.preview_request("ses_preview_fork", request)+ finally:+ remove()+ result = blocked.json()+ assert result["status"] == "not_model_ready" and result["missing_tool_results"] is True+ assert result["wire_prepared"] is False and "request_body_path" not in result+ assert earlier.status == fork.status == "ready"+ assert earlier.wire.body == fork.wire.body+++async def test_context_transition_is_reported_without_writing_or_sending(preview_host, monkeypatch):+ host = preview_host+ await host.harness.agent.store.consume_input(+ SESSION, host.request.context.platform_specific["delivery_id"], UserMessage((text("long " * 100_000),)),+ )+ remove = deny_effects(host, monkeypatch)+ try:+ response = await invoke(host)+ finally:+ remove()+ result = response.json()+ assert result["status"] == "transition_required" and result["transition_required"] is True+ assert result["wire_prepared"] is False and "request_body_path" not in result+ assert len(response.content) < 2000++[email protected]("field", ["model", "reasoning_effort"])+def test_preview_and_dispatch_share_explicit_null_resolution(preview_host, engine, field):+ from core.agent_session_context import session_model_settings+ host = preview_host+ host.store.update("preview-agent", reasoning_effort="high")+ with engine.begin() as conn:+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == SESSION).values(**{+ field: None, "metadata_json": json.dumps({"project_base": "/tmp", "explicit_setting_overrides": [field]}),+ }))+ context = _build_session_context(SESSION)+ built = request_preview.build_preview_request(host.controller, context)+ assert getattr(built, "vibe_agent_" + field) is None+ assert getattr(built, "vibe_agent_" + field + "_explicit") is True+ assert session_model_settings(+ context.platform_specific["agent_session_target"], fallback_model="default", fallback_reasoning_effort="high",+ )[0 if field == "model" else 1] is None+++async def test_preview_uses_stored_project_base_over_current_scope(preview_host, engine, monkeypatch, tmp_path):+ host = preview_host+ await commit_input(host)+ stored_project = tmp_path / "stored-project"+ cwd = stored_project / "session"+ cwd.mkdir(parents=True)+ stored_skill = stored_project / ".agents" / "skills" / "stored-bound-skill" / "SKILL.md"+ stored_skill.parent.mkdir(parents=True)+ stored_skill.write_text("---\nname: stored-bound-skill\ndescription: Stored boundary\n---\nStored body\n")+ scope_skill = tmp_path / ".agents" / "skills" / "scope-skill" / "SKILL.md"+ scope_skill.parent.mkdir(parents=True)+ scope_skill.write_text("---\nname: scope-skill\ndescription: Current scope\n---\nScope body\n")+ with engine.begin() as conn:+ scope_id = conn.execute(select(agent_sessions.c.scope_id).where(agent_sessions.c.id == SESSION)).scalar_one()+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == SESSION).values(+ workdir=str(cwd), metadata_json=json.dumps({"project_base": str(stored_project)}),+ ))+ conn.execute(update(scope_settings).where(scope_settings.c.scope_id == scope_id).values(workdir=str(tmp_path)))+ context = _build_session_context(SESSION)+ request = request_preview.build_preview_request(host.controller, context)+ assert request.context.platform_specific["agent_run_target"]["project_base"] == str(stored_project)+ sections, _ = await host.harness.agent._avibe_sections(request, cwd=str(cwd))+ assert "stored-bound-skill" in sections+ assert "scope-skill" not in sections+ remove = deny_effects(host, monkeypatch)+ try:+ response = await invoke(host)+ finally:+ remove()+ assert response.status_code == 200+ body = Path(response.json()["request_body_path"]).read_bytes()+ assert b"stored-bound-skill" in body+ assert b"scope-skill" not in body+++async def test_route_description_matches_production_without_credential_activation(preview_host, monkeypatch):+ host = preview_host+ before = host.service.store.config.to_payload()+ with monkeypatch.context() as m:+ m.setattr(host.router, "_gateway_credentials", forbidden)+ m.setattr(host.router, "_emit_transition", forbidden)+ described = await host.router.describe_vibey_request("menu-alias")+ assert host.service.store.config.to_payload() == before+ assert host.router._last_launch == host.router._last_supply_state == {}+ assert described.gateway_token == "auth-unbound"+ monkeypatch.setattr(host.router, "_gateway_credentials", AsyncMock(return_value=("http://fixture.invalid/vibey", "fixture-only-token")))+ host.router.turn_gateway.correlation = SimpleNamespace(turn_hosted_tools=lambda turn: None)+ monkeypatch.setattr(host.router, "_emit_transition", lambda *args: None)+ launched = await host.router.resolve("vibey", "menu-alias", process_scope="fixture", turn_id="fixture-turn")+ assert replace(launched, gateway_base_url=described.gateway_base_url, gateway_token="auth-unbound", gateway_request_metadata={}) == described+ host.router._gateway_credentials.assert_awaited_once()+[email protected]("caller", [None, {}, {"kind": "remote"}, {"kind": "remote", "resource_user_context": {}}, {"kind": "local", "extra": True}])+async def test_ipc_missing_or_malformed_authority_cannot_inherit_owner(monkeypatch, caller):+ import core.internal_server as server+ monkeypatch.setattr(server, "_build_session_context", forbidden)+ app = create_app(_build_controller_double())+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://internal") as client:+ response = await client.post("/internal/debug/request/preview", json={"session_id": SESSION, "context_seq": None, "caller": caller})+ assert response.status_code == 403++[email protected]("role", ["viewer", "editor", "member", "owner"])+async def test_ipc_revalidates_existing_remote_owner_authority(preview_host, monkeypatch, role):+ from tests.scenarios.permissions.test_cli_invocation_authority import _pair_instance, _snapshot+ import core.internal_server as server++ _pair_instance()+ host = preview_host+ await commit_input(host)+ snapshot = _snapshot(role)+ if role != "owner":+ monkeypatch.setattr(server, "_build_session_context", forbidden)+ remove = deny_effects(host, monkeypatch)+ try:+ result = await invoke(host, caller={"kind": "remote", "resource_user_context": snapshot})+ finally:+ remove()+ assert result.status_code == (200 if role == "owner" else 403)+ if role == "owner":+ # A stale pairing cannot become the controller's owner either.+ snapshot["vibe_instance_id"] = "other-instance"+ assert (await invoke(host, caller={"kind": "remote", "resource_user_context": snapshot})).status_code == 403+++def test_cli_parser_and_output_cannot_print_internal_payload(monkeypatch, capsys):+ parser = cli.build_parser()+ args = parser.parse_args(["debug", "request", "preview", "--session-id", SESSION, "--context-seq", "0"])+ assert cli._CLI_COMMAND_FLOORS[("debug", "request", "preview")] == "owner"+ async def response(*args, **kwargs):+ return {"status_code": 200, "body": {"status": "ready", "auth": "unbound", "request_body_path": "/private/body", "body": "secret ciphertext", "headers": {"Authorization": "secret"}}}+ monkeypatch.setattr(internal_client, "request_preview", response)+ assert cli.cmd_debug_request_preview(args) == 0+ output = capsys.readouterr()+ assert "ciphertext" not in output.out and "Authorization" not in output.out+ assert json.loads(output.out)["request_body_path"] == "/private/body"+ with invocation_authority(AuthorizationContext(instance_role="editor", is_remote=True)):+ assert cli.cmd_debug_request_preview(args) == 1+++async def test_client_preserves_remote_owner_instead_of_daemon_authority(monkeypatch, tmp_path):+ from core.control_ipc import ControlIpcClientEndpoint+ from tests.scenarios.permissions.test_cli_invocation_authority import _pair_instance, _snapshot+ from storage.resource_access_service import resource_user_context_from_metadata++ _pair_instance()+ authority = resource_user_context_from_metadata({"resource_user_context": _snapshot("owner")})+ captured = []+ def capture(request):+ captured.append(json.loads(request.content))+ return httpx.Response(200, json={"status": "ready"})+ monkeypatch.setattr(internal_client, "_resolve_endpoint_async", AsyncMock(return_value=ControlIpcClientEndpoint(transport="unix", socket_path=tmp_path / "socket")))+ monkeypatch.setattr(internal_client, "_async_transport", lambda endpoint: httpx.MockTransport(capture))+ with invocation_authority(authority):+ await internal_client.request_preview(SESSION)+ assert captured[0]["caller"]["kind"] == "remote"+ assert captured[0]["caller"]["resource_user_context"]["vibe_instance_role"] == "owner"+ with invocation_authority(AuthorizationContext(instance_role="member", is_remote=True)):+ with pytest.raises(PermissionError):+ await internal_client.request_preview(SESSION)+ assert len(captured) == 1+++async def test_artifact_refuses_unsafe_directory_and_future_cut_is_sanitized(preview_host, tmp_path):+ host = preview_host+ await commit_input(host)+ response = await invoke(host, 100)+ assert response.status_code == 409 and response.json() == {"error": "request_preview_failed"}+ root = paths.get_state_dir() / "request-previews"+ root.parent.mkdir(parents=True, exist_ok=True)+ root.symlink_to(tmp_path, target_is_directory=True)+ response = await invoke(host)+ assert response.status_code == 409+ assert not list(tmp_path.glob("preview-*"))diff --git a/vibe/cli.py b/vibe/cli.pyindex 719b4a7c5..4f865110a 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -1039,6 +1039,31 @@ _PROMPT_RENDER_INPUT_ERRORS = {}+def cmd_debug_request_preview(args) -> int:+ """Print only structural metadata and private artifact paths, never the prepared request."""+ from vibe.authorization import require_instance_role+ from vibe.internal_client import request_preview++ try:+ require_instance_role(None, "owner")+ response = asyncio.run(request_preview(args.session_id, context_seq=args.context_seq))+ if response["status_code"] != 200:+ print("Request preview failed; check Owner access, the Vibey Session and current model configuration.", file=sys.stderr)+ return 1+ payload = response["body"]+ # An allowlist makes future IPC payload growth unable to leak diagnostic contents to stdout.+ keys = (+ "kind", "status", "reason", "mode", "auth", "session_id", "context_seq", "requested_context_seq",+ "transition_required", "transition", "missing_tool_results", "wire_prepared", "body_bytes", "body_sha256",+ "artifact_dir", "manifest_path", "request_body_path",+ )+ print(json.dumps({key: payload[key] for key in keys if key in payload}, ensure_ascii=False, indent=2))+ return 0+ except Exception:+ print("Request preview unavailable; no model request was sent.", file=sys.stderr)+ return 1++def cmd_debug_prompt(args) -> int:"""Export all authored sources, optionally with the production rendering."""@@ -17259,7 +17284,7 @@ def build_parser():"debug",help="Inspect internal Avibe state",)- debug_subparsers = debug_parser.add_subparsers(dest="debug_command", metavar="{prompt}")+ debug_subparsers = debug_parser.add_subparsers(dest="debug_command", metavar="{prompt,request}")debug_subparsers.required = Truedebug_prompt_parser = debug_subparsers.add_parser("prompt",@@ -17285,6 +17310,20 @@ def build_parser():help="Export format",)_add_json_noop(debug_prompt_export_parser)+ debug_request_parser = debug_subparsers.add_parser("request", help="Inspect a model request without sending it")+ debug_request_subparsers = debug_request_parser.add_subparsers(dest="request_debug_command", required=True)+ debug_request_preview = debug_request_subparsers.add_parser(+ "preview", help="Reconstruct a Vibey Session's committed context with current configuration (Owner only)",+ description=(+ "Create owner-private request artifacts without calling a provider or changing the Session. "+ "Uses current Agent/system/tools/route configuration, not historical sent bytes. "+ "Queued inputs are excluded; context transitions and missing tool results are reported, not executed. "+ "Authentication is unbound. Requires the local controller; no Web forwarding route exists."+ ),+ )+ debug_request_preview.add_argument("--session-id", required=True, help="Existing active Vibey Session ID")+ debug_request_preview.add_argument("--context-seq", type=_non_negative_int, help="Inclusive committed context cutoff")+ _add_json_noop(debug_request_preview)runtime_parser = subparsers.add_parser("runtime",help="Inspect and prepare managed runtimes",@@ -19061,6 +19100,7 @@ _CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {# authored files, and have no role contract to repair here.("screenshot",): None,("debug", "prompt", "export"): None,+ ("debug", "request", "preview"): "owner",# Runtime, configuration and retention are operational management.(): "member",("start",): "member",@@ -19340,6 +19380,8 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:_print_task_error(exc, help_command="vibe computer --help")sys.exit(1)if args.command == "debug":+ if args.debug_command == "request":+ sys.exit(cmd_debug_request_preview(args))sys.exit(cmd_debug_prompt(args))if args.command == "doctor":sys.exit(cmd_doctor(args))diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex 0a0cc95d6..fa3f3949e 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -1095,6 +1095,34 @@ async def turn_state(session_id: str, *, socket_path: Optional[Path] = None) ->return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}+async def request_preview(+ session_id: str,+ *,+ context_seq: int | None = None,+ socket_path: Optional[Path] = None,+) -> dict[str, Any]:+ """Ask the controller to reconstruct locally; only a safe artifact summary crosses back."""+ from core.handlers.request_preview import preview_caller++ # Check and capture the invoking principal before any IPC operation. Never drop remote claims.+ caller = preview_caller()+ endpoint = await _resolve_endpoint_async(socket_path)+ try:+ async with httpx.AsyncClient(+ transport=_async_transport(endpoint), base_url=endpoint.base_url,+ headers=endpoint.headers, timeout=httpx.Timeout(60.0, connect=0.5),+ ) as client:+ response = await client.post("/internal/debug/request/preview", json={+ "session_id": session_id, "context_seq": context_seq, "caller": caller,+ })+ _validate_response(response, endpoint)+ except httpx.ReadTimeout as exc:+ raise InternalServerTimeout("Request preview timed out") from exc+ except _SOCKET_CONNECT_ERRORS as exc:+ raise InternalServerUnavailable("Request preview controller unavailable") from exc+ return {"status_code": response.status_code, "body": response.json() if response.content else {}}++async def list_running_agents(*,run_ids: Optional[list[str]] = None,