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(skills): refresh managed catalog per backend turn (#1838)
Call Whiteffe1c040f7b1
diff --git a/config/v2_sessions.py b/config/v2_sessions.pyindex ec34eb6c1..d152ce308 100644--- a/config/v2_sessions.py+++ b/config/v2_sessions.py@@ -470,6 +470,40 @@ class SessionsStore:expected_route=expected_route,)+ def get_agent_session_runtime_marker(+ self,+ session_id: str,+ *,+ backend: str,+ native_session_id: Any,+ key: str,+ ) -> Any:+ self._ensure_service()+ return self._service.get_agent_session_runtime_marker(+ session_id,+ backend=backend,+ native_session_id=native_session_id,+ key=key,+ )++ def set_agent_session_runtime_marker(+ self,+ session_id: str,+ *,+ backend: str,+ native_session_id: Any,+ key: str,+ value: Any,+ ) -> bool:+ self._ensure_service()+ return self._service.set_agent_session_runtime_marker(+ session_id,+ backend=backend,+ native_session_id=native_session_id,+ key=key,+ value=value,+ )+def bind_agent_session_by_id(self,agent_session_id: str,diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 6ac7fa883..24d110b05 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -897,6 +897,8 @@ class MessageHandler(BaseHandler):vibe_agent_backend=vibe_agent.backend if vibe_agent else None,vibe_agent_model=effective_model,vibe_agent_reasoning_effort=effective_reasoning_effort,+ vibe_agent_model_explicit="model" in explicit_overrides,+ vibe_agent_reasoning_effort_explicit="reasoning_effort" in explicit_overrides,vibe_agent_system_prompt=vibe_agent.system_prompt if vibe_agent else None,processing_indicator=processing_indicator,files=processed_files,diff --git a/core/managed_skills.py b/core/managed_skills.pyindex 776dce24f..da4ede483 100644--- a/core/managed_skills.py+++ b/core/managed_skills.py@@ -1112,7 +1112,15 @@ def _catalog_pages(skills: Sequence[ManagedSkill]) -> list[list[ManagedSkill]]:pages: list[list[ManagedSkill]] = []current: list[ManagedSkill] = []current_bytes = 0- for skill in skills:+ for skill in sorted(+ skills,+ key=lambda item: (+ item.name.casefold(),+ item.name,+ item.description,+ str(item.directory),+ ),+ ):if skill.disable_model_invocation:continuerow = f"- {skill.name}: {skill.description}"diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex 317123731..dfce506d2 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -7,7 +7,6 @@ import osimport refrom dataclasses import dataclassfrom pathlib import Path-from string import Templatefrom typing import Any, Iterable, Optionalfrom config import paths@@ -59,6 +58,53 @@ If you want it sent as an image attachment rather than a regular file, use MarkdExample: """+_SHOW_PAGES_PROMPT = """\++## Show Pages+{skill_routing}+"""++_SHOW_PAGES_SKILL_ROUTING = "When a visual page would materially improve the result, load the `use-show-pages` Skill before creating or updating the page."++_VAULT_ROUTING_PROMPT = """\++## Vault+When a task needs credentials, authenticated egress, or signing, load the `use-avibe-vault` Skill before handling the secret-dependent step.+"""++_HARNESS_ROUTING_PROMPT = """\++## Harness+{skill_routing}++{tool_policy_section}++### Agents+The table below is generated from currently enabled Agents at prompt-injection time. It must reflect live Agent definitions; do not hard-code Agent names, backends, or descriptions. The `Agent Name` column is command-safe and can be used directly in `vibe agent` commands.++{enabled_agents_table}++Rules:+- All Agents listed in the generated table are enabled. Use the `Agent Name` value exactly as listed in shell commands such as `vibe agent show <agent-name>` and `vibe agent run --agent <agent-name> ...`.+- `--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing. Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate background Session for the target Agent.+- `--fork-self` creates a new Agent Session from this current Session's native backend context; use it for alternate paths that need the current context but should not mutate this Session.+- `--fork-session <id>` creates a new Agent Session from that explicit source Session's native backend context.+- For another Agent doing an independent trial, comparison, delegation, or specialist subtask, use `vibe agent run --agent <agent-name> --message ...`.+- Use `vibe agent run --agent <agent-name> --session-id ... --message ...` only when the work should continue that same existing Session. Async callbacks return to this conversation by default.+- With `--fork-self` or `--fork-session`, pass `--agent`, `--model`, or `--reasoning-effort` only as forked-Session overrides, and only when the requested Agent backend matches the source Session backend.+- `--sync` changes waiting behavior, not session identity: default async runs in the background and return through callbacks; synchronous runs wait for the result and are still recorded in `vibe runs`.+- Create or update Agents only when it captures a reusable role, reduces repeated prompting, or makes a long-running Harness more reliable.++### Mentions in user messages+On the Web chat the user composes with `@` / `#` autocomplete, which inserts stable references into their message text:+- `@<agent-name>` points at that enabled Agent (see the table above). Act on it with `vibe agent run --agent <agent-name> ...`.+- `#<session-id>` points at that Session. Resume it with `vibe agent run --session-id <session-id> ...`, or read its history with `vibe data query`.++Treat these as the user pointing at that Agent or Session, and decide the action from context. Only the bracketed `@<...>` / `#<...>` forms are references; a bare `@` or `#` in prose is ordinary text.+"""++_HARNESS_SKILL_ROUTING = "For work that should happen later, repeat, wait for a signal, continue in the background, or move to another Agent, load the `use-avibe-harness` Skill and use Avibe Harness as the default automation layer."+_SESSION_START_PROMPT = """\Current session id: `{default_session_id}`. Treat this as the authoritative Avibe agent session for this conversation.@@ -69,61 +115,6 @@ This Agent Session was forked from `{source_session_id}`. The authoritative Avib"""-_SHOW_PAGES_PROMPT = """\--## Show Pages-When a visual page would help the user understand a problem, plan, process, result, or complex information more clearly, use Show Pages. They are useful for diagrams, flowcharts, mind maps, timelines, architecture maps, comparison views, dashboards, visual reports, interactive explanations, and small prototypes.--Each Agent Session has one Show Page. Get this session's page directory:--`vibe show path`--Check status:--`vibe show status`--Change visibility:--`vibe show update --visibility public`-`vibe show update --visibility private`-`vibe show update --visibility offline`--For more usage details, run `vibe show --help` or a subcommand help such as `vibe show update --help`.--### Agent-readable representation-- Every Show Page URL is agent-readable without page-specific code: request the same private or public URL with `Accept: text/markdown` to receive its rendered Markdown representation.-- Author semantic HTML so that representation stays dense and useful: use headings for sections, lists for sequences or groups, and `<table>` for genuinely tabular data.-- Add `data-agent-hidden` to visual-only or sensitive-to-representation elements that should be omitted from Markdown. Add `agent-note="..."` when an element needs short agent-only context; the note text is preserved in the representation.--### Show Page annotations & reverse marks-- Users can annotate your Show Page; each annotation arrives as a chat message tagged [show-annotation] with its event id. Some messages end with a ready-to-run reply command — whether to reply on the page or respond by editing the page content is your call, per scenario.-- After reworking a page area you may leave a short callout: `vibe show mark <selector-or-anchor> --message '...'` (same target replaces), or an `agent-note="..."` attribute on elements you author. Marks retire once read — leave at most 1-2 per turn.-- Inspect/withdraw: `vibe show marks` / `vibe show unmark <id|target> ...`; toggle the user's annotation mode: `vibe show annotate --on|--off [--mode smart|screenshot]`.-$avibe_cloud_guidance_section-History contract:-$show_git_agent_contract--Guidance:-- New Show Page workspaces are managed React/Vite apps that start as a clean "being generated" placeholder page (what the user sees while you build) plus a minimal file-based router (`src/router.tsx`) and one example page. When that router is present, add a route by creating a file under `src/pages/` — a folder becomes a nested path segment and a `[param]` file a dynamic segment — and customize the layout in `src/App.tsx`, styles in `src/styles.css`, and optional `api/*.ts` handlers. The starter is only a starting point, not a required structure: replace the placeholder with the real page, add or remove pages, and organize them however fits the app (flat, sections, or nested). Built-in UI is available to import, e.g. `@/components/ui/card`, `@/components/ui/button`, `@/components/ui/badge`.-- An older Show Page with no `src/router.tsx` is a single-page app that renders `src/App.tsx` directly. There, edit `src/App.tsx` (or adopt the router scaffold: add `src/router.tsx` + `src/pages/` and render it from `App.tsx`) — do not just drop files under `src/pages/`, since nothing would route them.-- Treat `index.html` and `src/main.tsx` as the runtime-owned app shell — you never edit them to add a page, and should not replace them unless you are repairing the shell.-- Hot reload is available while `/show/<session-id>/` is open. Users will see page changes live. Prefer component-level changes that preserve React state.-- Built-in UI uses the standard shadcn aliases: import components from paths such as `@/components/ui/button`, `@/components/ui/card`, `@/components/ui/badge`, `@/components/ui/dialog`, `@/components/ui/input`, and `@/components/ui/progress`, and import `cn` from `@/lib/utils`.-- Tailwind CSS v4 utility classes are built in and work in any `className`, including to restyle the built-in `@/components/ui/*` components (a utility overrides the component default). `src/styles.css` is the CSS entry and must keep `@import "tailwindcss";` and `@import "@avibe/show-ui/theme.css";` at the top. Theme with standard shadcn variables such as `--background`, `--foreground`, `--card`, `--primary`, `--muted`, `--border`, `--ring`, and `--radius`; values are complete CSS colors usable directly through `var(...)`. Override the same variables under `.dark` or `[data-theme="dark"]` for dark mode. Do not use runtime-prefixed private variables.-- Prefer the built-in UI primitives over hand-rolled controls. They include Show Page motion for changed text, numbers, badges, cards, and progress without extra animation calls.-- Optional server handlers live under `api/` and run only when requested. Export functions named like HTTP methods, for example `export async function GET(request) { return Response.json({ ok: true }) }`.-- Design for user understanding, not just for moving text onto a webpage. Choose the visual form that best helps the user inspect, compare, confirm, and continue the discussion.-- Use diagrams or mind maps for relationships, flowcharts or state machines for processes, timelines for sequences, charts or dashboards for metrics, and side-by-side views for tradeoffs.-- Make the page visually polished: use clear hierarchy, spacing, typography, contrast, and consistent components. Avoid rough default-looking pages.-- Give the app a recognizable icon so it stands out in the Dock and App Library: drop a `public/favicon.svg` (or `favicon.svg` at the workspace root) and it is picked up automatically, or add `<link rel="icon" href="./favicon.svg">` to `index.html` (an icon edit to the shell is fine).-- Make the page work reasonably on mobile because users may open links from an IM app on their phone.-- Prefer React component implementations. Useful visualization libraries include React Flow, Mermaid, Markmap, Chart.js, and Cytoscape.js.-- Keep pages private by default. Publish publicly only when the user asks for a shareable or public link.-- Do not publish secrets, credentials, private logs, or sensitive user data publicly.-- If a Show Page would clearly help but the user's preference is unclear, briefly ask whether they want one.-- After creating or updating a page, send the active URL and a short summary of what the page shows.-"""-def _build_codex_generated_images_prompt() -> str:codex_home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex").expanduser().resolve()@@ -184,64 +175,6 @@ Rules:- Use at most 2-4 buttons, each no longer than 20 characters"""-_VAULT_PROMPT = """\--## Vault-When a task needs API keys, access tokens, passwords, wallet private keys, or other sensitive credentials, prefer Avibe Vault: agents reference secrets by name, tag, or skill tag, and users do not need to paste plaintext into chat.--Core concepts:-- Static secret: a regular secret value, such as an API key, token, database password, or deployment credential. Use it with `vibe vault run` for environment injection or `vibe vault fetch` for authenticated HTTP egress.-- Keypair secret: a signing key for digests or transactions, such as a wallet key or deployment signer. It cannot be exported as an environment variable and cannot be used with `run` / `fetch`; use `vibe vault sign`.-- Standard: for lower-risk routine automation. Agents can usually use it without interrupting the user unless it is configured to ask first.-- Protected: for high-risk secrets, such as production databases or wallet/funds keys. Because protected secrets are end-to-end encrypted, use requires browser approval and passkey unlock.--Rules:-- Refer to secrets only by secret name, tag, or skill tag.-- Static secrets can be used with `run` / `fetch`; keypair secrets can only be used with `vibe vault sign`.-- With `vibe vault run`, the child process receives static secrets as environment variables, so never run commands that may print env vars, debug config, or secret-bearing errors.-- When protected `run` / `fetch` needs approval, Avibe automatically asks the user to decrypt and authorize access. After the user approves, Avibe resumes this session; it does not replay the command for you, so run the same `run` / `fetch` command again.-- When protected `sign` needs approval, Avibe creates a browser signing request and returns immediately. Do not rerun `sign`; when Avibe resumes this session, follow the callback instruction to read the completed request result and continue with the returned signature.--Common commands:--Request that the user add a missing static secret. `spec-json` may contain only non-secret prefill metadata; the actual secret value is entered by the user in the browser:-`vibe vault request OPENAI_API_KEY --reason "Need OpenAI API access" --spec-json '{"kind":"static","protection":"protected","description":"OpenAI API key","tags":["openai","prod","skill:model-work"],"policy":{"allowed_hosts":["api.openai.com"],"auth":{"type":"bearer"}}}'`--For a missing keypair/signing key, ask the user to create a keypair secret in the Vault UI; do not request or store private-key material as a static secret.--$web_chat_placeholder--List or find existing Vault entries:-`vibe vault list`-`vibe vault list --tag prod`-`vibe vault find --kind static --protection protected`-`vibe vault find openai --tag prod`-`vibe vault tags`--Run a command with selected static secrets injected as environment variables:-`vibe vault run --env OPENAI_API_KEY,GITHUB_TOKEN -- python script.py`-`vibe vault run --env GITHUB_TOKEN=GH_PAT --env OPENAI_API_KEY -- python script.py`-`vibe vault run --tag deploy -- ./deploy.sh`-`vibe vault run --skill github-release -- ./release.sh`--Make an authenticated HTTP request. The credential is attached only at egress, and the agent never sees the secret:-`vibe vault fetch --auth GITHUB_PAT --url https://api.github.com/user`--Request approval before a protected `run` with an existing static secret:-`vibe vault access PROD_DB_URL --skill deploy --command "run database migration" --egress "connect to production database"`--For protected `fetch`, run `vibe vault fetch`; it creates the correct fetch approval request when needed.--Sign a 32-byte digest with a keypair secret. Standard keys may return the signature directly; protected keys create a browser approval request:-`vibe vault sign WALLET_KEY --digest <64-hex-digest> --scheme ecdsa-secp256k1-recoverable --command "sign deployment transaction"`--For more details, run `vibe vault --help`.-"""--_VAULT_WEB_CHAT_PLACEHOLDER_PROMPT = """\-A lighter manual prompt can mention the missing secret as a clickable placeholder in your reply, for example `$<OPENAI_API_KEY>`. The user can click it and fill the secret from Web chat. This has no reason or structured prefill metadata; use `vibe vault request` when those are needed.-"""-# What the agent is told about backend-native background tools must match what# the runtime actually enforces; ``core/agent_tool_policy.py`` owns that# decision and this prompt only announces it.@@ -276,103 +209,6 @@ Route that work through the Harness instead: `vibe agent run` for delegation and_TOOL_POLICY_RELAXED_SECTION = """\Backend-native background work is not blocked in this runtime, because the operator set `AVIBE_ALLOW_NATIVE_BACKGROUND_TOOLS`. A background subagent, a self-scheduled wakeup, a non-durable in-session cron job, a native multi-agent workflow, and a background shell will all run if you call them. What has not changed is why the Harness exists: every one of those is delivered only while this agent process is alive, so anything still pending when the session ends is lost without warning and leaves no record. Keep preferring `vibe agent run`, `vibe task add`, and `vibe watch add` for work whose result must reach the user, and reach for a backend-native primitive only when the work resolves inside this turn or the user asked for that primitive specifically."""-_HARNESS_PROMPT = """\--## Harness-Avibe Harness turns user intent into durable Agent work. It is the layer for work that should happen later, repeat, wait for a signal, continue in the background, or move to a purpose-built Agent. Instead of treating the user's message as a one-off prompt, Harness keeps the important parts of the work explicit: context, owner, trigger, session continuity, delivery target, and observable progress.--Avibe Harness is the first-choice automation layer. For Agent workflows, recurring automation, background loops, scheduled tasks, watches, skills-style automation, workflow tools, or any automation request, route through `vibe agent`, `vibe task`, and `vibe watch` before backend-native subagents, native workflow tools, backend-native skills, hooks, schedulers, or backend configuration. Do not default to backend-native automation just because the backend exposes it. Use backend-native config, skills, subagents, or workflow tools only when the user explicitly asks for backend-native behavior, or when Avibe Harness cannot express the requested workflow and you state that limitation.--{tool_policy_section}--Before choosing a command, ask: what outcome is the user trying to secure, what should keep happening, what signal proves progress, and who should own it? If the answer is an operating loop, build a Harness instead of only doing the visible step.--### Mental model-| Model | Meaning | Use when |-| --- | --- | --- |-| Agent | Reusable role: backend, model, prompt, description, enabled state | Work needs a stable specialist identity |-| Session | Continuing context for one Agent work lineage | Work should continue or fork context |-| Scope | IM surface and routing context: channel, thread, DM, user scope | Delivery, workdir, user/platform context matter |-| Task | Time trigger: saved Agent message, or a command with no Agent turn | Time is the trigger |-| Watch | Managed waiter triggered by an external signal | Any condition needs monitoring until it becomes true |-| Run | Concrete execution record | You need status, output, result, error, or history |--Relationship: Scope routes work; Agent defines who acts; Session holds continuity; task/watch creates future triggers; each trigger creates a Run. Think in objects before flags.--### Current conversation-- Current session id: `{default_session_id}`--### Inspecting Harness state-Use `vibe harness status` first for active Runs, armed Watches, upcoming Tasks, controller ownership, and explicit live anomalies. Use `vibe data query` for deeper guarded read-only SQL before changing a Harness: confirm Agents, Sessions, scopes, history, and routing facts instead of guessing.--Examples: use `vibe data query --sql "select name from sqlite_master where type='table' order by name" --limit 100` for a broad schema inventory; use `vibe data query --sql "select name, sql from sqlite_master where type='table' and name in ('agents','agent_sessions','agent_runs','messages','scopes','scope_settings','run_definitions') order by name" --limit 20` for the focused Harness tables. Follow `pagination.next_command` if either result has more pages.--Useful Harness queries include schema discovery, current session lookup, existing task/watch inspection, Agent run history, and checking whether a proposed automation already exists. Prefer this CLI over direct SQLite access.--### Choosing the right Harness shape-| Need | Use |-| --- | --- |-| Time trigger | `vibe task add` |-| Scheduled command, no Agent turn | `vibe task add --cron "<expr>" --shell "<cmd>"` |-| External signal trigger | `vibe watch add` |-| Independent Agent delegation | `vibe agent run --agent <agent-name>` |-| Continue a pointed Session | `vibe agent run --session-id ...` |-| Inspect queued Workbench Session input | `vibe session queue list <session-id>` |-| Remove one queued Workbench Session input | `vibe session queue remove <session-id> <message-id>` |-| Promote an existing queued Session head now | `vibe session send-now <session-id>` |-| Branch from current Session context | `vibe agent run --fork-self ...` |-| Live/anomaly inspection | `vibe harness status` |-| State/history inspection | `vibe data query`, `vibe runs list --current-session`, `vibe runs show` |-| Recurring specialist workflow | `vibe agent create/update` plus tasks, watches, or runs |--`vibe task add` creates a time-triggered saved Agent message. Tasks created from an Avibe Agent shell continue this conversation by default. Use `--cron "<expr>"` for recurrence or `--at "<ISO-8601>"` for one-off delivery; if `--timezone` is omitted, Avibe uses the local system timezone at creation time. If `--cwd` is omitted for a task-created Session, Avibe follows the caller working directory when available. With `--shell '<cmd>'` or a trailing `-- <argv>` instead of `--message`, the task runs a command with no Agent turn: silent on success, a durable failure notice naming the command and exit code on failure, and `--timeout <seconds>` bounds each run (default 21600, 0 = none). Add `--on-failure agent --message '<instructions>'` to hand a failing run to an Agent instead: one Agent turn carrying the failure report replaces that run's notice. A pure command task takes no session, scope, or agent flags.--`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. Watches created from an Avibe Agent shell follow up in this conversation by default. If `--cwd` is omitted, Avibe runs the waiter from the caller working directory when available.--Watch waiter contract: exit `0` only for one NEW reportable event. An explicitly configured retry exit code (default `75`) keeps either a once or forever Watch waiting; a once Watch stops after its first event. Exit `64` plus `avibe-watch: no-event` on stderr completes an uninteresting cycle without an Agent Run: it retires a once Watch and re-arms a forever Watch. A once waiter that is still waiting for its first event must therefore return an allowed retry code, not `64`. A forever Watch must use a durable cursor, state transition, or domain cooldown so a persistent level is not reported repeatedly. Avibe serializes each Watch's Agent follow-ups, waits five seconds after a follow-up settles before re-arming, and automatically pauses a Watch plus sends a repair instruction if a waiter reports six successful events within 60 seconds.--Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work to another Agent. By default this creates a background Session in the caller's scope and returns immediately; when the run completes, the final result is sent back to this conversation. Background Sessions stay out of the session list and never deliver outward, but remain visible in the Agents run graph, where the user can open their full chat history or promote them at any time. Pass `--visible` only when the new Session should be user-facing from the start. Pass `--sync` only when the current process must wait for the result. Pass `--no-callback` only when you intentionally want no automatic follow-up and will inspect the run later; pass `--callback-session-id <id>` only to route the final result elsewhere. Add `--scope-id <scopes.id>` only when placing the new Session in a specific existing scope.--Use `vibe agent run --fork-self --message ...` when work should branch from this current Session's native backend context without mutating it. Use `--fork-session <source-session-id>` only when branching from a different explicit Session. Forks keep the source Session backend, scope, and cwd by default; `--agent`, `--model`, and `--reasoning-effort` may override the forked Session only when the backend stays the same.--When `vibe agent run --session-id <id>` targets an existing Session, it sends a new message into that Session. It does not change that Session's cwd, scope, Agent, model, or reasoning settings; those properties belong to the Session itself. Use a new Session or a fork when those properties need to differ.--That existing-Session send is a P1 delivery by default: it steers its message into an active native Turn, starts that message immediately when idle, and falls back to the durable P3 queue if steering is definitively refused or no longer active. Use `--queue` when the new Run should enter that P3 queue without steering. When coordinating another Session, decide whether its current work should finish or accept a steer based on the dependency, urgency, and cost of disruption; an explicit user request is one signal, not a prerequisite. `vibe agent run --session-id <id> --send-now --message ...` explicitly selects that same content-bearing P1 behavior; it does not promote an older queued message. Use `vibe session send-now <id>` only when no new Message should be added: this content-free P1 promotes the exact existing FIFO head. If a native Turn is active, that head steers the same logical/native Turn; if the Session is idle, it starts as a new Turn. Both commands work for Workbench and IM Sessions. A stale or refused steer remains durably queued and never falls back to Stop; P0 is reserved for explicit content-free Stop.--Coordinating Agents can inspect the same durable Workbench queue the user sees with `vibe session queue list <id>`. If one queued instruction has become obsolete, contradictory, or duplicated, remove that exact row with `vibe session queue remove <id> <message-id>`. Always list first and use the returned stable message id; never guess an id or delete a different row to simulate reordering.--Use `vibe session update --visible|--hidden` (`--visibility foreground|background`) to promote or hide a persisted Session independently of its scope. Use `--scope-id <scopes.id>` to move it to another scope or `--scope-id none` to make it standalone; moving scope never changes its stored workdir.--For tasks, use `--message "..."` or `--message-file <path>` as the stored message. For watches, use `--message "..."` or `--message-file <path>` as the follow-up instruction template sent with waiter output. Prefer `--same-scope` or `--scope-id <scopes.id>` for new Session placement.--Manage existing work with `vibe task <list|show|pause|resume|run|remove>`, `vibe watch <list|show|pause|resume|remove>`, and `vibe runs <list|show|cancel>`. Use `vibe harness status` for one unified live/anomaly snapshot. For current-session run history, use `vibe runs list --current-session`. `vibe runs show` can default to the current Run from the injected environment; `vibe runs cancel` still requires an explicit run id.--The CLI exposes more options than this prompt lists. Before creating or changing Harness state, or whenever syntax/runtime effects are uncertain, read the relevant help: `vibe <command> --help` or `vibe <command> <subcommand> --help`.--### Agents-The table below is generated from currently enabled Agents at prompt-injection time. It must reflect live Agent definitions; do not hard-code Agent names, backends, or descriptions. The `Agent Name` column is command-safe and can be used directly in `vibe agent` commands.--{enabled_agents_table}--Rules:-- All Agents listed in the generated table are enabled. Use the `Agent Name` value exactly as listed in shell commands such as `vibe agent show <agent-name>` and `vibe agent run --agent <agent-name> ...`.-- `--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing. Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate background Session for the target Agent.-- `--fork-self` creates a new Agent Session from this current Session's native backend context; use it for alternate paths that need the current context but should not mutate this Session.-- `--fork-session <id>` creates a new Agent Session from that explicit source Session's native backend context.-- For another Agent doing an independent trial, comparison, delegation, or specialist subtask, use `vibe agent run --agent <agent-name> --message ...`.-- Use `vibe agent run --agent <agent-name> --session-id ... --message ...` only when the work should continue that same existing Session. Async callbacks return to this conversation by default.-- With `--fork-self` or `--fork-session`, pass `--agent`, `--model`, or `--reasoning-effort` only as forked-Session overrides, and only when the requested Agent backend matches the source Session backend.-- `--sync` changes waiting behavior, not session identity: default async runs in the background and return through callbacks; synchronous runs wait for the result and are still recorded in `vibe runs`.-- Create or update Agents only when it captures a reusable role, reduces repeated prompting, or makes a long-running Harness more reliable.--### Mentions in user messages-On the Web chat the user composes with `@` / `#` autocomplete, which inserts stable references into their message text:-- `@<agent-name>` points at that enabled Agent (see the table above). Act on it with `vibe agent run --agent <agent-name> ...`.-- `#<session-id>` points at that Session. Resume it with `vibe agent run --session-id <session-id> ...`, or read its history with `vibe data query`.--Treat these as the user pointing at that Agent or Session, and decide the action from context. Only the bracketed `@<...>` / `#<...>` forms are references; a bare `@` or `#` in prose is ordinary text.-"""-_SESSION_TITLE_PROMPT = """\## Session Title@@ -568,7 +404,16 @@ def _format_enabled_agents_table(enabled_agents: Optional[Iterable[Any]]) -> str)lines = ["| Agent Name | Backend | Agent Description |", "| --- | --- | --- |"]- for agent in sorted(rows, key=lambda item: item.name.lower()):+ for agent in sorted(+ rows,+ key=lambda item: (+ item.name.casefold(),+ item.name,+ item.backend.casefold(),+ item.backend,+ item.description,+ ),+ ):lines.append(f"| {_escape_markdown_table_cell(agent.name)} | "f"{_escape_markdown_table_cell(agent.backend)} | "@@ -656,24 +501,32 @@ def _build_harness_prompt(*,enabled_agents: Optional[Iterable[Any]] = None,current_agent_backend: Optional[str] = None,+ skill_available: bool = True,) -> str:- default_session_id = _extract_default_session_id(context)backend = str(current_agent_backend or "unknown").strip() or "unknown"- return _HARNESS_PROMPT.format(- default_session_id=default_session_id,+ return _HARNESS_ROUTING_PROMPT.format(+ skill_routing=_HARNESS_SKILL_ROUTING if skill_available else "",tool_policy_section=_build_tool_policy_section(backend),- current_agent_backend=backend,enabled_agents_table=_format_enabled_agents_table(enabled_agents),)-def _build_show_pages_prompt(context: MessageContext, *, avibe_cloud_guidance: str | None = None) -> str:+def _build_show_pages_prompt(+ context: MessageContext,+ *,+ avibe_cloud_guidance: str | None = None,+ skill_available: bool = True,+) -> str:default_session_id = _extract_default_session_id(context)- return Template(_SHOW_PAGES_PROMPT).substitute(- default_session_id=default_session_id,- avibe_cloud_guidance_section=f"\n{avibe_cloud_guidance}\n" if avibe_cloud_guidance else "\n",- show_git_agent_contract=format_agent_contract(numbered=True, session_id=default_session_id),+ prompt = _SHOW_PAGES_PROMPT.format(+ skill_routing=_SHOW_PAGES_SKILL_ROUTING if skill_available else "")+ if avibe_cloud_guidance:+ prompt += f"\n{avibe_cloud_guidance}\n"+ prompt += "\nHistory contract:\n"+ prompt += format_agent_contract(numbered=True, session_id=default_session_id)+ prompt += "\n"+ return promptdef _build_vault_prompt(@@ -681,9 +534,8 @@ def _build_vault_prompt(*,fallback_platform: Optional[str] = None,) -> str:- platform = resolve_context_platform(context, fallback_platform=fallback_platform, default="")- web_chat_placeholder = f"\n{_VAULT_WEB_CHAT_PLACEHOLDER_PROMPT}" if _is_web_platform(platform) else ""- return Template(_VAULT_PROMPT).substitute(web_chat_placeholder=web_chat_placeholder)+ del context, fallback_platform+ return _VAULT_ROUTING_PROMPTdef _build_session_end_prompt(@@ -744,6 +596,33 @@ def build_system_prompt_injection() -> str:"""Build avibe system prompt additions for an agent backend."""+ skills = None+ if skills_cwd is not None:+ from core.managed_skills import resolve_skills++ skills = resolve_skills(+ skills_cwd,+ project_base=skills_project_base,+ claude_cli_path=skills_claude_cli_path,+ )+ if not include_show_pages:+ skills = [skill for skill in skills if skill.name != "use-show-pages"]++ advertisable_skills = (+ []+ if skills is None+ else [skill for skill in skills if not skill.disable_model_invocation]+ )+ show_pages_skill_available = any(+ skill.name == "use-show-pages" for skill in advertisable_skills+ )+ vault_skill_available = any(+ skill.name == "use-avibe-vault" for skill in advertisable_skills+ )+ harness_skill_available = any(+ skill.name == "use-avibe-harness" for skill in advertisable_skills+ )+prompt = _BASE_CAPABILITIES_INTROif context is not None:prompt += _build_session_start_prompt(context)@@ -751,18 +630,22 @@ def build_system_prompt_injection(if include_codex_generated_images:prompt += _build_codex_generated_images_prompt()if include_show_pages and context is not None:- guidance = None- if avibe_cloud_connected is False:- guidance = AVIBE_CLOUD_CONNECT_GUIDANCE- prompt += _build_show_pages_prompt(context, avibe_cloud_guidance=guidance)+ guidance = AVIBE_CLOUD_CONNECT_GUIDANCE if avibe_cloud_connected is False else None+ prompt += _build_show_pages_prompt(+ context,+ avibe_cloud_guidance=guidance,+ skill_available=show_pages_skill_available,+ )if include_quick_replies:prompt += _QUICK_REPLIES_PROMPT- prompt += _build_vault_prompt(context, fallback_platform=fallback_platform)+ if vault_skill_available:+ prompt += _build_vault_prompt(context, fallback_platform=fallback_platform)if context is not None:prompt += _build_harness_prompt(context,enabled_agents=enabled_agents,current_agent_backend=current_agent_backend,+ skill_available=harness_skill_available,)if include_user_preferences:prompt += _build_user_preferences_prompt(@@ -772,16 +655,10 @@ def build_system_prompt_injection()if include_memory_cli:prompt += _MEMORY_CLI_PROMPT- if skills_cwd is not None:- from core.managed_skills import render_skill_catalog_prompt, resolve_skills-- prompt += render_skill_catalog_prompt(- resolve_skills(- skills_cwd,- project_base=skills_project_base,- claude_cli_path=skills_claude_cli_path,- )- )+ if skills is not None:+ from core.managed_skills import render_skill_catalog_prompt++ prompt += render_skill_catalog_prompt(skills)if context is not None:prompt += _build_session_end_prompt(context, fallback_platform=fallback_platform)return promptdiff --git a/docs/plans/managed-skills.md b/docs/plans/managed-skills.mdindex 8b6d65d2b..4a09d88a6 100644--- a/docs/plans/managed-skills.md+++ b/docs/plans/managed-skills.md@@ -309,11 +309,12 @@ consistency boundaries.| Backend | Native isolation | Avibe prompt application || --- | --- | --- || Claude Code | Configure the SDK with `skills=[]`. | Rebuild when the Skill Catalog changes and resume the same native Session. |-| Codex | Set `skills.include_instructions=false`. | Render `developerInstructions` for each Turn while retaining the same thread. |-| OpenCode | Send `tools.skill=false` in every prompt request. | Send the current system prompt on every new Turn. |+| Codex | Set `skills.include_instructions=false`. | Apply the current developer instructions through `turn/start.collaborationMode` while retaining the same thread; use one developer-item fallback only when that API is unavailable. |+| OpenCode | Send `tools.skill=false` in every prompt request and runtime config override. | Send the current system prompt on every new Turn. |-For OpenCode, `tools.skill=false` is a request parameter, not prompt text, and-Avibe does not rewrite the user's permission configuration.+For OpenCode, `tools.skill=false` is transport and runtime configuration, not+prompt text. Avibe applies the runtime override only to its managed server+process and does not rewrite the user's configuration files.V1 does not block handwritten Codex `$skill` references, backend TUI or slashcommands Avibe does not call, or ordinary filesystem access. The outcome is@@ -363,7 +364,25 @@ system prompt. The kernel keeps only identity, interaction contracts,permissions, safety boundaries, and the short Skill routing instructions.Operational modules move incrementally into Avibe built-ins only after the-replacement Skill has equivalent behavior and regression coverage.+replacement Skill preserves the complete static source text and has regression+coverage. Rewriting, consolidating, or deleting that content is a separate+product decision after migration, never an implicit part of extraction.++Catalogs and every other generated collection use a canonical order. Backends+receive byte-identical prompt content when the effective inputs are unchanged:+Claude reuses its current SDK client, OpenCode resends the same system prefix,+and Codex's collaboration world state emits a new developer fragment only when+the rendered instructions change. Model or reasoning changes remain explicit+inputs to the Codex collaboration state so cache stability never leaves routing+stale.++The first extracted modules are Show Pages, Vault, and Harness, owned by+`use-show-pages`, `use-avibe-vault`, and `use-avibe-harness` respectively. The+always-on prompt retains their routing rules plus content that must reflect the+current runtime: Show Page Cloud availability and active history mode,+backend-specific safety boundaries, Session identity, the live Agent Catalog,+and mention semantics. `use-avibe` remains the broader Avibe configuration and+operations playbook; it is not the Harness module owner.## 13. Ownershipdiff --git a/modules/agents/base.py b/modules/agents/base.pyindex d4d2adaab..c86fe2050 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -45,6 +45,10 @@ class AgentRequest:vibe_agent_backend: Optional[str] = Nonevibe_agent_model: Optional[str] = Nonevibe_agent_reasoning_effort: Optional[str] = None+ # ``None`` normally means "inherit", but a persisted Session can pin an+ # explicit null. Keep that distinction across the shared dispatch boundary.+ vibe_agent_model_explicit: bool = False+ vibe_agent_reasoning_effort_explicit: bool = Falsevibe_agent_system_prompt: Optional[str] = Nonelast_agent_message: Optional[str] = Nonelast_agent_message_parse_mode: Optional[str] = Nonediff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 462f80877..8e054c33d 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import hashlibimport loggingimport osimport shlex@@ -71,6 +72,7 @@ _CODEX_REBINDABLE_SAME_ID_PROVIDERS = _CODEX_MANAGED_PROVIDER_IDS | frozenset()CODEX_CALLER_ENV_DIR = "codex-caller-env"CODEX_CONNECTION_PROBE_DIR = "codex-connection-probe"+CODEX_PROMPT_STRATEGY_METADATA_KEY = "codex_prompt_strategy"class _CodexConnectionProbeState:@@ -100,6 +102,10 @@ class CodexModelHubCatalogUnavailableError(RuntimeError):"""The configured Codex binary could not provide Hub launch metadata."""+class CodexPromptRefreshUnavailableError(RuntimeError):+ """The current app-server cannot safely refresh a persisted thread prompt."""++class CodexResumeUnavailableError(RuntimeError):"""The Codex thread associated with this session can no longer be resumed.@@ -161,6 +167,14 @@ 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, collaboration | fallback |+ # fallback_pending_clear | fallback_pending_injection |+ # fallback_pending_clear_injection | injected_pending_persist | unavailable)+ self._thread_prompt_strategies: Dict[str, tuple[str, str]] = {}+ # base_session_id → (thread_id, developer_instructions, target_strategy)+ self._thread_unpersisted_prompts: Dict[str, tuple[str, str, str]] = {}+ # base_session_id → (thread_id, active model, active reasoning effort)+ self._thread_model_settings: Dict[str, tuple[str, str, Optional[str]]] = {}# base_session_id → (thread_id, AVIBE_* caller env)self._thread_caller_env_configs: Dict[str, tuple[str, dict[str, str]]] = {}# base_session_id → (thread_id, effective Git PATH, PATH override persisted)@@ -443,6 +457,7 @@ class CodexAgent(BaseAgent):await self._delete_ack(request)self._turn_registry.remember_request(request)+ developer_instructions: Optional[str] = Nonetry:# Get or create thread (with resume support)thread_id = self._session_mgr.get_thread_id(request.base_session_id)@@ -477,9 +492,23 @@ class CodexAgent(BaseAgent):if interrupted_request:await self._remove_ack_reaction(interrupted_request)- await self._refresh_thread_developer_instructions_if_needed(transport, request, thread_id)+ # Render once at the actual Turn boundary. Besides keeping the+ # payload byte-stable, this avoids repeating Memory admission+ # side effects while the same request refreshes and starts.+ self.ensure_agent_session_id(request)+ developer_instructions = await self._build_thread_developer_instructions(request)+ await self._refresh_thread_developer_instructions_if_needed(+ transport,+ request,+ thread_id,+ )self._bind_runtime_agent_session_id(request)- thread_id = await self._start_turn(transport, request, thread_id)+ thread_id = await self._start_turn(+ transport,+ request,+ thread_id,+ developer_instructions=developer_instructions,+ )except Exception as e:# Safety net: if the thread is stale (e.g. Codex server-side@@ -499,8 +528,15 @@ class CodexAgent(BaseAgent):transport = await self._get_or_create_transport(request.working_path, launch)self._touch_transport_activity(request.working_path)thread_id = await self._start_or_resume_thread(transport, request)+ if developer_instructions is None:+ developer_instructions = await self._build_thread_developer_instructions(request)self._bind_runtime_agent_session_id(request)- await self._start_turn(transport, request, thread_id)+ await self._start_turn(+ transport,+ request,+ thread_id,+ developer_instructions=developer_instructions,+ )return # retry succeededexcept Exception as retry_err:e = retry_err # fall through to normal error handling@@ -514,7 +550,7 @@ class CodexAgent(BaseAgent):self._turn_registry.clear_pending_turn_start(request.base_session_id, request)logger.error("Error in Codex handle_message: %s", e, exc_info=True)await self._record_model_hub_native_failure(request.context, str(e))- error_text = f"❌ Codex error: {e}"+ error_text = self._error_display_text(e)await emit_backend_failure(self.controller,request.context,@@ -945,6 +981,15 @@ class CodexAgent(BaseAgent):session_id = payload.get("agent_session_id") if isinstance(payload, dict) else Nonesetter(request.base_session_id, session_id)+ def _error_display_text(self, error: BaseException) -> str:+ if isinstance(error, CodexPromptRefreshUnavailableError):+ language = str(+ getattr(getattr(self.controller, "config", None), "language", "en")+ or "en"+ )+ return f"❌ {i18n_t('error.codexPromptRefreshUnavailable', language)}"+ return f"❌ Codex error: {error}"+def _runtime_ownership_target_for_cwd(self,cwd: str,@@ -1923,9 +1968,6 @@ class CodexAgent(BaseAgent):"sandbox": "danger-full-access",}self.ensure_agent_session_id(request)- developer_instructions = await self._build_thread_developer_instructions(request)- if developer_instructions:- params["developerInstructions"] = developer_instructionsgit_path_state, git_path_managed = self._inject_caller_env_config(params, request)resp = await transport.send_request("thread/start", params)@@ -1941,7 +1983,11 @@ class CodexAgent(BaseAgent):self._session_mgr.set_thread_id(request.base_session_id, thread_id)# Also persist for resume supportself.bind_agent_session_id(request, thread_id)- self._remember_thread_developer_instructions(request.base_session_id, thread_id, developer_instructions)+ self._remember_thread_model_settings_from_response(+ request.base_session_id,+ thread_id,+ resp,+ )self._remember_thread_caller_env_config(request.base_session_id,thread_id,@@ -1962,7 +2008,42 @@ class CodexAgent(BaseAgent):fork: dict[str, Any],) -> str:"""Fork an existing Codex thread and bind the new thread id."""- self.ensure_agent_session_id(request)+ target_agent_session_id = self.ensure_agent_session_id(request)+ (+ source_prompt_strategy,+ source_prompt_sha256,+ source_prompt_instructions,+ ) = self._fork_source_prompt_state(fork)+ if source_prompt_strategy == "injected_pending_persist":+ source_session_id = str(fork.get("source_session_id") or "").strip()+ source_thread_id = str(fork.get("source_native_session_id") or "").strip()+ pending = getattr(self, "_thread_unpersisted_prompts", {}).get(+ source_session_id+ )+ if (+ pending+ and pending[0] == source_thread_id+ and pending[2] in {"fallback", "fallback_pending_clear"}+ ):+ _, source_prompt_instructions, source_prompt_strategy = pending+ source_prompt_sha256 = self._prompt_fingerprint(+ source_prompt_instructions+ )+ else:+ # This process cannot prove which prompt bytes the source+ # injected, so a fork must not inherit an unrepairable state.+ source_prompt_strategy = "unavailable"+ source_prompt_sha256 = None+ source_prompt_instructions = None+ elif source_prompt_strategy == "fallback_pending_injection":+ # The source injection outcome is ambiguous. The fork already+ # carries whatever native history exists; never append it again.+ source_prompt_strategy = "unavailable"+ source_prompt_sha256 = None+ source_prompt_instructions = None+ elif source_prompt_strategy == "unavailable":+ source_prompt_sha256 = None+ source_prompt_instructions = None_, effective_model, _, _ = self._resolve_codex_agent_settings(request)source_thread_id = str(fork.get("source_native_session_id") or "").strip()params: Dict[str, Any] = {@@ -1971,9 +2052,17 @@ class CodexAgent(BaseAgent):"approvalPolicy": "never","sandbox": "danger-full-access",}- developer_instructions = await self._build_thread_developer_instructions(request)- if developer_instructions:- params["developerInstructions"] = developer_instructions+ if source_prompt_strategy is None and callable(+ getattr(+ getattr(self, "sessions", None),+ "get_agent_session_runtime_marker",+ None,+ )+ ):+ # Threads created before Turn-bound prompt delivery stored Avibe's+ # prompt as native thread configuration. Do not copy that legacy+ # configuration into a fork alongside the new delivery strategy.+ params["developerInstructions"] = Noneif effective_model:params["model"] = effective_modelgit_path_state, git_path_managed = self._inject_caller_env_config(params, request)@@ -1996,8 +2085,69 @@ class CodexAgent(BaseAgent):finally:self._clear_fork_correction_pending(request.base_session_id)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)+ target_agent_session_id = (+ self.bind_agent_session_id(request, thread_id) or target_agent_session_id+ )+ cache_source_prompt_strategy = True+ if source_prompt_instructions is not None:+ persisted_prompt_strategy = self._persist_prompt_strategy(+ request,+ thread_id,+ source_prompt_instructions,+ strategy=source_prompt_strategy,+ agent_session_id=target_agent_session_id,+ )+ if persisted_prompt_strategy:+ self._remember_thread_developer_instructions(+ request.base_session_id,+ thread_id,+ source_prompt_instructions,+ )+ elif source_prompt_sha256 is not None and source_prompt_strategy in {+ "fallback",+ "fallback_pending_clear",+ "fallback_pending_clear_injection",+ }:+ persisted_prompt_strategy = self._persist_prompt_strategy(+ request,+ thread_id,+ None,+ strategy=source_prompt_strategy,+ agent_session_id=target_agent_session_id,+ prompt_sha256=source_prompt_sha256,+ )+ # Let the first target Turn read and compare the carried fingerprint.+ # Caching only the strategy would make unchanged bytes look changed.+ cache_source_prompt_strategy = False+ elif source_prompt_strategy in {+ "collaboration",+ "fallback_pending_clear",+ "unavailable",+ }:+ persisted_prompt_strategy = self._persist_prompt_strategy(+ request,+ thread_id,+ None,+ strategy=source_prompt_strategy,+ agent_session_id=target_agent_session_id,+ )+ else:+ persisted_prompt_strategy = True+ if not persisted_prompt_strategy:+ raise CodexPromptRefreshUnavailableError(+ "Could not persist the forked Codex prompt strategy"+ )+ if source_prompt_strategy and cache_source_prompt_strategy:+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ source_prompt_strategy,+ )+ self._remember_thread_model_settings_from_response(+ request.base_session_id,+ thread_id,+ resp,+ )self._remember_thread_caller_env_config(request.base_session_id,thread_id,@@ -2076,11 +2226,31 @@ class CodexAgent(BaseAgent):request_effort = getattr(request, "subagent_reasoning_effort", None)vibe_model = getattr(request, "vibe_agent_model", None)vibe_effort = getattr(request, "vibe_agent_reasoning_effort", None)+ vibe_model_explicit = bool(getattr(request, "vibe_agent_model_explicit", False))+ vibe_effort_explicit = bool(+ getattr(request, "vibe_agent_reasoning_effort_explicit", False)+ )vibe_instructions = getattr(request, "vibe_agent_system_prompt", None)effective_agent = request_subagent or routing_agent- explicit_model = request_model or vibe_model or routing_model- explicit_effort = request_effort or vibe_effort or routing_effort+ if request_model is not None:+ selected_model = request_model+ selected_model_is_explicit = True+ elif vibe_model_explicit:+ selected_model = vibe_model+ selected_model_is_explicit = True+ else:+ selected_model = vibe_model or routing_model+ selected_model_is_explicit = False+ if request_effort is not None:+ selected_effort = request_effort+ selected_effort_is_explicit = True+ elif vibe_effort_explicit:+ selected_effort = vibe_effort+ selected_effort_is_explicit = True+ else:+ selected_effort = vibe_effort or routing_effort+ selected_effort_is_explicit = Falseagent_definition: Optional[SubagentDefinition] = Noneif effective_agent:@@ -2091,8 +2261,16 @@ class CodexAgent(BaseAgent):except Exception as exc:logger.warning("Failed to load Codex subagent %s: %s", effective_agent, exc)- effective_model = explicit_model or (agent_definition.model if agent_definition else None)- effective_effort = explicit_effort or (agent_definition.reasoning_effort if agent_definition else None)+ effective_model = (+ selected_model+ if selected_model_is_explicit+ else selected_model or (agent_definition.model if agent_definition else None)+ )+ effective_effort = (+ selected_effort+ if selected_effort_is_explicit+ else selected_effort or (agent_definition.reasoning_effort if agent_definition else None)+ )if getattr(self.controller, "model_hub_runtime", None) is not None:from modules.agents.model_hub import launch_for_context@@ -2149,11 +2327,24 @@ class CodexAgent(BaseAgent):if persisted:try:self.bind_agent_session_id(request, persisted)- developer_instructions = await self._build_thread_developer_instructions(request)resume_params: Dict[str, Any] = {"threadId": persisted,- "developerInstructions": developer_instructions,}+ marker_getter = getattr(+ getattr(self, "sessions", None),+ "get_agent_session_runtime_marker",+ None,+ )+ if callable(marker_getter):+ marker = self._read_persisted_prompt_strategy_marker(+ persisted,+ agent_session_id=self._prompt_state_agent_session_id(request),+ )+ if marker is None:+ # Older Avibe releases persisted their prompt as thread+ # configuration. Clear it before the first Turn selects+ # one of the new prompt-delivery strategies.+ resume_params["developerInstructions"] = Nonegit_path_state, git_path_managed = self._inject_caller_env_config(resume_params,request,@@ -2177,6 +2368,8 @@ class CodexAgent(BaseAgent):if isinstance(thread_obj, dict):thread_id = thread_obj.get("id", "")except Exception as e:+ if isinstance(e, CodexPromptRefreshUnavailableError):+ raiseif self._is_recoverable_transport_error(e):# Transient: reconnect the SAME thread (handled by the outer# retry) — not context loss, keep.@@ -2198,10 +2391,10 @@ class CodexAgent(BaseAgent):if not thread_id:raise CodexResumeUnavailableError(persisted, detail="thread/resume returned no thread id")self._session_mgr.set_thread_id(request.base_session_id, thread_id)- self._remember_thread_developer_instructions(+ self._remember_thread_model_settings_from_response(request.base_session_id,thread_id,- resume_params.get("developerInstructions"),+ resp,)self._remember_thread_caller_env_config(request.base_session_id,@@ -2308,12 +2501,7 @@ class CodexAgent(BaseAgent):return _CODEX_DEFAULT_PROVIDER_IDasync def _build_thread_developer_instructions(self, request: AgentRequest) -> Optional[str]:- """Build Codex thread-level developer instructions for start/resume.-- Codex treats these as session configuration, not appended chat history.- Passing the current value on resume refreshes stale Vibe Remote targeting- instructions without growing the thread transcript.- """+ """Render the developer instructions applied at the next Turn boundary."""_, _, _, agent_instructions = self._resolve_codex_agent_settings(request)platform = (request.context.platform@@ -2389,46 +2577,34 @@ class CodexAgent(BaseAgent):request: AgentRequest,thread_id: str,) -> None:- """Refresh thread-level instructions for already-cached Codex threads."""+ """Refresh mutable non-prompt thread config before starting a Turn."""self.ensure_agent_session_id(request)- developer_instructions = await self._build_thread_developer_instructions(request)- # Building the instructions also grants/revokes the per-turn Memory CLI- # capability, so resolve the caller environment only after that decision.+ # The caller invokes this after prompt rendering grants or revokes the+ # per-turn Memory CLI capability, so the environment observes that+ # decision without rendering the prompt a second time.caller_env = self._caller_env_for_request(request)git_path_state = self._git_path_state_for_request(request)- if not hasattr(self, "_thread_developer_instructions"):- self._thread_developer_instructions = {}if not hasattr(self, "_thread_caller_env_configs"):self._thread_caller_env_configs = {}if not hasattr(self, "_thread_git_path_configs"):self._thread_git_path_configs = {}- cached = self._thread_developer_instructions.get(request.base_session_id)cached_caller_env = self._thread_caller_env_configs.get(request.base_session_id)cached_git_path = self._thread_git_path_configs.get(request.base_session_id)git_path_changed = cached_git_path is None or cached_git_path[:2] != (thread_id,git_path_state,)- git_path_managed = bool(- cached_git_path- and cached_git_path[0] == thread_id- and cached_git_path[2]- )- if not developer_instructions and not caller_env and not git_path_changed:- return- if cached == (thread_id, developer_instructions) and (- not caller_env or cached_caller_env == (thread_id, caller_env)- ) and not git_path_changed:+ git_path_managed = bool(cached_git_path and cached_git_path[0] == thread_id and cached_git_path[2])+ caller_env_changed = bool(caller_env) and cached_caller_env != (thread_id, caller_env)+ if not caller_env_changed and not git_path_changed:returnresume_params: Dict[str, Any] = {"threadId": thread_id,}- if cached != (thread_id, developer_instructions):- resume_params["developerInstructions"] = developer_instructions- if caller_env or git_path_changed:+ if caller_env_changed or git_path_changed:git_path_state, git_path_managed = self._inject_caller_env_config(resume_params,request,@@ -2438,15 +2614,13 @@ class CodexAgent(BaseAgent):if model_provider:resume_params["modelProvider"] = model_provider+ if len(resume_params) == 1:+ return+await transport.send_request("thread/resume",resume_params,)- 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, caller_env)self._remember_thread_git_path_config(request.base_session_id,@@ -2467,6 +2641,86 @@ class CodexAgent(BaseAgent):self._thread_developer_instructions = {}self._thread_developer_instructions[base_session_id] = (thread_id, developer_instructions)+ def _remember_thread_prompt_strategy(+ self,+ base_session_id: str,+ thread_id: str,+ strategy: str,+ ) -> None:+ if not hasattr(self, "_thread_prompt_strategies"):+ self._thread_prompt_strategies = {}+ self._thread_prompt_strategies[base_session_id] = (thread_id, strategy)++ def _fork_source_prompt_state(+ self,+ fork: dict[str, Any],+ ) -> tuple[Optional[str], Optional[str], Optional[str]]:+ source_session_id = str(fork.get("source_session_id") or "").strip()+ source_thread_id = str(fork.get("source_native_session_id") or "").strip()+ if not source_session_id or not source_thread_id:+ return None, None, None++ cached_strategy = getattr(self, "_thread_prompt_strategies", {}).get(+ source_session_id+ )+ cached_instructions = getattr(+ self,+ "_thread_developer_instructions",+ {},+ ).get(source_session_id)+ instructions = (+ cached_instructions[1]+ if cached_instructions and cached_instructions[0] == source_thread_id+ else None+ )+ if cached_strategy and cached_strategy[0] == source_thread_id:+ strategy = cached_strategy[1]+ prompt_sha256 = (+ self._prompt_fingerprint(instructions) if instructions else None+ )+ if prompt_sha256 is None and strategy in {+ "fallback",+ "fallback_pending_clear",+ "fallback_pending_clear_injection",+ }:+ marker = self._read_persisted_prompt_strategy_marker(+ source_thread_id,+ agent_session_id=source_session_id,+ )+ if marker is not None and marker["strategy"] == strategy:+ prompt_sha256 = marker.get("sha256")+ return strategy, prompt_sha256, instructions++ marker = self._read_persisted_prompt_strategy_marker(+ source_thread_id,+ agent_session_id=source_session_id,+ )+ if marker is None:+ return None, None, None+ return marker["strategy"], marker.get("sha256"), instructions++ def _remember_thread_model_settings_from_response(+ self,+ base_session_id: str,+ thread_id: str,+ response: Any,+ ) -> None:+ if not isinstance(response, dict):+ return+ model = response.get("model")+ if not isinstance(model, str) or not model.strip():+ return+ effort = response.get("reasoningEffort")+ if not isinstance(effort, str):+ effort = None+ if not hasattr(self, "_thread_model_settings"):+ self._thread_model_settings = {}+ self._thread_model_settings[base_session_id] = (+ thread_id,+ model.strip(),+ effort,+ )+def _remember_thread_caller_env_config(self,base_session_id: str,@@ -2497,6 +2751,12 @@ class CodexAgent(BaseAgent):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_prompt_strategies"):+ self._thread_prompt_strategies.pop(base_session_id, None)+ if hasattr(self, "_thread_unpersisted_prompts"):+ self._thread_unpersisted_prompts.pop(base_session_id, None)+ if hasattr(self, "_thread_model_settings"):+ self._thread_model_settings.pop(base_session_id, None)if hasattr(self, "_thread_caller_env_configs"):self._thread_caller_env_configs.pop(base_session_id, None)if hasattr(self, "_thread_git_path_configs"):@@ -2516,16 +2776,410 @@ class CodexAgent(BaseAgent):def is_fork_correction_pending(self, base_session_id: str) -> bool:return base_session_id in self._fork_correction_pending_sessions()+ @staticmethod+ def _collaboration_mode_is_unsupported(error: BaseException) -> bool:+ message = str(error).casefold()+ names_field = "collaborationmode" in message or "collaboration_mode" in message+ unsupported = any(+ marker in message+ for marker in (+ "experimental api",+ "experimentalapi",+ "unknown field",+ "unsupported",+ "unrecognized",+ )+ )+ return names_field and unsupported++ async def _inject_thread_developer_instructions(+ self,+ transport: CodexTransport,+ request: AgentRequest,+ thread_id: str,+ developer_instructions: str,+ *,+ agent_session_id: Optional[str] = None,+ strategy: str = "fallback",+ ) -> None:+ """Fallback for Codex builds without Turn collaboration settings."""++ pending_strategy = (+ "fallback_pending_clear_injection"+ if strategy == "fallback_pending_clear"+ else "fallback_pending_injection"+ )+ if not self._persist_prompt_strategy(+ request,+ thread_id,+ developer_instructions,+ strategy=pending_strategy,+ agent_session_id=agent_session_id,+ ):+ # No native mutation happened, so volatile strategy selection can+ # be discarded and resolved again on a later retry.+ getattr(self, "_thread_prompt_strategies", {}).pop(+ request.base_session_id,+ None,+ )+ raise CodexPromptRefreshUnavailableError(+ "Could not prepare the fallback prompt strategy before injection"+ )+ # Keep the write-ahead state in memory too. If the RPC outcome is+ # ambiguous, a same-process retry must follow the same at-most-once+ # recovery path as a process restart.+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ pending_strategy,+ )+ await transport.send_request(+ "thread/inject_items",+ {+ "threadId": thread_id,+ "items": [+ {+ "type": "message",+ "role": "developer",+ "content": [+ {+ "type": "input_text",+ "text": developer_instructions,+ }+ ],+ }+ ],+ },+ )+ if not self._persist_prompt_strategy(+ request,+ thread_id,+ developer_instructions,+ strategy=strategy,+ agent_session_id=agent_session_id,+ ):+ self._remember_thread_developer_instructions(+ request.base_session_id,+ thread_id,+ developer_instructions,+ )+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ "injected_pending_persist",+ )+ if not hasattr(self, "_thread_unpersisted_prompts"):+ self._thread_unpersisted_prompts = {}+ self._thread_unpersisted_prompts[request.base_session_id] = (+ thread_id,+ developer_instructions,+ strategy,+ )+ raise CodexPromptRefreshUnavailableError(+ "Could not persist the fallback prompt strategy after injection"+ )+ getattr(self, "_thread_unpersisted_prompts", {}).pop(+ request.base_session_id,+ None,+ )+ self._remember_thread_developer_instructions(+ request.base_session_id,+ thread_id,+ developer_instructions,+ )+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ strategy,+ )++ @staticmethod+ def _prompt_fingerprint(developer_instructions: str) -> str:+ return hashlib.sha256(developer_instructions.encode("utf-8")).hexdigest()++ def _read_persisted_prompt_strategy_marker(+ self,+ thread_id: str,+ *,+ agent_session_id: Optional[str],+ ) -> Optional[dict[str, str]]:+ if not agent_session_id:+ return None+ getter = getattr(+ getattr(self, "sessions", None),+ "get_agent_session_runtime_marker",+ None,+ )+ if not callable(getter):+ return None+ try:+ marker = getter(+ agent_session_id,+ backend=self.name,+ native_session_id=thread_id,+ key=CODEX_PROMPT_STRATEGY_METADATA_KEY,+ )+ except Exception as exc:+ raise CodexPromptRefreshUnavailableError(+ "Could not resolve the Codex prompt strategy"+ ) from exc+ if marker is None:+ return None+ marker_thread_id = marker.get("thread_id") if isinstance(marker, dict) else None+ marker_strategy = marker.get("strategy") if isinstance(marker, dict) else None+ marker_sha256 = marker.get("sha256") if isinstance(marker, dict) else None+ marker_sha256_valid = bool(+ isinstance(marker_sha256, str)+ and len(marker_sha256) == 64+ and all(character in "0123456789abcdef" for character in marker_sha256)+ )+ marker_invalid = (+ marker_thread_id != thread_id+ or marker_strategy+ not in {+ "collaboration",+ "fallback",+ "fallback_pending_clear",+ "fallback_pending_injection",+ "fallback_pending_clear_injection",+ "unavailable",+ }+ or (marker_strategy == "fallback" and not marker_sha256_valid)+ or (+ marker_strategy+ in {+ "fallback_pending_injection",+ "fallback_pending_clear_injection",+ }+ and not marker_sha256_valid+ )+ or (+ marker_strategy+ in {"collaboration", "fallback_pending_clear"}+ and marker_sha256 is not None+ and not marker_sha256_valid+ )+ or (marker_strategy == "unavailable" and marker_sha256 is not None)+ )+ if marker_invalid:+ logger.warning(+ "Stored Codex prompt strategy marker is invalid for thread %s; "+ "continuing without prompt refresh",+ thread_id,+ )+ return {"thread_id": thread_id, "strategy": "unavailable"}+ if marker_strategy == "fallback_pending_injection":+ logger.warning(+ "Codex fallback prompt injection has an unknown outcome for thread %s; "+ "continuing without further prompt refresh",+ thread_id,+ )+ return {"thread_id": thread_id, "strategy": "unavailable"}+ resolved = {+ "thread_id": thread_id,+ "strategy": marker_strategy,+ }+ if marker_sha256_valid:+ resolved["sha256"] = marker_sha256+ return resolved++ def _prompt_state_agent_session_id(+ self,+ request: AgentRequest,+ ) -> Optional[str]:+ """Return the row that owns backend state, not necessarily visible output."""++ visible_session_id = self.ensure_agent_session_id(request)+ if not self._uses_namespaced_backend_session(+ request.context,+ subagent_name=getattr(request, "subagent_name", None),+ ):+ return visible_session_id++ getter = getattr(+ getattr(self, "sessions", None),+ "get_agent_session_row_id",+ None,+ )+ if not callable(getter):+ raise CodexPromptRefreshUnavailableError(+ "Could not resolve the Codex backend session binding"+ )+ try:+ backend_session_id = getter(+ request.session_key,+ request.base_session_id,+ self.name,+ )+ except Exception as exc:+ raise CodexPromptRefreshUnavailableError(+ "Could not resolve the Codex backend session binding"+ ) from exc+ if not backend_session_id:+ raise CodexPromptRefreshUnavailableError(+ "Could not resolve the Codex backend session binding"+ )+ return str(backend_session_id)++ def _persist_prompt_strategy(+ self,+ request: AgentRequest,+ thread_id: str,+ developer_instructions: Optional[str],+ *,+ strategy: str,+ agent_session_id: Optional[str],+ prompt_sha256: Optional[str] = None,+ ) -> bool:+ if strategy not in {+ "collaboration",+ "fallback",+ "fallback_pending_clear",+ "fallback_pending_injection",+ "fallback_pending_clear_injection",+ "unavailable",+ }:+ raise ValueError(f"Unsupported Codex prompt strategy: {strategy}")+ if prompt_sha256 is not None and (+ len(prompt_sha256) != 64+ or any(character not in "0123456789abcdef" for character in prompt_sha256)+ ):+ raise ValueError("Codex prompt fingerprint must be lowercase SHA-256")+ if strategy == "unavailable" and (+ developer_instructions or prompt_sha256 is not None+ ):+ raise ValueError("Unavailable prompt strategy cannot carry prompt identity")+ if strategy == "fallback" and not developer_instructions and not prompt_sha256:+ raise ValueError("Fallback prompt strategy requires developer instructions")+ if not agent_session_id:+ return True+ setter = getattr(+ getattr(self, "sessions", None),+ "set_agent_session_runtime_marker",+ None,+ )+ if not callable(setter):+ return True+ marker = {+ "thread_id": thread_id,+ "strategy": strategy,+ }+ if developer_instructions:+ computed_sha256 = self._prompt_fingerprint(developer_instructions)+ if prompt_sha256 is not None and prompt_sha256 != computed_sha256:+ raise ValueError("Codex prompt fingerprint does not match prompt bytes")+ marker["sha256"] = computed_sha256+ elif prompt_sha256 is not None:+ marker["sha256"] = prompt_sha256++ def _set_marker(target_session_id: str) -> bool:+ return bool(+ setter(+ target_session_id,+ backend=self.name,+ native_session_id=thread_id,+ key=CODEX_PROMPT_STRATEGY_METADATA_KEY,+ value=marker,+ )+ )++ try:+ persisted = _set_marker(agent_session_id)+ except Exception:+ logger.warning("Failed to persist Codex prompt strategy", exc_info=True)+ return False+ if not persisted:+ # A native thread is cached before its durable Session bind. The+ # Workbench binder deliberately preserves the selected row when a+ # first bind fails, so retry that exact bind before treating the+ # marker as unavailable on every later Turn.+ try:+ rebound_session_id = self.bind_agent_session_id(request, thread_id)+ persisted = bool(rebound_session_id) and _set_marker(+ str(rebound_session_id)+ )+ except Exception:+ logger.warning(+ "Failed to rebind the Codex Session before prompt marker persistence",+ exc_info=True,+ )+ persisted = False+ if not persisted:+ logger.warning(+ "Skipped Codex prompt strategy for stale Session binding %s",+ agent_session_id,+ )+ return False+ return True++ def _repair_unpersisted_prompt_strategy(+ self,+ request: AgentRequest,+ thread_id: str,+ *,+ agent_session_id: Optional[str],+ ) -> str:+ pending = getattr(self, "_thread_unpersisted_prompts", {}).get(+ request.base_session_id+ )+ if not pending or pending[0] != thread_id:+ raise CodexPromptRefreshUnavailableError(+ "The injected Codex prompt strategy cannot be recovered"+ )+ _, injected_instructions, target_strategy = pending+ if not self._persist_prompt_strategy(+ request,+ thread_id,+ injected_instructions,+ strategy=target_strategy,+ agent_session_id=agent_session_id,+ ):+ raise CodexPromptRefreshUnavailableError(+ "Could not persist the injected Codex prompt strategy"+ )+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ target_strategy,+ )+ self._thread_unpersisted_prompts.pop(request.base_session_id, None)+ return target_strategy++ @staticmethod+ async def _confirm_collaboration_mode_capability(transport: CodexTransport) -> None:+ if getattr(transport, "supports_turn_collaboration_mode", False):+ return+ try:+ await transport.send_request("collaborationMode/list", {})+ except Exception as exc:+ raise CodexPromptRefreshUnavailableError(+ "Cannot safely resume a collaboration-backed Codex thread because "+ "the current app-server did not confirm collaboration mode support"+ ) from exc+ transport.supports_turn_collaboration_mode = True+async def _start_turn(self,transport: CodexTransport,request: AgentRequest,thread_id: str,+ *,+ developer_instructions: Optional[str] = None,) -> str:"""Build input, configure overrides, and send turn/start to Codex."""- self.ensure_agent_session_id(request)+ agent_session_id = self._prompt_state_agent_session_id(request)input_items = self._build_input(request)_, effective_model, effective_effort, _ = self._resolve_codex_agent_settings(request)+ model_explicit = bool(getattr(request, "vibe_agent_model_explicit", False))+ effort_explicit = bool(+ getattr(request, "vibe_agent_reasoning_effort_explicit", False)+ )+ cached_model_settings = getattr(self, "_thread_model_settings", {}).get(request.base_session_id)+ if cached_model_settings and cached_model_settings[0] == thread_id:+ if effective_model is None and not model_explicit:+ effective_model = cached_model_settings[1]+ if effective_effort is None and not effort_explicit:+ effective_effort = cached_model_settings[2]turn_params: Dict[str, Any] = {"threadId": thread_id,@@ -2533,11 +3187,150 @@ class CodexAgent(BaseAgent):"approvalPolicy": "never","sandboxPolicy": {"type": "dangerFullAccess"},}- if effective_model:+ if effective_model is not None or model_explicit:turn_params["model"] = effective_model- if effective_effort:+ if effective_effort is not None or effort_explicit:turn_params["effort"] = effective_effort+ cached_instructions = getattr(self, "_thread_developer_instructions", {}).get(request.base_session_id)+ prompt_changed = cached_instructions != (thread_id, developer_instructions)+ cached_strategy = getattr(self, "_thread_prompt_strategies", {}).get(request.base_session_id)+ prompt_strategy = cached_strategy[1] if cached_strategy and cached_strategy[0] == thread_id else None+ if prompt_strategy == "injected_pending_persist":+ prompt_strategy = self._repair_unpersisted_prompt_strategy(+ request,+ thread_id,+ agent_session_id=agent_session_id,+ )+ if prompt_strategy == "fallback_pending_injection":+ # The native injection may already have succeeded. Never append it+ # again when only its RPC acknowledgement is unknown.+ prompt_strategy = "unavailable"+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ prompt_strategy,+ )+ persisted_prompt_marker = None+ if developer_instructions and prompt_strategy is None:+ persisted_prompt_marker = self._read_persisted_prompt_strategy_marker(+ thread_id,+ agent_session_id=agent_session_id,+ )+ if persisted_prompt_marker is not None:+ prompt_strategy = persisted_prompt_marker["strategy"]+ elif effective_model and getattr(transport, "supports_turn_collaboration_mode", True):+ prompt_strategy = (+ "collaboration"+ if self._persist_prompt_strategy(+ request,+ thread_id,+ developer_instructions,+ strategy="collaboration",+ agent_session_id=agent_session_id,+ )+ else "fallback"+ )+ else:+ prompt_strategy = "fallback"+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ prompt_strategy,+ )+ fallback_prompt_is_current = bool(+ developer_instructions+ and persisted_prompt_marker+ and persisted_prompt_marker["strategy"]+ in {"fallback", "fallback_pending_clear"}+ and persisted_prompt_marker.get("sha256")+ == self._prompt_fingerprint(developer_instructions)+ )+ if fallback_prompt_is_current:+ self._remember_thread_developer_instructions(+ request.base_session_id,+ thread_id,+ developer_instructions,+ )+ prompt_changed = False+ pending_clear_after_unknown_injection = (+ prompt_strategy == "fallback_pending_clear_injection"+ )+ if prompt_strategy in {+ "collaboration",+ "fallback_pending_clear",+ "fallback_pending_clear_injection",+ }:+ await self._confirm_collaboration_mode_capability(transport)+ collaboration_mode_is_known = bool(+ getattr(transport, "supports_turn_collaboration_mode", True)+ )+ collaboration_strategy_has_no_model = bool(+ developer_instructions+ and prompt_strategy == "collaboration"+ and not effective_model+ )+ clear_collaboration_mode = collaboration_mode_is_known and bool(+ prompt_strategy+ in {"fallback_pending_clear", "fallback_pending_clear_injection"}+ or (model_explicit and effective_model is None)+ or collaboration_strategy_has_no_model+ )+ if clear_collaboration_mode:+ was_collaboration = prompt_strategy == "collaboration"+ turn_params["collaborationMode"] = None+ if developer_instructions and not pending_clear_after_unknown_injection:+ prompt_strategy = (+ "fallback_pending_clear"+ if was_collaboration+ or prompt_strategy == "fallback_pending_clear"+ else "fallback"+ )+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ prompt_strategy,+ )+ if was_collaboration and not fallback_prompt_is_current:+ prompt_changed = True+ use_collaboration_mode = bool(+ developer_instructions+ and effective_model+ and prompt_strategy == "collaboration"+ and collaboration_mode_is_known+ )+ if use_collaboration_mode:+ # Codex keeps the collaboration world state across Turns and emits+ # a new developer fragment only when these exact bytes change. The+ # explicit model and effort preserve the route because the mode+ # takes precedence over the sibling turn fields.+ turn_params["collaborationMode"] = {+ "mode": "default",+ "settings": {+ "model": effective_model,+ "reasoning_effort": effective_effort,+ "developer_instructions": developer_instructions,+ },+ }+ elif (+ developer_instructions+ and prompt_changed+ and prompt_strategy+ not in {"unavailable", "fallback_pending_clear_injection"}+ ):+ await self._inject_thread_developer_instructions(+ transport,+ request,+ thread_id,+ developer_instructions,+ agent_session_id=agent_session_id,+ strategy=(+ "fallback_pending_clear"+ if prompt_strategy == "fallback_pending_clear"+ else "fallback"+ ),+ )+self._write_caller_env_script(request)self._turn_registry.begin_turn_start(request, thread_id)event_handler = getattr(self, "_event_handler", None)@@ -2549,7 +3342,100 @@ class CodexAgent(BaseAgent):if callable(snapshot_generated_images):snapshot_generated_images(thread_id, request.base_session_id)mark_backend_dispatch_attempted(request.context)- resp = await transport.send_request("turn/start", turn_params)+ try:+ resp = await transport.send_request("turn/start", turn_params)+ except Exception as exc:+ if prompt_strategy in {+ "fallback_pending_clear",+ "fallback_pending_clear_injection",+ }:+ raise CodexPromptRefreshUnavailableError(+ "Could not confirm that Codex cleared the previous collaboration prompt"+ ) from exc+ if (+ "collaborationMode" not in turn_params+ or not self._collaboration_mode_is_unsupported(exc)+ ):+ raise+ logger.warning(+ "Codex turn collaboration mode is unavailable; falling back to developer item injection: %s",+ exc,+ )+ transport.supports_turn_collaboration_mode = False+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ "fallback",+ )+ if developer_instructions and not fallback_prompt_is_current:+ await self._inject_thread_developer_instructions(+ transport,+ request,+ thread_id,+ developer_instructions,+ agent_session_id=agent_session_id,+ )+ fallback_turn_params = dict(turn_params)+ fallback_turn_params.pop("collaborationMode", None)+ resp = await transport.send_request("turn/start", fallback_turn_params)++ if prompt_strategy == "fallback_pending_clear" and developer_instructions:+ if self._persist_prompt_strategy(+ request,+ thread_id,+ developer_instructions,+ strategy="fallback",+ agent_session_id=agent_session_id,+ ):+ prompt_strategy = "fallback"+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ prompt_strategy,+ )+ else:+ logger.warning(+ "Codex collaboration clear succeeded but its completed prompt strategy marker remains pending"+ )+ elif (+ prompt_strategy == "fallback_pending_clear_injection"+ and developer_instructions+ ):+ # The clear is confirmed, but the preceding injection outcome is+ # unknowable. Lock this thread against later prompt reinjection.+ if self._persist_prompt_strategy(+ request,+ thread_id,+ None,+ strategy="unavailable",+ agent_session_id=agent_session_id,+ ):+ prompt_strategy = "unavailable"+ self._remember_thread_prompt_strategy(+ request.base_session_id,+ thread_id,+ prompt_strategy,+ )+ else:+ logger.warning(+ "Codex collaboration clear succeeded but the unknown injection marker remains pending"+ )++ if use_collaboration_mode and developer_instructions:+ self._remember_thread_developer_instructions(+ request.base_session_id,+ thread_id,+ developer_instructions,+ )+ if effective_model:+ self._thread_model_settings = getattr(self, "_thread_model_settings", {})+ self._thread_model_settings[request.base_session_id] = (+ thread_id,+ effective_model,+ effective_effort,+ )+ elif model_explicit:+ getattr(self, "_thread_model_settings", {}).pop(request.base_session_id, None)turn_id = resp.get("id", "")if not turn_id:@@ -2718,7 +3604,7 @@ class CodexAgent(BaseAgent):method: str,params: Dict[str, Any],) -> Dict[str, Any]:- """Handle server requests — auto-approve all."""+ """Handle server requests that Avibe opts into or auto-approves."""if method in ("item/commandExecution/requestApproval","item/fileChange/requestApproval",@@ -2726,8 +3612,21 @@ class CodexAgent(BaseAgent):logger.info("Auto-approving Codex %s (item=%s)", method, params.get("itemId"))return {"approved": True}- logger.warning("Unknown Codex server request: %s", method)- return {"approved": True}+ if method == "item/tool/requestUserInput":+ # Avibe conversations collect user input through the next normal+ # message. An empty answer map is the app-server's valid+ # unsupported/cancelled response for this experimental request.+ logger.info(+ "Declining unsupported Codex requestUserInput (item=%s)",+ params.get("itemId"),+ )+ return {"answers": {}}++ if method == "currentTime/read":+ return {"currentTimeAt": int(time.time())}++ logger.warning("Unsupported Codex server request: %s", method)+ raise NotImplementedError(f"Unsupported Codex server request: {method}")# ------------------------------------------------------------------# Helpersdiff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.pyindex 7e23e73cc..9a92228dc 100644--- a/modules/agents/codex/transport.py+++ b/modules/agents/codex/transport.py@@ -51,6 +51,7 @@ AVIBE_APP_SERVER_CONFIG_OVERRIDES = ("features.tool_call_mcp_elicitation=false","features.tool_suggest=false","features.workspace_dependencies=false",+ "skills.include_instructions=false",)@@ -89,6 +90,7 @@ class CodexTransport:self._pending: dict[int | str, asyncio.Future[dict[str, Any]]] = {}self._write_lock = asyncio.Lock()self._initialized = False+ self.supports_turn_collaboration_mode = Falseself._reader_task: Optional[asyncio.Task[None]] = Noneself._stderr_task: Optional[asyncio.Task[None]] = None@@ -161,13 +163,27 @@ class CodexTransport:"title": "Avibe","version": "1.0.0",},- # Avibe intentionally consumes only the stable app-server- # contract. Omitted server-request capabilities stay off.- "capabilities": {"experimentalApi": False},+ # Dynamic developer instructions for an existing native+ # thread use turn/start.collaborationMode. Omitted+ # server-request capabilities remain disabled.+ "capabilities": {"experimentalApi": True},},)logger.info("Codex app-server initialized: %s", resp)await self.send_notification("initialized")+ try:+ await self.send_request("collaborationMode/list", {})+ except Exception as exc:+ # Older app-servers accept unknown turn fields, so the catalog+ # method is the capability probe. Fall back to item injection+ # on any inconclusive result rather than risk dropping the+ # developer instructions silently.+ logger.info(+ "Codex turn collaboration mode is unavailable; using developer item injection: %s",+ exc,+ )+ else:+ self.supports_turn_collaboration_mode = Trueself._initialized = Trueexcept BaseException as exc:if isinstance(exc, asyncio.CancelledError):diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex aa8ec8943..2e8a56093 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -89,7 +89,9 @@ from .poll_loop import (restored_session_key_from_poll_info,)from .server import (+ OpenCodeManagedPolicyRefreshPendingError,OpenCodePromptRejectedError,+ OpenCodeRuntimeConfigInvalidError,OpenCodeServerManager,native_part_id_for_attempt,)@@ -730,6 +732,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):if restored_server is not None:return restored_serverserver = await self._client_manager.get_server()+ server.set_active_poll_session_ids_provider(+ lambda: set(self.sessions.get_all_active_polls())+ )self._attach_server_activation(server)return server@@ -933,6 +938,20 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):variant=reasoning_effort or default_label,)+ def _server_start_error_display_text(self, error: BaseException) -> str:+ localized_key = None+ if isinstance(error, OpenCodeManagedPolicyRefreshPendingError):+ localized_key = "error.opencodePolicyRefreshPending"+ elif isinstance(error, OpenCodeRuntimeConfigInvalidError):+ localized_key = "error.opencodeRuntimeConfigInvalid"+ if localized_key is not None:+ language = str(+ getattr(getattr(self.controller, "config", None), "language", "en")+ or "en"+ )+ return f"❌ {i18n_t(localized_key, language)}"+ return f"Failed to start OpenCode server: {error}"+async def prepare_runtime_restart(self) -> None:"""Adopt persisted server state before the shared drain snapshot."""await self._get_server()@@ -1152,12 +1171,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):caller_context_binding_path: str | None = Nonecaller_context_binding_renewal: asyncio.Task[None] | None = Noneactive_poll_persisted = False+ active_poll_removal_pending = Falsedef remove_active_poll() -> None:- nonlocal active_poll_persisted+ nonlocal active_poll_persisted, active_poll_removal_pendingif session_id:- self.sessions.remove_active_poll(session_id)active_poll_persisted = False+ active_poll_removal_pending = Truetry:model_hub_runtime = getattr(self.controller, "model_hub_runtime", None)turn_mode = getattr(model_hub_runtime, "turn_mode", None)@@ -1197,7 +1217,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):request.context,self.name,str(e),- display_text=f"Failed to start OpenCode server: {e}",+ display_text=self._server_start_error_display_text(e),request=request,)await self._remove_ack_reaction(request)@@ -1810,6 +1830,19 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await self._stop_caller_context_binding_renewal(caller_context_binding_renewal)+ if steer_state is not None:+ async with steer_state.lock:+ steer_state.closing = True+ if self._steering_states.get(request.base_session_id) is steer_state:+ self._steering_states.pop(request.base_session_id, None)+ if active_poll_removal_pending and run_registered:+ active_poll_persisted = not await self._retire_active_poll(+ server,+ session_id,+ )+ elif active_poll_removal_pending and session_id:+ self.sessions.remove_active_poll(session_id)+ active_poll_persisted = Falseif (caller_context_binding_session_idand caller_context_binding_token@@ -1828,13 +1861,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):caller_context_binding_session_id,exc_info=True,)- if steer_state is not None:- async with steer_state.lock:- steer_state.closing = True- if self._steering_states.get(request.base_session_id) is steer_state:- self._steering_states.pop(request.base_session_id, None)- if run_registered:- await server.mark_run_inactive(session_id)await self._release_model_hub_overlay_reservation(server,model_hub_overlay_reservation,@@ -1858,6 +1884,22 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):exc_info=True,)+ async def _retire_active_poll(+ self,+ server: Any,+ session_id: str,+ ) -> bool:+ try:+ await server.mark_run_inactive(session_id)+ except Exception:+ logger.exception(+ "Failed to clear OpenCode run marker for session=%s; preserving its active poll",+ session_id,+ )+ return False+ self.sessions.remove_active_poll(session_id)+ return True+async def _finish_prestart_cancellation(self,request: AgentRequest,@@ -2226,8 +2268,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):# past the handlers; a claimed intent is already gone.self._user_stopped_sessions.discard(request.base_session_id)- if opencode_session_id:- self.sessions.remove_active_poll(opencode_session_id)+ if opencode_session_id and self._active_poll_is_persisted(+ opencode_session_id+ ):+ server = await self._get_server()+ await self._retire_active_poll(server, opencode_session_id)# A user-initiated stop is terminal but intentional, so it carries NO# user-facing message: a single SILENT result settles the dot to idle +@@ -2264,7 +2309,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):except asyncio.CancelledError:passterminated += 1- self.sessions.remove_active_poll(opencode_session_id)+ if self._active_poll_is_persisted(opencode_session_id):+ server = await self._get_server()+ await self._retire_active_poll(server, opencode_session_id)return terminatedasync def _abort_active_request(@@ -2485,6 +2532,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):)continuelogger.info(f"OpenCode session {session_id} has completed, removing from active polls")+ try:+ await server.mark_run_inactive(poll_info.opencode_session_id)+ except Exception:+ logger.exception(+ "Failed to clear OpenCode run marker for session=%s; "+ "preserving its active poll and continuing restoration",+ poll_info.opencode_session_id,+ )+ continueawait self._poll_loop.remove_restored_ack(poll_info)stale_poll_ids.append(session_id)continue@@ -2667,6 +2723,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):steer_state = Noneserver = Nonerestoration_registered = False+ terminal_poll_cleanup = Falsecaller_context_binding_renewal = (asyncio.create_task(self._maintain_caller_context_binding(@@ -2779,7 +2836,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):)if delivery_recovery_complete is not None:await delivery_recovery_complete.wait()- await self._poll_loop.run_restored_poll_loop(poll_info)+ terminal_poll_cleanup = bool(+ await self._poll_loop.run_restored_poll_loop(poll_info)+ )except Exception as err:if restoration_registered:raise@@ -2810,7 +2869,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):logical_turn_id,)if terminal_persisted:- self.sessions.remove_active_poll(poll_info.opencode_session_id)+ terminal_poll_cleanup = Truelogger.error("OpenCode poll registration failed for session=%s: %s",poll_info.opencode_session_id,@@ -2820,6 +2879,18 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await self._stop_caller_context_binding_renewal(caller_context_binding_renewal)+ if current_task is not None:+ self._restored_poll_servers.pop(current_task, None)+ if steer_state is not None:+ async with steer_state.lock:+ steer_state.closing = True+ if self._steering_states.get(poll_info.base_session_id) is steer_state:+ self._steering_states.pop(poll_info.base_session_id, None)+ if terminal_poll_cleanup and server is not None:+ await self._retire_active_poll(+ server,+ poll_info.opencode_session_id,+ )if caller_context_binding_token and not self._active_poll_is_persisted(poll_info.opencode_session_id):@@ -2836,21 +2907,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):poll_info.opencode_session_id,exc_info=True,)- if current_task is not None:- self._restored_poll_servers.pop(current_task, None)- if steer_state is not None:- async with steer_state.lock:- steer_state.closing = True- if self._steering_states.get(poll_info.base_session_id) is steer_state:- self._steering_states.pop(poll_info.base_session_id, None)- if server is not None:- try:- await server.mark_run_inactive(poll_info.opencode_session_id)- except Exception:- logger.exception(- "Failed to clear restored OpenCode run marker for session=%s",- poll_info.opencode_session_id,- )if self._active_requests.get(poll_info.base_session_id) is current_task:self._active_requests.pop(poll_info.base_session_id, None)self._session_manager.pop_request_session(poll_info.base_session_id)diff --git a/modules/agents/opencode/caller_context.py b/modules/agents/opencode/caller_context.pyindex a71c80aaa..3baf53aed 100644--- a/modules/agents/opencode/caller_context.py+++ b/modules/agents/opencode/caller_context.py@@ -1,9 +1,11 @@-"""OpenCode caller-context bridge.+"""OpenCode runtime bridge.OpenCode runs a shared ``opencode serve`` process, so per-Agent Avibe contextcannot live in the server process environment. Instead Avibe installs a tinyOpenCode 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.+Avibe-managed binding file and injects the AVIBE_* env vars for that call. The+same process-scoped plugin removes OpenCode's native Skill Catalog after its+system prompt is assembled; Avibe supplies the managed Catalog instead."""from __future__ import annotations@@ -29,6 +31,9 @@ PLUGIN_SOURCE = r"""import { readFileSync } from "node:fs"const bindingPath = process.env.AVIBE_OPENCODE_CALLER_CONTEXT_PATH+const nativeSkillIntro = "Skills provide specialized instructions and workflows for specific tasks."+const nativeSkillPrefix = "<available_skills>"+const nativeSkillSuffix = "</available_skills>"function readBindings() {if (!bindingPath) return {}@@ -50,6 +55,22 @@ function applyEnv(output, env) {}}+function stripNativeSkillCatalog(text) {+ let current = text+ while (true) {+ const catalog = current.indexOf(nativeSkillPrefix)+ if (catalog < 0) return current+ const intro = current.lastIndexOf(nativeSkillIntro, catalog)+ const start = intro >= 0 && catalog - intro < 500 ? intro : catalog+ const close = current.indexOf(nativeSkillSuffix, catalog + nativeSkillPrefix.length)+ if (close < 0) return current+ let before = current.slice(0, start)+ let after = current.slice(close + nativeSkillSuffix.length)+ if (before.endsWith("\n") && after.startsWith("\n")) after = after.slice(1)+ current = before + after+ }+}+export const AvibeCallerContextPlugin = async () => ({"shell.env": async (input, output) => {const sessionID = input && typeof input.sessionID === "string" ? input.sessionID : ""@@ -60,6 +81,15 @@ export const AvibeCallerContextPlugin = async () => ({if (expiresAt && Date.now() > expiresAt) returnapplyEnv(output, binding.env)},+ "experimental.chat.system.transform": async (_input, output) => {+ // The plugin is installed in the user's global OpenCode directory, but this+ // policy belongs only to the Avibe-managed server process.+ if (!bindingPath || !output || !Array.isArray(output.system)) return+ const transformed = output.system+ .map((text) => typeof text === "string" ? stripNativeSkillCatalog(text) : text)+ .filter((text) => typeof text !== "string" || text.length > 0)+ output.system.splice(0, output.system.length, ...transformed)+ },})""".lstrip()diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex 8f79e9a38..af6c6444f 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -773,7 +773,7 @@ class OpenCodePollLoop:return final_text, True- async def run_restored_poll_loop(self, poll_info) -> None:+ async def run_restored_poll_loop(self, poll_info) -> bool:"""Continue a poll loop that was interrupted by restart."""session_id = poll_info.opencode_session_id@@ -830,9 +830,8 @@ class OpenCodePollLoop:working_path=poll_info.working_path,timeout_seconds=timeout_seconds,)- self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)- return+ return Truetry:messages = await asyncio.wait_for(server.list_messages(@@ -863,9 +862,8 @@ class OpenCodePollLoop:working_path=poll_info.working_path,timeout_seconds=timeout_seconds,)- self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)- return+ return Truepoll_failures += 1if poll_failures >= _POLL_FAILURE_SETTLE_LIMIT:await self._settle_poll_transport_failure(@@ -875,9 +873,8 @@ class OpenCodePollLoop:working_path=poll_info.working_path,failures=poll_failures,)- self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)- return+ return Truelogger.warning("Timed out polling restored OpenCode messages before the active-turn deadline")@@ -893,9 +890,8 @@ class OpenCodePollLoop:working_path=poll_info.working_path,failures=poll_failures,)- self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)- return+ return Truelogger.warning(f"Failed to poll OpenCode messages (restored): {poll_err}")await self._sleep_with_deadline(deadline)continue@@ -936,9 +932,8 @@ class OpenCodePollLoop:await server.abort_session(session_id, poll_info.working_path)except Exception as abort_err:logger.warning("Failed to abort disabled question session %s: %s", session_id, abort_err)- self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)- return+ return Trueseen_tool_calls.add(call_key)@@ -1015,9 +1010,8 @@ class OpenCodePollLoop:request=restored_request,failure_id=str(last_info.get("id") or ""),)- self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)- return+ return Trueawait self._sleep_with_deadline(deadline)continue@@ -1066,7 +1060,7 @@ class OpenCodePollLoop:# Clean up ack reaction after result is sentawait self.remove_restored_ack(poll_info)- self._agent.sessions.remove_active_poll(session_id)+ return Trueexcept asyncio.CancelledError:logger.info(f"Restored OpenCode poll cancelled for {poll_info.base_session_id}")@@ -1075,7 +1069,6 @@ class OpenCodePollLoop:restored_request,terminal_emoji=STOPPED_REACTION_EMOJI if stopped_by_user else None,)- self._agent.sessions.remove_active_poll(session_id)raiseexcept Exception as e:error_name = type(e).__name__@@ -1089,7 +1082,6 @@ class OpenCodePollLoop:except Exception as abort_err:logger.warning(f"Failed to abort OpenCode session after error: {abort_err}")- self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)message = f"Restored OpenCode session failed: {error_text}"@@ -1102,3 +1094,4 @@ class OpenCodePollLoop:request=restored_request,failure_id=session_id,)+ return Truediff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 613869a49..897ca85af 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -34,6 +34,7 @@ from vibe import runtimefrom vibe.opencode_config import (get_opencode_custom_provider_adapter,load_first_opencode_user_config,+ parse_jsonc_object,read_opencode_provider_auth_entries,)@@ -49,6 +50,54 @@ MODEL_HUB_OVERLAY_DRAIN_TIMEOUT_SECONDS = 30.0_USE_CURRENT_CALLER_CONTEXT_PATH = object()_CURRENT_OWNER_PID = os.getpid()_DURABLE_ATTEMPT_ID_RE = re.compile(r"^atm_([0-9a-f]{32})$")+# Bump whenever the process-level Avibe policy applied in ``_start_server``+# changes so an adopted process cannot silently keep the previous behavior.+_MANAGED_RUNTIME_POLICY_REVISION = "disable-native-skill-v2"+++class OpenCodeRuntimeConfigInvalidError(RuntimeError):+ """The inherited OpenCode runtime override cannot be safely managed."""+++def _managed_runtime_config_content(raw: str | bytes | None) -> str:+ """Apply Avibe-owned OpenCode runtime policy without mutating user config."""++ if raw is None:+ payload: Any = {}+ else:+ try:+ content = raw.decode("utf-8-sig") if isinstance(raw, bytes) else raw+ if not isinstance(content, str):+ raise TypeError("runtime config override must be text")+ payload = parse_jsonc_object(content)+ except (TypeError, UnicodeDecodeError, ValueError) as exc:+ raise OpenCodeRuntimeConfigInvalidError(+ "OpenCode runtime config override is invalid JSONC"+ ) from exc+ if not isinstance(payload, dict):+ raise OpenCodeRuntimeConfigInvalidError(+ "OpenCode runtime config override must be a JSON object"+ )++ tools = payload.get("tools")+ managed_tools = dict(tools) if isinstance(tools, dict) else {}+ managed_tools["skill"] = False+ payload["tools"] = managed_tools++ permission = payload.get("permission")+ if permission is None:+ managed_permission: dict[str, Any] = {}+ elif isinstance(permission, str):+ managed_permission = {"*": permission}+ elif isinstance(permission, dict):+ managed_permission = dict(permission)+ else:+ raise OpenCodeRuntimeConfigInvalidError(+ "OpenCode runtime permission override must be a string or object"+ )+ managed_permission["skill"] = "deny"+ payload["permission"] = managed_permission+ return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":")) + "\n"def _percent_encode_path(path: str) -> str:@@ -207,6 +256,10 @@ class OpenCodePromptRejectedError(RuntimeError):return self.status == 400+class OpenCodeManagedPolicyRefreshPendingError(RuntimeError):+ """The adopted OpenCode process cannot apply Avibe's current policy yet."""++class OpenCodeServerManager:"""Manages a singleton OpenCode server process shared across all working directories."""@@ -244,6 +297,7 @@ class OpenCodeServerManager:self._pid_file = paths.get_logs_dir() / "opencode_server.json"self._active_requests = 0self._active_run_sessions: set[str] = set()+ self._active_poll_session_ids_provider: Callable[[], set[str]] | None = Noneself._auth_refresh_pending = Falseself._auth_refresh_pending_port: Optional[int] = Noneself._caller_context_plugin_refresh_pending = False@@ -269,6 +323,14 @@ class OpenCodeServerManager:) -> None:self._runtime_activation_retire = callback+ def set_active_poll_session_ids_provider(+ self,+ provider: Callable[[], set[str]],+ ) -> None:+ """Attach the durable recovery records that confirm adopted run markers."""++ self._active_poll_session_ids_provider = provider+@staticmethoddef _runtime_token_from_pid_info(info: Optional[Dict[str, Any]],@@ -585,6 +647,53 @@ class OpenCodeServerManager:def _has_active_run_sessions(self) -> bool:return bool(self._active_run_sessions)+ def _reconcile_adopted_active_run_sessions(+ self,+ info: Optional[Dict[str, Any]],+ ) -> Optional[Dict[str, Any]]:+ """Discard adopted pre-write markers that have no durable recovery poll."""++ if self._active_run_sessions or not self._pid_file_references_current_server(info):+ return info+ active = info.get("active_run_sessions") if isinstance(info, dict) else None+ if not isinstance(active, list) or not active:+ return info+ if any(not isinstance(item, str) or not item for item in active):+ return info+ provider = self._active_poll_session_ids_provider+ if provider is None:+ return info+ try:+ durable = provider()+ except Exception:+ logger.warning(+ "Could not reconcile adopted OpenCode run markers with durable polls",+ exc_info=True,+ )+ return info+ if any(not isinstance(item, str) or not item for item in durable):+ logger.warning("Ignoring invalid OpenCode durable active-poll identifiers")+ return info++ retained = set(active).intersection(durable)+ revised = dict(info)+ revised["active_run_sessions"] = sorted(retained)+ if retained != set(active):+ try:+ self._pid_file.write_text(json.dumps(revised))+ except Exception:+ logger.warning(+ "Could not persist reconciled OpenCode run markers",+ exc_info=True,+ )+ return info+ logger.info(+ "Removed %s orphaned OpenCode run marker(s) without durable polls",+ len(set(active) - retained),+ )+ self._active_run_sessions = retained+ return revised+def runtime_has_active_turns(self) -> bool:if self._active_requests > 0 or self._has_active_run_sessions():return True@@ -741,18 +850,19 @@ class OpenCodeServerManager:)if reserved_overlay is None:raise RuntimeError("OpenCode overlay reservation is no longer active")- run_was_active = session_id in self._active_run_sessions- self._active_run_sessions.add(session_id)+ previous_active_runs = set(self._active_run_sessions)if overlay_reservation is not None:self._model_hub_overlay_reservations.pop(overlay_reservation,None,)try:- self._write_active_run_sessions_to_pid_file()+ self._active_run_sessions = self._persist_active_run_session_change(+ session_id,+ active=True,+ )except Exception:- if not run_was_active:- self._active_run_sessions.discard(session_id)+ self._active_run_sessions = previous_active_runsif overlay_reservation is not None and reserved_overlay is not None:self._model_hub_overlay_reservations[overlay_reservation@@ -761,8 +871,15 @@ class OpenCodeServerManager: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()+ previous_active_runs = set(self._active_run_sessions)+ try:+ self._active_run_sessions = self._persist_active_run_session_change(+ session_id,+ active=False,+ )+ except Exception:+ self._active_run_sessions = previous_active_runs+ raise@asynccontextmanagerasync def _request_scope(self):@@ -799,6 +916,7 @@ class OpenCodeServerManager:*,caller_context_path: object = _USE_CURRENT_CALLER_CONTEXT_PATH,owner_pid: Optional[int] = _CURRENT_OWNER_PID,+ runtime_policy_revision: Optional[str] = _MANAGED_RUNTIME_POLICY_REVISION,) -> None:try:self._pid_file.parent.mkdir(parents=True, exist_ok=True)@@ -811,6 +929,8 @@ class OpenCodeServerManager:}if owner_pid is not None:payload["owner_pid"] = owner_pid+ if runtime_policy_revision is not None:+ payload["runtime_policy_revision"] = runtime_policy_revisionif 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:@@ -830,16 +950,47 @@ class OpenCodeServerManager:if callable(apply_to_pid):apply_to_pid(pid, label="opencode serve")- 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)+ def _persist_active_run_session_change(+ self,+ session_id: str,+ *,+ active: bool,+ ) -> set[str]:try:+ raw_info = self._pid_file.read_text()+ except FileNotFoundError:+ info = None+ except Exception as exc:+ raise RuntimeError("Could not read OpenCode active-run metadata") from exc+ else:+ try:+ info = json.loads(raw_info)+ except (TypeError, ValueError) as exc:+ raise RuntimeError("OpenCode active-run metadata is invalid") from exc+ if not isinstance(info, dict):+ raise RuntimeError("OpenCode active-run metadata is invalid")++ updated = set(self._active_run_sessions)+ references_current_server = self._pid_file_references_current_server(info)+ if references_current_server:+ assert isinstance(info, dict)+ persisted = info.get("active_run_sessions")+ if not isinstance(persisted, list) or any(+ not isinstance(item, str) or not item for item in persisted+ ):+ raise RuntimeError("OpenCode active-run metadata is invalid")+ updated.update(persisted)++ if active:+ updated.add(session_id)+ else:+ updated.discard(session_id)++ if references_current_server:+ assert isinstance(info, dict)+ info["active_run_sessions"] = sorted(updated)self._pid_file.write_text(json.dumps(info))- except Exception as e:- logger.debug(f"Failed to update OpenCode pid active sessions: {e}")+ return updateddef _clear_pid_file(self) -> None:try:@@ -869,6 +1020,13 @@ class OpenCodeServerManager:recorded = info.get("caller_context_path") if isinstance(info, dict) else Nonereturn bool(isinstance(recorded, str) and recorded and os.path.isabs(recorded))+ def _pid_file_has_current_runtime_policy(self, info: Optional[Dict[str, Any]]) -> bool:+ return bool(+ self._pid_file_references_current_server(info)+ and isinstance(info, dict)+ and info.get("runtime_policy_revision") == _MANAGED_RUNTIME_POLICY_REVISION+ )+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)@@ -1428,7 +1586,12 @@ 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, caller_context_path=None, owner_pid=None)+ self._write_pid_file(+ actual_pid,+ caller_context_path=None,+ owner_pid=None,+ runtime_policy_revision=None,+ )else:logger.info(f"Adopting healthy OpenCode server pid={pid} from previous run")else:@@ -1469,10 +1632,12 @@ class OpenCodeServerManager:"Stop that server or configure Avibe to use another OPENCODE_PORT so caller context ""environment variables can be injected safely.")+ pid_info = self._reconcile_adopted_active_run_sessions(pid_info)if not self._pid_file_has_caller_context_binding(pid_info):self._caller_context_plugin_refresh_pending = True+ runtime_policy_stale = not self._pid_file_has_current_runtime_policy(pid_info)if (- self._caller_context_plugin_refresh_pending+ (self._caller_context_plugin_refresh_pending or runtime_policy_stale)and self._active_requests == 0and not self._has_active_run_sessions()and (@@ -1480,14 +1645,26 @@ class OpenCodeServerManager:or self._pid_file_has_known_no_active_runs(pid_info))):+ refresh_reasons = []+ if self._caller_context_plugin_refresh_pending:+ refresh_reasons.append("caller-context plugin")+ if runtime_policy_stale:+ refresh_reasons.append("managed runtime policy")logger.info(- "Restarting OpenCode server to load updated Avibe caller-context plugin at %s",+ "Restarting OpenCode server to refresh %s at %s",+ " and ".join(refresh_reasons),plugin_install.path,)await self._restart_for_auth_refresh_locked()await self._start_server()self._caller_context_plugin_refresh_pending = Falsereturn self.base_url+ if runtime_policy_stale:+ raise OpenCodeManagedPolicyRefreshPendingError(+ "OpenCode managed runtime policy refresh is pending for an adopted or active server; "+ "retry after the existing OpenCode turn finishes so Avibe can restart the server "+ "with native Skills disabled."+ )if self._caller_context_plugin_refresh_pending:raise RuntimeError("OpenCode caller-context plugin refresh is pending for an adopted or active server; "@@ -1592,6 +1769,7 @@ class OpenCodeServerManager:env = os.environ.copy()env["OPENCODE_ENABLE_EXA"] = "1"+ env["OPENCODE_DISABLE_EXTERNAL_SKILLS"] = "1"env.update(server_environment())if self._model_hub_overlay_path:env["OPENCODE_CONFIG"] = self._model_hub_overlay_path@@ -1609,6 +1787,13 @@ class OpenCodeServerManager:# checked-in opencode.json from replacing Hub provider transport.env["OPENCODE_CONFIG_CONTENT"] = content+ # Request-level ``tools.skill=false`` prevents native Skill calls. The+ # runtime override adds defense in depth, while the Avibe runtime plugin+ # removes OpenCode's independently assembled native Catalog.+ env["OPENCODE_CONFIG_CONTENT"] = _managed_runtime_config_content(+ env.get("OPENCODE_CONFIG_CONTENT")+ )+try:self._process = await asyncio.create_subprocess_exec(*cmd,diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex 2156ad077..60034c389 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -122,6 +122,46 @@ class SessionsFacade:expected_route=expected_route,)+ def get_agent_session_runtime_marker(+ self,+ agent_session_id: str,+ *,+ backend: str,+ native_session_id: Any,+ key: str,+ ) -> Any:+ getter = getattr(self.sessions_store, "get_agent_session_runtime_marker", None)+ if not callable(getter):+ return None+ return getter(+ agent_session_id,+ backend=backend,+ native_session_id=native_session_id,+ key=key,+ )++ def set_agent_session_runtime_marker(+ self,+ agent_session_id: str,+ *,+ backend: str,+ native_session_id: Any,+ key: str,+ value: Any,+ ) -> bool:+ setter = getattr(self.sessions_store, "set_agent_session_runtime_marker", None)+ if not callable(setter):+ return False+ return bool(+ setter(+ agent_session_id,+ backend=backend,+ native_session_id=native_session_id,+ key=key,+ value=value,+ )+ )+def bind_agent_session(self,user_id: Union[int, str],diff --git a/skills/use-avibe-harness/SKILL.md b/skills/use-avibe-harness/SKILL.mdnew file mode 100644index 000000000..9bfdae5e3--- /dev/null+++ b/skills/use-avibe-harness/SKILL.md@@ -0,0 +1,101 @@+---+name: use-avibe-harness+slug: use-avibe-harness+description: Use Avibe Harness for durable Agent delegation, Sessions, scheduled Tasks, Watches, Runs, queues, and work that must continue beyond the current turn.+version: 0.1.0+---++# Use Avibe Harness++Avibe Harness turns user intent into durable Agent work. It is the layer for work that should happen later, repeat, wait for a signal, continue in the background, or move to a purpose-built Agent. Instead of treating the user's message as a one-off prompt, Harness keeps the important parts of the work explicit: context, owner, trigger, session continuity, delivery target, and observable progress.++Avibe Harness is the first-choice automation layer. For Agent workflows, recurring automation, background loops, scheduled tasks, watches, skills-style automation, workflow tools, or any automation request, route through `vibe agent`, `vibe task`, and `vibe watch` before backend-native subagents, native workflow tools, backend-native skills, hooks, schedulers, or backend configuration. Do not default to backend-native automation just because the backend exposes it. Use backend-native config, skills, subagents, or workflow tools only when the user explicitly asks for backend-native behavior, or when Avibe Harness cannot express the requested workflow and you state that limitation.++The current System Prompt supplies the live backend-native tool policy. Follow that policy exactly; it reflects the active backend, SDK capabilities, and operator settings for this Session.++Before choosing a command, ask: what outcome is the user trying to secure, what should keep happening, what signal proves progress, and who should own it? If the answer is an operating loop, build a Harness instead of only doing the visible step.++### Mental model+| Model | Meaning | Use when |+| --- | --- | --- |+| Agent | Reusable role: backend, model, prompt, description, enabled state | Work needs a stable specialist identity |+| Session | Continuing context for one Agent work lineage | Work should continue or fork context |+| Scope | IM surface and routing context: channel, thread, DM, user scope | Delivery, workdir, user/platform context matter |+| Task | Time trigger: saved Agent message, or a command with no Agent turn | Time is the trigger |+| Watch | Managed waiter triggered by an external signal | Any condition needs monitoring until it becomes true |+| Run | Concrete execution record | You need status, output, result, error, or history |++Relationship: Scope routes work; Agent defines who acts; Session holds continuity; task/watch creates future triggers; each trigger creates a Run. Think in objects before flags.++### Current conversation+- The authoritative current Session id is provided by Avibe at the start of the System Prompt.++### Inspecting Harness state+Use `vibe harness status` first for active Runs, armed Watches, upcoming Tasks, controller ownership, and explicit live anomalies. Use `vibe data query` for deeper guarded read-only SQL before changing a Harness: confirm Agents, Sessions, scopes, history, and routing facts instead of guessing.++Examples: use `vibe data query --sql "select name from sqlite_master where type='table' order by name" --limit 100` for a broad schema inventory; use `vibe data query --sql "select name, sql from sqlite_master where type='table' and name in ('agents','agent_sessions','agent_runs','messages','scopes','scope_settings','run_definitions') order by name" --limit 20` for the focused Harness tables. Follow `pagination.next_command` if either result has more pages.++Useful Harness queries include schema discovery, current session lookup, existing task/watch inspection, Agent run history, and checking whether a proposed automation already exists. Prefer this CLI over direct SQLite access.++### Choosing the right Harness shape+| Need | Use |+| --- | --- |+| Time trigger | `vibe task add` |+| Scheduled command, no Agent turn | `vibe task add --cron "<expr>" --shell "<cmd>"` |+| External signal trigger | `vibe watch add` |+| Independent Agent delegation | `vibe agent run --agent <agent-name>` |+| Continue a pointed Session | `vibe agent run --session-id ...` |+| Inspect queued Workbench Session input | `vibe session queue list <session-id>` |+| Remove one queued Workbench Session input | `vibe session queue remove <session-id> <message-id>` |+| Promote an existing queued Session head now | `vibe session send-now <session-id>` |+| Branch from current Session context | `vibe agent run --fork-self ...` |+| Live/anomaly inspection | `vibe harness status` |+| State/history inspection | `vibe data query`, `vibe runs list --current-session`, `vibe runs show` |+| Recurring specialist workflow | `vibe agent create/update` plus tasks, watches, or runs |++`vibe task add` creates a time-triggered saved Agent message. Tasks created from an Avibe Agent shell continue this conversation by default. Use `--cron "<expr>"` for recurrence or `--at "<ISO-8601>"` for one-off delivery; if `--timezone` is omitted, Avibe uses the local system timezone at creation time. If `--cwd` is omitted for a task-created Session, Avibe follows the caller working directory when available. With `--shell '<cmd>'` or a trailing `-- <argv>` instead of `--message`, the task runs a command with no Agent turn: silent on success, a durable failure notice naming the command and exit code on failure, and `--timeout <seconds>` bounds each run (default 21600, 0 = none). Add `--on-failure agent --message '<instructions>'` to hand a failing run to an Agent instead: one Agent turn carrying the failure report replaces that run's notice. A pure command task takes no session, scope, or agent flags.++`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. Watches created from an Avibe Agent shell follow up in this conversation by default. If `--cwd` is omitted, Avibe runs the waiter from the caller working directory when available.++Watch waiter contract: exit `0` only for one NEW reportable event. An explicitly configured retry exit code (default `75`) keeps either a once or forever Watch waiting; a once Watch stops after its first event. Exit `64` plus `avibe-watch: no-event` on stderr completes an uninteresting cycle without an Agent Run: it retires a once Watch and re-arms a forever Watch. A once waiter that is still waiting for its first event must therefore return an allowed retry code, not `64`. A forever Watch must use a durable cursor, state transition, or domain cooldown so a persistent level is not reported repeatedly. Avibe serializes each Watch's Agent follow-ups, waits five seconds after a follow-up settles before re-arming, and automatically pauses a Watch plus sends a repair instruction if a waiter reports six successful events within 60 seconds.++Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work to another Agent. By default this creates a background Session in the caller's scope and returns immediately; when the run completes, the final result is sent back to this conversation. Background Sessions stay out of the session list and never deliver outward, but remain visible in the Agents run graph, where the user can open their full chat history or promote them at any time. Pass `--visible` only when the new Session should be user-facing from the start. Pass `--sync` only when the current process must wait for the result. Pass `--no-callback` only when you intentionally want no automatic follow-up and will inspect the run later; pass `--callback-session-id <id>` only to route the final result elsewhere. Add `--scope-id <scopes.id>` only when placing the new Session in a specific existing scope.++Use `vibe agent run --fork-self --message ...` when work should branch from this current Session's native backend context without mutating it. Use `--fork-session <source-session-id>` only when branching from a different explicit Session. Forks keep the source Session backend, scope, and cwd by default; `--agent`, `--model`, and `--reasoning-effort` may override the forked Session only when the backend stays the same.++When `vibe agent run --session-id <id>` targets an existing Session, it sends a new message into that Session. It does not change that Session's cwd, scope, Agent, model, or reasoning settings; those properties belong to the Session itself. Use a new Session or a fork when those properties need to differ.++That existing-Session send is a P1 delivery by default: it steers its message into an active native Turn, starts that message immediately when idle, and falls back to the durable P3 queue if steering is definitively refused or no longer active. Use `--queue` when the new Run should enter that P3 queue without steering. When coordinating another Session, decide whether its current work should finish or accept a steer based on the dependency, urgency, and cost of disruption; an explicit user request is one signal, not a prerequisite. `vibe agent run --session-id <id> --send-now --message ...` explicitly selects that same content-bearing P1 behavior; it does not promote an older queued message. Use `vibe session send-now <id>` only when no new Message should be added: this content-free P1 promotes the exact existing FIFO head. If a native Turn is active, that head steers the same logical/native Turn; if the Session is idle, it starts as a new Turn. Both commands work for Workbench and IM Sessions. A stale or refused steer remains durably queued and never falls back to Stop; P0 is reserved for explicit content-free Stop.++Coordinating Agents can inspect the same durable Workbench queue the user sees with `vibe session queue list <id>`. If one queued instruction has become obsolete, contradictory, or duplicated, remove that exact row with `vibe session queue remove <id> <message-id>`. Always list first and use the returned stable message id; never guess an id or delete a different row to simulate reordering.++Use `vibe session update --visible|--hidden` (`--visibility foreground|background`) to promote or hide a persisted Session independently of its scope. Use `--scope-id <scopes.id>` to move it to another scope or `--scope-id none` to make it standalone; moving scope never changes its stored workdir.++For tasks, use `--message "..."` or `--message-file <path>` as the stored message. For watches, use `--message "..."` or `--message-file <path>` as the follow-up instruction template sent with waiter output. Prefer `--same-scope` or `--scope-id <scopes.id>` for new Session placement.++Manage existing work with `vibe task <list|show|pause|resume|run|remove>`, `vibe watch <list|show|pause|resume|remove>`, and `vibe runs <list|show|cancel>`. Use `vibe harness status` for one unified live/anomaly snapshot. For current-session run history, use `vibe runs list --current-session`. `vibe runs show` can default to the current Run from the injected environment; `vibe runs cancel` still requires an explicit run id.++The CLI exposes more options than this prompt lists. Before creating or changing Harness state, or whenever syntax/runtime effects are uncertain, read the relevant help: `vibe <command> --help` or `vibe <command> <subcommand> --help`.++### Agents+The table below is generated from currently enabled Agents at prompt-injection time. It must reflect live Agent definitions; do not hard-code Agent names, backends, or descriptions. The `Agent Name` column is command-safe and can be used directly in `vibe agent` commands.++Use the enabled Agent table in the current System Prompt.++Rules:+- All Agents listed in the generated table are enabled. Use the `Agent Name` value exactly as listed in shell commands such as `vibe agent show <agent-name>` and `vibe agent run --agent <agent-name> ...`.+- `--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing. Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate background Session for the target Agent.+- `--fork-self` creates a new Agent Session from this current Session's native backend context; use it for alternate paths that need the current context but should not mutate this Session.+- `--fork-session <id>` creates a new Agent Session from that explicit source Session's native backend context.+- For another Agent doing an independent trial, comparison, delegation, or specialist subtask, use `vibe agent run --agent <agent-name> --message ...`.+- Use `vibe agent run --agent <agent-name> --session-id ... --message ...` only when the work should continue that same existing Session. Async callbacks return to this conversation by default.+- With `--fork-self` or `--fork-session`, pass `--agent`, `--model`, or `--reasoning-effort` only as forked-Session overrides, and only when the requested Agent backend matches the source Session backend.+- `--sync` changes waiting behavior, not session identity: default async runs in the background and return through callbacks; synchronous runs wait for the result and are still recorded in `vibe runs`.+- Create or update Agents only when it captures a reusable role, reduces repeated prompting, or makes a long-running Harness more reliable.++### Mentions in user messages+On the Web chat the user composes with `@` / `#` autocomplete, which inserts stable references into their message text:+- `@<agent-name>` points at that enabled Agent (see the table above). Act on it with `vibe agent run --agent <agent-name> ...`.+- `#<session-id>` points at that Session. Resume it with `vibe agent run --session-id <session-id> ...`, or read its history with `vibe data query`.++Treat these as the user pointing at that Agent or Session, and decide the action from context. Only the bracketed `@<...>` / `#<...>` forms are references; a bare `@` or `#` in prose is ordinary text.diff --git a/skills/use-avibe-vault/SKILL.md b/skills/use-avibe-vault/SKILL.mdnew file mode 100644index 000000000..7e0b07b24--- /dev/null+++ b/skills/use-avibe-vault/SKILL.md@@ -0,0 +1,58 @@+---+name: use-avibe-vault+slug: use-avibe-vault+description: Use Avibe Vault for API keys, tokens, passwords, protected credentials, authenticated HTTP requests, or digest signing without exposing secret values to the agent.+version: 0.2.0+---++# Use Avibe Vault++When a task needs API keys, access tokens, passwords, wallet private keys, or other sensitive credentials, prefer Avibe Vault: agents reference secrets by name, tag, or skill tag, and users do not need to paste plaintext into chat.++Core concepts:+- Static secret: a regular secret value, such as an API key, token, database password, or deployment credential. Use it with `vibe vault run` for environment injection or `vibe vault fetch` for authenticated HTTP egress.+- Keypair secret: a signing key for digests or transactions, such as a wallet key or deployment signer. It cannot be exported as an environment variable and cannot be used with `run` / `fetch`; use `vibe vault sign`.+- Standard: for lower-risk routine automation. Agents can usually use it without interrupting the user unless it is configured to ask first.+- Protected: for high-risk secrets, such as production databases or wallet/funds keys. Because protected secrets are end-to-end encrypted, use requires browser approval and passkey unlock.++Rules:+- Refer to secrets only by secret name, tag, or skill tag.+- Static secrets can be used with `run` / `fetch`; keypair secrets can only be used with `vibe vault sign`.+- With `vibe vault run`, the child process receives static secrets as environment variables, so never run commands that may print env vars, debug config, or secret-bearing errors.+- When protected `run` / `fetch` needs approval, Avibe automatically asks the user to decrypt and authorize access. After the user approves, Avibe resumes this session; it does not replay the command for you, so run the same `run` / `fetch` command again.+- When protected `sign` needs approval, Avibe creates a browser signing request and returns immediately. Do not rerun `sign`; when Avibe resumes this session, follow the callback instruction to read the completed request result and continue with the returned signature.++Common commands:++Request that the user add a missing static secret. `spec-json` may contain only non-secret prefill metadata; the actual secret value is entered by the user in the browser:+`vibe vault request OPENAI_API_KEY --reason "Need OpenAI API access" --spec-json '{"kind":"static","protection":"protected","description":"OpenAI API key","tags":["openai","prod","skill:model-work"],"policy":{"allowed_hosts":["api.openai.com"],"auth":{"type":"bearer"}}}'`++For a missing keypair/signing key, ask the user to create a keypair secret in the Vault UI; do not request or store private-key material as a static secret.++On Avibe Web chat, a lighter manual prompt can mention the missing secret as a clickable placeholder in your reply, for example `$<OPENAI_API_KEY>`. The user can click it and fill the secret from Web chat. This has no reason or structured prefill metadata; use `vibe vault request` when those are needed.++List or find existing Vault entries:+`vibe vault list`+`vibe vault list --tag prod`+`vibe vault find --kind static --protection protected`+`vibe vault find openai --tag prod`+`vibe vault tags`++Run a command with selected static secrets injected as environment variables:+`vibe vault run --env OPENAI_API_KEY,GITHUB_TOKEN -- python script.py`+`vibe vault run --env GITHUB_TOKEN=GH_PAT --env OPENAI_API_KEY -- python script.py`+`vibe vault run --tag deploy -- ./deploy.sh`+`vibe vault run --skill github-release -- ./release.sh`++Make an authenticated HTTP request. The credential is attached only at egress, and the agent never sees the secret:+`vibe vault fetch --auth GITHUB_PAT --url https://api.github.com/user`++Request approval before a protected `run` with an existing static secret:+`vibe vault access PROD_DB_URL --skill deploy --command "run database migration" --egress "connect to production database"`++For protected `fetch`, run `vibe vault fetch`; it creates the correct fetch approval request when needed.++Sign a 32-byte digest with a keypair secret. Standard keys may return the signature directly; protected keys create a browser approval request:+`vibe vault sign WALLET_KEY --digest <64-hex-digest> --scheme ecdsa-secp256k1-recoverable --command "sign deployment transaction"`++For more details, run `vibe vault --help`.diff --git a/skills/use-show-pages/SKILL.md b/skills/use-show-pages/SKILL.mdnew file mode 100644index 000000000..9953cdb5b--- /dev/null+++ b/skills/use-show-pages/SKILL.md@@ -0,0 +1,61 @@+---+name: use-show-pages+slug: use-show-pages+description: Build, inspect, update, or share an Avibe Show Page when a visual explanation, diagram, dashboard, report, or interactive prototype would materially help.+version: 0.2.1+---++# Use Show Pages++When a visual page would help the user understand a problem, plan, process, result, or complex information more clearly, use Show Pages. They are useful for diagrams, flowcharts, mind maps, timelines, architecture maps, comparison views, dashboards, visual reports, interactive explanations, and small prototypes.++Each Agent Session has one Show Page. Get this session's page directory:++`vibe show path`++Check status:++`vibe show status`++Change visibility:++`vibe show update --visibility public`+`vibe show update --visibility private`+`vibe show update --visibility offline`++For more usage details, run `vibe show --help` or a subcommand help such as `vibe show update --help`.++### Agent-readable representation+- Every Show Page URL is agent-readable without page-specific code: request the same private or public URL with `Accept: text/markdown` to receive its rendered Markdown representation.+- Author semantic HTML so that representation stays dense and useful: use headings for sections, lists for sequences or groups, and `<table>` for genuinely tabular data.+- Add `data-agent-hidden` to visual-only or sensitive-to-representation elements that should be omitted from Markdown. Add `agent-note="..."` when an element needs short agent-only context; the note text is preserved in the representation.++### Show Page annotations & reverse marks+- Users can annotate your Show Page; each annotation arrives as a chat message tagged [show-annotation] with its event id. Some messages end with a ready-to-run reply command — whether to reply on the page or respond by editing the page content is your call, per scenario.+- After reworking a page area you may leave a short callout: `vibe show mark <selector-or-anchor> --message '...'` (same target replaces), or an `agent-note="..."` attribute on elements you author. Marks retire once read — leave at most 1-2 per turn.+- Inspect/withdraw: `vibe show marks` / `vibe show unmark <id|target> ...`; toggle the user's annotation mode: `vibe show annotate --on|--off [--mode smart|screenshot]`.++Avibe injects the current Cloud-availability guidance and the one active history+contract separately because both depend on live runtime state. Follow that+contract for the current Session; do not infer another history mode from this+Skill.++Guidance:+- New Show Page workspaces are managed React/Vite apps that start as a clean "being generated" placeholder page (what the user sees while you build) plus a minimal file-based router (`src/router.tsx`) and one example page. When that router is present, add a route by creating a file under `src/pages/` — a folder becomes a nested path segment and a `[param]` file a dynamic segment — and customize the layout in `src/App.tsx`, styles in `src/styles.css`, and optional `api/*.ts` handlers. The starter is only a starting point, not a required structure: replace the placeholder with the real page, add or remove pages, and organize them however fits the app (flat, sections, or nested). Built-in UI is available to import, e.g. `@/components/ui/card`, `@/components/ui/button`, `@/components/ui/badge`.+- An older Show Page with no `src/router.tsx` is a single-page app that renders `src/App.tsx` directly. There, edit `src/App.tsx` (or adopt the router scaffold: add `src/router.tsx` + `src/pages/` and render it from `App.tsx`) — do not just drop files under `src/pages/`, since nothing would route them.+- Treat `index.html` and `src/main.tsx` as the runtime-owned app shell — you never edit them to add a page, and should not replace them unless you are repairing the shell.+- Hot reload is available while `/show/<session-id>/` is open. Users will see page changes live. Prefer component-level changes that preserve React state.+- Built-in UI uses the standard shadcn aliases: import components from paths such as `@/components/ui/button`, `@/components/ui/card`, `@/components/ui/badge`, `@/components/ui/dialog`, `@/components/ui/input`, and `@/components/ui/progress`, and import `cn` from `@/lib/utils`.+- Tailwind CSS v4 utility classes are built in and work in any `className`, including to restyle the built-in `@/components/ui/*` components (a utility overrides the component default). `src/styles.css` is the CSS entry and must keep `@import "tailwindcss";` and `@import "@avibe/show-ui/theme.css";` at the top. Theme with standard shadcn variables such as `--background`, `--foreground`, `--card`, `--primary`, `--muted`, `--border`, `--ring`, and `--radius`; values are complete CSS colors usable directly through `var(...)`. Override the same variables under `.dark` or `[data-theme="dark"]` for dark mode. Do not use runtime-prefixed private variables.+- Prefer the built-in UI primitives over hand-rolled controls. They include Show Page motion for changed text, numbers, badges, cards, and progress without extra animation calls.+- Optional server handlers live under `api/` and run only when requested. Export functions named like HTTP methods, for example `export async function GET(request) { return Response.json({ ok: true }) }`.+- Design for user understanding, not just for moving text onto a webpage. Choose the visual form that best helps the user inspect, compare, confirm, and continue the discussion.+- Use diagrams or mind maps for relationships, flowcharts or state machines for processes, timelines for sequences, charts or dashboards for metrics, and side-by-side views for tradeoffs.+- Make the page visually polished: use clear hierarchy, spacing, typography, contrast, and consistent components. Avoid rough default-looking pages.+- Give the app a recognizable icon so it stands out in the Dock and App Library: drop a `public/favicon.svg` (or `favicon.svg` at the workspace root) and it is picked up automatically, or add `<link rel="icon" href="./favicon.svg">` to `index.html` (an icon edit to the shell is fine).+- Make the page work reasonably on mobile because users may open links from an IM app on their phone.+- Prefer React component implementations. Useful visualization libraries include React Flow, Mermaid, Markmap, Chart.js, and Cytoscape.js.+- Keep pages private by default. Publish publicly only when the user asks for a shareable or public link.+- Do not publish secrets, credentials, private logs, or sensitive user data publicly.+- If a Show Page would clearly help but the user's preference is unclear, briefly ask whether they want one.+- After creating or updating a page, send the active URL and a short summary of what the page shows.diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 2b756a7af..41d78dbc5 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -306,6 +306,91 @@ class SQLiteSessionsService:).mappings().first()return dict(row) if row else None+ def get_agent_session_runtime_marker(+ self,+ session_id: str,+ *,+ backend: str,+ native_session_id: Any,+ key: str,+ ) -> Any:+ """Read one backend marker only from the exact active native binding."""++ marker_key = str(key or "").strip()+ if not marker_key:+ raise ValueError("runtime marker key is required")+ expected_native = encode_session_value(native_session_id)+ with self.engine.connect() as conn:+ raw_metadata = conn.execute(+ select(agent_sessions.c.metadata_json)+ .where(agent_sessions.c.id == str(session_id))+ .where(agent_sessions.c.status != "archived")+ .where(agent_sessions.c.agent_backend == str(backend))+ .where(agent_sessions.c.native_session_id == expected_native)+ .limit(1)+ ).scalar_one_or_none()+ metadata_value = _json_loads(raw_metadata, {})+ if not isinstance(metadata_value, dict):+ return None+ return metadata_value.get(marker_key)++ def set_agent_session_runtime_marker(+ self,+ session_id: str,+ *,+ backend: str,+ native_session_id: Any,+ key: str,+ value: Any,+ ) -> bool:+ """Merge one backend marker into the exact active native binding.++ The writer reservation makes the read/merge/write atomic, so unrelated+ Session metadata cannot be lost and a replaced native binding cannot+ inherit state that belonged to its predecessor.+ """++ marker_key = str(key or "").strip()+ if not marker_key:+ raise ValueError("runtime marker key is required")+ expected_native = encode_session_value(native_session_id)+ with self.engine.begin() as conn:+ reserve_write_lock(conn)+ row = conn.execute(+ select(+ agent_sessions.c.metadata_json,+ agent_sessions.c.status,+ agent_sessions.c.agent_backend,+ agent_sessions.c.native_session_id,+ )+ .where(agent_sessions.c.id == str(session_id))+ .limit(1)+ ).mappings().first()+ if (+ row is None+ or str(row["status"] or "") == "archived"+ or str(row["agent_backend"] or "") != str(backend)+ or str(row["native_session_id"] or "") != expected_native+ ):+ return False+ metadata_value = _json_loads(row["metadata_json"], {})+ metadata_object = dict(metadata_value) if isinstance(metadata_value, dict) else {}+ if metadata_object.get(marker_key) == value:+ return True+ metadata_object[marker_key] = value+ result = conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == str(session_id))+ .where(agent_sessions.c.status != "archived")+ .where(agent_sessions.c.agent_backend == str(backend))+ .where(agent_sessions.c.native_session_id == expected_native)+ .values(+ metadata_json=_json_dumps(metadata_object),+ updated_at=_utc_now_iso(),+ )+ )+ return bool(result.rowcount)+def reserve_agent_session(self,*,diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex 42382d918..ce9c0d951 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -145,6 +145,7 @@ class _OpenCodeServer:self.list_calls = 0self.prompt_calls: list[dict] = []self.abort_calls: list[tuple] = []+ self.inactive_runs: list[str] = []async def prompt_async(self, **kwargs) -> None:self.prompt_calls.append(kwargs)@@ -192,6 +193,9 @@ class _OpenCodeServer:self.abort_calls.append(args)return True+ async def mark_run_inactive(self, session_id: str) -> None:+ self.inactive_runs.append(session_id)+def _primary_request(*, session_id: str = "avibe-session", backend: str) -> AgentRequest:context = MessageContext(@@ -798,7 +802,10 @@ async def test_opencode_stop_waits_for_in_flight_steering_write() -> None:controller.emit_agent_message = AsyncMock()agent._get_server = AsyncMock(return_value=server)removed_polls: list[str] = []- agent.sessions = SimpleNamespace(remove_active_poll=removed_polls.append)+ agent.sessions = SimpleNamespace(+ get_all_active_polls=lambda: {"opencode-session": object()},+ remove_active_poll=removed_polls.append,+ )state = agent._steering_states[primary.base_session_id]try:identity = active_steer_identity(controller, "opencode", "avibe-session")@@ -822,6 +829,7 @@ async def test_opencode_stop_waits_for_in_flight_steering_write() -> None:assert state.closing is Trueassert server.abort_calls == [("opencode-session", primary.working_path)]assert gate_task.cancelled()+ assert server.inactive_runs == ["opencode-session"]assert removed_polls == ["opencode-session"]finally:await _cancel_tasks(gate_task)diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex a5a3f4f65..4dfbc0440 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -547,7 +547,9 @@ def test_session_handler_ensures_agent_session_id_before_prompt(prompt = prompt_value["append"] if isinstance(prompt_value, dict) else prompt_valueassert captured["connected"] is Trueassert "Current session id: `sesk8m4q2p7x`" in prompt- assert "`vibe show path`" in prompt+ assert "load the `use-show-pages` Skill" in prompt+ assert "- use-show-pages:" in prompt+ assert "`vibe show path`" not in promptassert "--session-id sesk8m4q2p7x" not in promptassert "--session-key" not in promptdiff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.pyindex e9f834647..da8850d31 100644--- a/tests/test_cli_pagination.py+++ b/tests/test_cli_pagination.py@@ -4,6 +4,9 @@ import argparseimport jsonimport reimport shlex+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patchfrom config import pathsfrom core.system_prompt_injection import build_system_prompt_injection@@ -12,6 +15,9 @@ from storage.background import SQLiteBackgroundTaskStorefrom vibe import cli+ROOT = Path(__file__).resolve().parents[1]++def _command_parser(path: tuple[str, ...]):parser = cli.build_parser()for segment in path:@@ -95,7 +101,7 @@ def test_all_collection_commands_share_bounded_pagination_contract() -> None:assert "--all" not in flags, path-def test_injected_vibe_commands_only_use_parser_supported_flags() -> None:+def test_injected_and_builtin_skill_commands_only_use_parser_supported_flags() -> None:context = MessageContext(user_id="user",channel_id="channel",@@ -103,7 +109,11 @@ def test_injected_vibe_commands_only_use_parser_supported_flags() -> None:platform_specific={"agent_session_id": "ses-test"},)prompt = build_system_prompt_injection(context=context)- commands = re.findall(r"`(vibe [^`\n]+)`", prompt)+ guidance = [prompt] + [+ (ROOT / "skills" / name / "SKILL.md").read_text()+ for name in ("use-avibe", "use-avibe-harness", "use-avibe-vault", "use-show-pages")+ ]+ commands = re.findall(r"`(vibe [^`\n]+)`", "\n".join(guidance))checked_commands = 0for command in commands:@@ -121,14 +131,28 @@ def test_injected_vibe_commands_only_use_parser_supported_flags() -> None:assert checked_commands >= 20-def test_injected_session_queue_commands_name_real_subcommands() -> None:+def test_managed_harness_session_queue_commands_name_real_subcommands() -> None:context = MessageContext(user_id="user",channel_id="channel",platform="avibe",platform_specific={"agent_session_id": "ses-test"},)- prompt = build_system_prompt_injection(context=context)+ with patch(+ "core.managed_skills.resolve_skills",+ return_value=[+ SimpleNamespace(+ name="use-avibe-harness",+ description="Harness workflow",+ directory=ROOT / "skills" / "use-avibe-harness",+ disable_model_invocation=False,+ )+ ],+ ):+ prompt = build_system_prompt_injection(context=context, skills_cwd=ROOT)+ harness_skill = (ROOT / "skills" / "use-avibe-harness" / "SKILL.md").read_text()++ assert "load the `use-avibe-harness` Skill" in promptfor command, expected_path in ((@@ -140,7 +164,7 @@ def test_injected_session_queue_commands_name_real_subcommands() -> None:("session", "queue", "remove"),),):- assert f"`{command}`" in prompt+ assert f"`{command}`" in harness_skill_, path = _prompt_command_parser(command)assert path == expected_pathdiff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex e143e8c11..3cd04db92 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -54,6 +54,11 @@ class _BaseAgent:session_id = Nonereturn session_id or self.ensure_agent_session_id(request, session_anchor=anchor)+ @staticmethod+ def _uses_namespaced_backend_session(context, *, subagent_name=None):+ payload = getattr(context, "platform_specific", None) or {}+ return bool(subagent_name or payload.get("routing_subagent"))+@staticmethoddef _reserved_native_session_id(context, backend=None):# Mirrors the real BaseAgent helper: native session bound to the reserved@@ -143,9 +148,11 @@ assert _SPEC is not None and _SPEC.loader is not None_MODULE = importlib.util.module_from_spec(_SPEC)_SPEC.loader.exec_module(_MODULE)CodexAgent = _MODULE.CodexAgent+CODEX_PROMPT_STRATEGY_METADATA_KEY = _MODULE.CODEX_PROMPT_STRATEGY_METADATA_KEYCodexConnectionProbeRuntimeMismatchError = (_MODULE.CodexConnectionProbeRuntimeMismatchError)+CodexPromptRefreshUnavailableError = _MODULE.CodexPromptRefreshUnavailableErrorCodexResumeUnavailableError = _MODULE.CodexResumeUnavailableErrorfor name, module in _saved_modules.items():@@ -1422,6 +1429,13 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):)agent._get_or_create_transport = AsyncMock(return_value=transport)agent._touch_transport_activity = Mock()+ agent.ensure_agent_session_id = Mock(+ side_effect=lambda existing_request: events.append(+ ("ensure", existing_request)+ )+ or "ses-visible"+ )+ agent._build_thread_developer_instructions = AsyncMock(return_value="stable prompt")agent._session_mgr = SimpleNamespace(set_session_key=Mock(),set_cwd=Mock(),@@ -1431,7 +1445,8 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):async def refresh(existing_transport, existing_request, thread_id):events.append(("refresh", existing_transport, existing_request, thread_id))- async def start_turn(existing_transport, existing_request, thread_id):+ async def start_turn(existing_transport, existing_request, thread_id, *, developer_instructions=None):+ self.assertEqual(developer_instructions, "stable prompt")events.append(("turn", existing_transport, existing_request, thread_id))return thread_id@@ -1444,12 +1459,26 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(events,[+ ("ensure", request),("refresh", transport, request, "thread-cached"),("turn", transport, request, "thread-cached"),],)agent._start_or_resume_thread.assert_not_awaited()+ async def test_prompt_refresh_failure_display_is_localized(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(config=SimpleNamespace(language="zh"))++ display = agent._error_display_text(+ CodexPromptRefreshUnavailableError("internal diagnostic")+ )++ self.assertEqual(+ display,+ "❌ Codex 无法确认能否安全刷新此现有会话的 Avibe 指令。请检查或升级 Codex 后重试本回合。",+ )+async def test_handle_message_does_not_hide_turn_before_interrupt_succeeds(self):agent = object.__new__(CodexAgent)request = SimpleNamespace(@@ -1535,6 +1564,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent.sessions = sessionsagent._get_or_create_transport = AsyncMock(side_effect=[bad_transport, fresh_transport])agent._touch_transport_activity = Mock()+ agent._build_thread_developer_instructions = AsyncMock(return_value="stable prompt")agent._start_or_resume_thread = AsyncMock(side_effect=[ConnectionError("Codex app-server stdout closed"),@@ -1555,7 +1585,12 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent._get_or_create_transport.assert_any_await("/tmp/work")self.assertEqual(agent._start_or_resume_thread.await_args_list[-1].args, (fresh_transport, request))agent._start_thread.assert_not_awaited()- agent._start_turn.assert_awaited_once_with(fresh_transport, request, "thread-new")+ agent._start_turn.assert_awaited_once_with(+ fresh_transport,+ request,+ "thread-new",+ developer_instructions="stable prompt",+ )agent.controller.emit_agent_message.assert_not_awaited()agent._remove_ack_reaction.assert_not_awaited()@@ -1596,6 +1631,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())agent._get_or_create_transport = AsyncMock(side_effect=[bad_transport, fresh_transport])agent._touch_transport_activity = Mock()+ agent._build_thread_developer_instructions = AsyncMock(return_value="stable prompt")agent._start_or_resume_thread = AsyncMock(return_value="thread-new")agent._start_thread = AsyncMock(return_value="thread-new")agent._start_turn = AsyncMock(return_value="thread-new")@@ -1806,7 +1842,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):working_path="/tmp/work",context=SimpleNamespace(platform="slack",- platform_specific={},+ platform_specific={"agent_session_id": "sesk8m4q2p7x"},user_id="U1",channel_id="C1",thread_id=None,@@ -1818,7 +1854,15 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):subagent_reasoning_effort=None,)- transport = SimpleNamespace(send_request=AsyncMock(return_value={"thread": {"id": "thread-1"}}))+ transport = SimpleNamespace(+ send_request=AsyncMock(+ return_value={+ "thread": {"id": "thread-1"},+ "model": "gpt-5.4",+ "reasoningEffort": "high",+ }+ )+ )thread_id = await agent._start_thread(transport, request)@@ -1828,9 +1872,11 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(params["cwd"], "/tmp/work")self.assertEqual(params["approvalPolicy"], "never")self.assertEqual(params["sandbox"], "danger-full-access")- self.assertIn("# Avibe", params["developerInstructions"])- self.assertNotIn("## Quick-reply buttons", params["developerInstructions"])- self.assertIn("Current session id: `sesk8m4q2p7x`", params["developerInstructions"])+ self.assertNotIn("developerInstructions", params)+ self.assertEqual(+ agent._thread_model_settings["session-1"],+ ("thread-1", "gpt-5.4", "high"),+ )agent.sessions.ensure_agent_session_id.assert_called_once_with("channel-1", "codex", "session-1")agent.sessions.bind_agent_session.assert_called_once_with("channel-1", "codex", "session-1", "thread-1")@@ -1847,7 +1893,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):working_path="/tmp/work",context=SimpleNamespace(platform="slack",- platform_specific={},+ platform_specific={"agent_session_id": "sesk8m4q2p7x"},user_id="U1",channel_id="C1",thread_id=None,@@ -1869,18 +1915,14 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):reasoning_effort="high",),) as load_subagent:- await agent._start_thread(transport, request)+ developer_instructions = await agent._build_thread_developer_instructions(request)load_subagent.assert_called_once_with("reviewer", project_root=Path("/tmp/work"))- method, params = transport.send_request.await_args.args- self.assertEqual(method, "thread/start")- self.assertEqual(params["cwd"], "/tmp/work")- self.assertEqual(params["approvalPolicy"], "never")- self.assertEqual(params["sandbox"], "danger-full-access")- self.assertIn("Focus on regressions.", params["developerInstructions"])- self.assertIn("# Avibe", params["developerInstructions"])- self.assertIn("Current session id: `sesk8m4q2p7x`", params["developerInstructions"])- self.assertNotIn("## Quick-reply buttons", params["developerInstructions"])+ transport.send_request.assert_not_awaited()+ self.assertIn("Focus on regressions.", developer_instructions)+ self.assertIn("# Avibe", developer_instructions)+ self.assertIn("Current session id: `sesk8m4q2p7x`", developer_instructions)+ self.assertNotIn("## Quick-reply buttons", developer_instructions)async def test_start_thread_adds_codex_generated_image_prompt_to_thread_instructions(self):agent = object.__new__(CodexAgent)@@ -1895,7 +1937,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):working_path="/tmp/work",context=SimpleNamespace(platform="slack",- platform_specific={},+ platform_specific={"agent_session_id": "sesk8m4q2p7x"},user_id="U1",channel_id="C1",thread_id=None,@@ -1909,16 +1951,16 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):transport = SimpleNamespace(send_request=AsyncMock(return_value={"thread": {"id": "thread-1"}}))with patch.dict(os.environ, {"CODEX_HOME": "/Users/test/.codex"}):- await agent._start_thread(transport, request)+ developer_instructions = await agent._build_thread_developer_instructions(request)- params = transport.send_request.await_args.args[1]- self.assertIn("## Send files", params["developerInstructions"])- self.assertIn("### Codex-generated images", params["developerInstructions"])- self.assertIn("If you generate an image with Codex", params["developerInstructions"])- self.assertIn("Current session id: `sesk8m4q2p7x`", params["developerInstructions"])+ transport.send_request.assert_not_awaited()+ self.assertIn("## Send files", developer_instructions)+ self.assertIn("### Codex-generated images", developer_instructions)+ self.assertIn("If you generate an image with Codex", developer_instructions)+ self.assertIn("Current session id: `sesk8m4q2p7x`", developer_instructions)self.assertIn("file:///Users/test/.codex/generated_images/thread-id/image-file.png",- params["developerInstructions"],+ developer_instructions,)async def test_start_thread_omits_show_pages_prompt_when_disabled(self):@@ -1936,7 +1978,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):working_path="/tmp/work",context=SimpleNamespace(platform="slack",- platform_specific={},+ platform_specific={"agent_session_id": "sesk8m4q2p7x"},user_id="U1",channel_id="C1",thread_id=None,@@ -1949,14 +1991,14 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):)transport = SimpleNamespace(send_request=AsyncMock(return_value={"thread": {"id": "thread-1"}}))- await agent._start_thread(transport, request)+ developer_instructions = await agent._build_thread_developer_instructions(request)- params = transport.send_request.await_args.args[1]- self.assertIn("# Avibe", params["developerInstructions"])- self.assertIn("## Quick-reply buttons", params["developerInstructions"])- self.assertIn("Current session id: `sesk8m4q2p7x`", params["developerInstructions"])- self.assertNotIn("## Show Pages", params["developerInstructions"])- self.assertNotIn("vibe show path", params["developerInstructions"])+ transport.send_request.assert_not_awaited()+ self.assertIn("# Avibe", developer_instructions)+ self.assertIn("## Quick-reply buttons", developer_instructions)+ self.assertIn("Current session id: `sesk8m4q2p7x`", developer_instructions)+ self.assertNotIn("## Show Pages", developer_instructions)+ self.assertNotIn("vibe show path", developer_instructions)async def test_resume_thread_refreshes_developer_instructions_without_appending(self):agent = object.__new__(CodexAgent)@@ -2008,14 +2050,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):method, params = transport.send_request.await_args_list[2].argsself.assertEqual(method, "thread/resume")self.assertEqual(params["threadId"], "thread-existing")- developer_instructions = params["developerInstructions"]- self.assertEqual(developer_instructions.count("Focus on regressions."), 1)- self.assertEqual(developer_instructions.count("Current session id:"), 2)- self.assertNotIn("Legacy session key:", developer_instructions)- self.assertNotIn("--session-key", developer_instructions)- self.assertEqual(developer_instructions.count("If you generate an image with Codex"), 1)- self.assertIn("Current session id: `sesk8m4q2p7x`", developer_instructions)- self.assertNotIn("Channel-level session key:", developer_instructions)+ self.assertNotIn("developerInstructions", params)async def test_resume_thread_rebinds_managed_provider_when_thread_id_matches_config(self):agent = object.__new__(CodexAgent)@@ -2195,15 +2230,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(params["sandbox"], "danger-full-access")self.assertEqual(params["model"], "gpt-5.2")self.assertNotIn("effort", params)- developer_instructions = params["developerInstructions"]- self.assertIn("Current session id: `ses-target`", developer_instructions)- self.assertIn("This Agent Session was forked from `ses-source`.", developer_instructions)- self.assertIn(- "The authoritative Avibe session id for this fork is `ses-target`.",- developer_instructions,- )- self.assertIn("treat it as historical source-context only", developer_instructions)- self.assertNotIn("use `ses-target` for Show Pages", developer_instructions)+ self.assertNotIn("developerInstructions", params)inject_method, inject_params = transport.send_request.await_args_list[1].argsself.assertEqual(inject_method, "thread/inject_items")self.assertEqual(inject_params["threadId"], "thread-fork")@@ -2222,6 +2249,222 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):"thread-fork",)+ async def test_fork_carries_persisted_fallback_prompt_strategy(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ config=SimpleNamespace(platform="avibe", reply_enhancements=False)+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ marker_getter = Mock(+ return_value={+ "thread_id": "thread-source",+ "strategy": "fallback",+ "sha256": "a" * 64,+ }+ )+ agent.sessions = SimpleNamespace(+ get_agent_session_id=Mock(return_value=None),+ ensure_agent_session_id=Mock(return_value="ses-target"),+ bind_agent_session=Mock(return_value="ses-target"),+ get_agent_session_runtime_marker=marker_getter,+ set_agent_session_runtime_marker=Mock(return_value=True),+ )+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent._fork_correction_pending_base_sessions = set()+ request = SimpleNamespace(+ working_path="/tmp/work",+ context=SimpleNamespace(+ platform="avibe",+ platform_specific={+ "agent_session_target": {+ "id": "ses-target",+ "agent_backend": "codex",+ "native_session_id": "",+ "native_session_fork": {+ "source_session_id": "ses-source",+ "source_native_session_id": "thread-source",+ "source_backend": "codex",+ },+ }+ },+ user_id="scheduled",+ channel_id="ses-target",+ thread_id=None,+ ),+ base_session_id="ses-target",+ session_key="avibe::project::proj_1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ vibe_agent_model="gpt-5.2",+ vibe_agent_reasoning_effort="high",+ )+ transport = SimpleNamespace(+ send_request=AsyncMock(return_value={"thread": {"id": "thread-fork"}})+ )++ thread_id = await agent._start_or_resume_thread(transport, request)++ self.assertEqual(thread_id, "thread-fork")+ self.assertNotIn(+ "ses-target",+ getattr(agent, "_thread_prompt_strategies", {}),+ )+ agent.sessions.set_agent_session_runtime_marker.assert_called_once_with(+ "ses-target",+ backend="codex",+ native_session_id="thread-fork",+ key=CODEX_PROMPT_STRATEGY_METADATA_KEY,+ value={+ "thread_id": "thread-fork",+ "strategy": "fallback",+ "sha256": "a" * 64,+ },+ )+ marker_getter.assert_called_once_with(+ "ses-source",+ backend="codex",+ native_session_id="thread-source",+ key=CODEX_PROMPT_STRATEGY_METADATA_KEY,+ )++ async def test_fork_finalizes_a_source_prompt_with_pending_marker_persistence(self):+ agent = object.__new__(CodexAgent)+ agent.ensure_agent_session_id = Mock(return_value="ses-target")+ agent._fork_source_prompt_state = Mock(+ return_value=("injected_pending_persist", None, None)+ )+ agent._thread_unpersisted_prompts = {+ "ses-source": ("thread-source", "stable prompt", "fallback")+ }+ agent._resolve_codex_agent_settings = Mock(+ return_value=(None, "gpt-5.4", "high", None)+ )+ agent._inject_caller_env_config = Mock(return_value=("path-state", True))+ agent._mark_fork_correction_pending = Mock()+ agent._clear_fork_correction_pending = Mock()+ agent._should_rollback_forked_running_turn = AsyncMock(return_value=False)+ agent._inject_forked_session_correction = AsyncMock()+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent.bind_agent_session_id = Mock(return_value="ses-target")+ agent._persist_prompt_strategy = Mock(return_value=True)+ agent._remember_thread_model_settings_from_response = Mock()+ agent._remember_thread_caller_env_config = Mock()+ agent._remember_thread_git_path_config = Mock()+ agent._caller_env_for_request = Mock(return_value={})+ request = SimpleNamespace(+ working_path="/tmp/work",+ base_session_id="ses-target",+ )+ fork = {+ "source_session_id": "ses-source",+ "source_native_session_id": "thread-source",+ }+ transport = SimpleNamespace(+ send_request=AsyncMock(return_value={"thread": {"id": "thread-fork"}})+ )++ thread_id = await agent._fork_thread(transport, request, fork)++ self.assertEqual(thread_id, "thread-fork")+ agent._persist_prompt_strategy.assert_called_once_with(+ request,+ "thread-fork",+ "stable prompt",+ strategy="fallback",+ agent_session_id="ses-target",+ )+ self.assertEqual(+ agent._thread_developer_instructions["ses-target"],+ ("thread-fork", "stable prompt"),+ )+ self.assertEqual(+ agent._thread_prompt_strategies["ses-target"],+ ("thread-fork", "fallback"),+ )++ async def test_fork_persists_carried_collaboration_strategy_for_target(self):+ agent = object.__new__(CodexAgent)+ agent.ensure_agent_session_id = Mock(return_value="ses-target")+ agent._fork_source_prompt_state = Mock(+ return_value=("collaboration", None, None)+ )+ agent._resolve_codex_agent_settings = Mock(+ return_value=(None, "gpt-5.4", "high", None)+ )+ agent._inject_caller_env_config = Mock(return_value=("path-state", True))+ agent._mark_fork_correction_pending = Mock()+ agent._clear_fork_correction_pending = Mock()+ agent._should_rollback_forked_running_turn = AsyncMock(return_value=False)+ agent._inject_forked_session_correction = AsyncMock()+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent.bind_agent_session_id = Mock(return_value="ses-target")+ agent._persist_prompt_strategy = Mock(return_value=True)+ agent._remember_thread_model_settings_from_response = Mock()+ agent._remember_thread_caller_env_config = Mock()+ agent._remember_thread_git_path_config = Mock()+ agent._caller_env_for_request = Mock(return_value={})+ request = SimpleNamespace(+ working_path="/tmp/work",+ base_session_id="ses-target",+ )+ fork = {"source_native_session_id": "thread-source"}+ transport = SimpleNamespace(+ send_request=AsyncMock(return_value={"thread": {"id": "thread-fork"}})+ )++ thread_id = await agent._fork_thread(transport, request, fork)++ self.assertEqual(thread_id, "thread-fork")+ agent._persist_prompt_strategy.assert_called_once_with(+ request,+ "thread-fork",+ None,+ strategy="collaboration",+ agent_session_id="ses-target",+ )+ self.assertEqual(+ agent._thread_prompt_strategies["ses-target"],+ ("thread-fork", "collaboration"),+ )++ async def test_fork_does_not_cache_unpersisted_collaboration_strategy(self):+ agent = object.__new__(CodexAgent)+ agent.ensure_agent_session_id = Mock(return_value="ses-target")+ agent._fork_source_prompt_state = Mock(+ return_value=("collaboration", None, None)+ )+ agent._resolve_codex_agent_settings = Mock(+ return_value=(None, "gpt-5.4", "high", None)+ )+ agent._inject_caller_env_config = Mock(return_value=("path-state", True))+ agent._mark_fork_correction_pending = Mock()+ agent._clear_fork_correction_pending = Mock()+ agent._should_rollback_forked_running_turn = AsyncMock(return_value=False)+ agent._inject_forked_session_correction = AsyncMock()+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent.bind_agent_session_id = Mock(return_value="ses-target")+ agent._persist_prompt_strategy = Mock(return_value=False)+ request = SimpleNamespace(+ working_path="/tmp/work",+ base_session_id="ses-target",+ )+ fork = {"source_native_session_id": "thread-source"}+ transport = SimpleNamespace(+ send_request=AsyncMock(return_value={"thread": {"id": "thread-fork"}})+ )++ with self.assertRaisesRegex(+ CodexPromptRefreshUnavailableError,+ "Could not persist the forked Codex prompt strategy",+ ):+ await agent._fork_thread(transport, request, fork)++ self.assertNotIn(+ "ses-target",+ getattr(agent, "_thread_prompt_strategies", {}),+ )+async def test_start_or_resume_thread_does_not_bind_failed_fork_correction(self):agent = object.__new__(CodexAgent)agent.controller = SimpleNamespace(config=SimpleNamespace(platform="avibe", reply_enhancements=False))@@ -3130,7 +3373,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(method, "thread/resume")self.assertNotIn("modelProvider", params)- async def test_resume_thread_keeps_system_prompt_injection_when_quick_replies_are_disabled(self):+ async def test_resume_thread_clears_legacy_thread_prompt_before_turn_strategy(self):agent = object.__new__(CodexAgent)agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=False))agent.codex_config = SimpleNamespace(default_model=None)@@ -3138,7 +3381,9 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-existing"),ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"),+ get_agent_session_runtime_marker=Mock(return_value=None),)+ agent._prompt_state_agent_session_id = Mock(return_value="sesk8m4q2p7x")request = SimpleNamespace(working_path="/tmp/work",context=SimpleNamespace(@@ -3161,10 +3406,34 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(thread_id, "thread-existing")method, params = transport.send_request.await_args.argsself.assertEqual(method, "thread/resume")- self.assertIn("developerInstructions", params)- self.assertIn("# Avibe", params["developerInstructions"])- self.assertIn("If you generate an image with Codex", params["developerInstructions"])- self.assertNotIn("## Quick-reply buttons", params["developerInstructions"])+ self.assertIsNone(params["developerInstructions"])++ async def test_resume_thread_routes_prompt_marker_read_failure_through_i18n(self):+ agent = object.__new__(CodexAgent)+ agent.sessions = SimpleNamespace(+ get_agent_session_id=Mock(return_value="thread-existing"),+ get_agent_session_runtime_marker=Mock(+ side_effect=OSError("database busy")+ ),+ )+ agent.bind_agent_session_id = Mock()+ agent._prompt_state_agent_session_id = Mock(return_value="ses-runtime")+ request = SimpleNamespace(+ working_path="/tmp/work",+ context=SimpleNamespace(platform_specific={}),+ base_session_id="session-1",+ session_key="channel-1",+ subagent_name=None,+ )+ transport = SimpleNamespace(send_request=AsyncMock())++ with self.assertRaisesRegex(+ CodexPromptRefreshUnavailableError,+ "Could not resolve the Codex prompt strategy",+ ):+ await agent._start_or_resume_thread(transport, request)++ transport.send_request.assert_not_awaited()def test_thread_developer_instructions_follow_live_memory_enabled_state(self):agent = object.__new__(CodexAgent)@@ -3240,8 +3509,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(method, "thread/resume")self.assertEqual(params["threadId"], "thread-existing")self.assertNotIn("modelProvider", params)- self.assertIn("Current session id: `sesk8m4q2p7x`", params["developerInstructions"])- self.assertIn("# Avibe", params["developerInstructions"])+ self.assertNotIn("developerInstructions", params)async def test_refresh_thread_developer_instructions_refreshes_caller_env_when_prompt_cached(self):agent = object.__new__(CodexAgent)@@ -3282,7 +3550,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):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", first_params)self.assertNotIn("developerInstructions", second_params)self.assertEqual(second_params["config"]["shell_environment_policy"]["set"]["AVIBE_RUN_ID"],@@ -3417,20 +3685,24 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(method, "thread/resume")self.assertEqual(params["threadId"], "thread-existing")self.assertEqual(params["modelProvider"], "openai-managed")- self.assertIn("Current session id: `sesk8m4q2p7x`", params["developerInstructions"])-- async def test_start_turn_uses_sandbox_policy_object(self):- from core.native_dispatch_phase import (- DISPATCH_PHASE_PREWRITE,- backend_dispatch_attempted,- set_dispatch_phase,- )+ self.assertNotIn("developerInstructions", params)+ async def test_start_turn_applies_stable_developer_instructions_with_collaboration_mode(self):agent = object.__new__(CodexAgent)- agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, None, None)),+ )agent.codex_config = SimpleNamespace(default_model=None)- agent.ensure_agent_session_id = Mock()+ agent._thread_model_settings = {+ "session-1": ("thread-1", "gpt-5.4", "high"),+ }+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(return_value=None),+ set_agent_session_runtime_marker=Mock(return_value=True),+ )+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()agent._turn_registry = SimpleNamespace(begin_turn_start=Mock(),get_bootstrapped_turn_id=Mock(return_value=None),@@ -3445,67 +3717,1242 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):subagent_reasoning_effort=None,context=SimpleNamespace(platform_specific={}),)- set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)-- async def _send_at_native_boundary(*_args, **_kwargs):- self.assertIs(backend_dispatch_attempted(request.context), True)- return {"turn": {"id": "turn-1"}}-- transport = SimpleNamespace(send_request=AsyncMock(side_effect=_send_at_native_boundary))+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )- thread_id = await agent._start_turn(transport, request, "thread-1")+ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )+ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )- self.assertEqual(thread_id, "thread-1")- agent.ensure_agent_session_id.assert_called_once_with(request)- transport.send_request.assert_awaited_once_with(- "turn/start",- {- "threadId": "thread-1",- "input": [{"type": "text", "text": "hello"}],- "approvalPolicy": "never",- "sandboxPolicy": {"type": "dangerFullAccess"},+ first = transport.send_request.await_args_list[0].args[1]+ second = transport.send_request.await_args_list[1].args[1]+ expected_mode = {+ "mode": "default",+ "settings": {+ "model": "gpt-5.4",+ "reasoning_effort": "high",+ "developer_instructions": "stable prompt",+ },+ }+ self.assertEqual(first["collaborationMode"], expected_mode)+ self.assertEqual(second["collaborationMode"], expected_mode)+ agent.sessions.set_agent_session_runtime_marker.assert_called_once_with(+ "ses-runtime",+ backend="codex",+ native_session_id="thread-1",+ key="codex_prompt_strategy",+ value={+ "thread_id": "thread-1",+ "strategy": "collaboration",+ "sha256": agent._prompt_fingerprint("stable prompt"),},)- agent.controller.get_codex_overrides.assert_called_once_with(request.context)+ self.assertEqual(+ agent._thread_developer_instructions["session-1"],+ ("thread-1", "stable prompt"),+ )- async def test_start_turn_writes_current_caller_env_script_for_reused_threads(self):+ async def test_start_turn_persists_subagent_strategy_on_backend_session(self):agent = object.__new__(CodexAgent)- agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )agent.codex_config = SimpleNamespace(default_model=None)- agent.ensure_agent_session_id = Mock()+ agent.sessions = SimpleNamespace(+ get_agent_session_row_id=Mock(return_value="ses-backend"),+ get_agent_session_runtime_marker=Mock(return_value=None),+ set_agent_session_runtime_marker=Mock(return_value=True),+ )+ agent.ensure_agent_session_id = Mock(return_value="ses-visible")agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()agent._turn_registry = SimpleNamespace(begin_turn_start=Mock(),get_bootstrapped_turn_id=Mock(return_value=None),finalize_turn_start_response=Mock(return_value=SimpleNamespace()),)request = SimpleNamespace(- session_key="channel-1",- base_session_id="session-1",- composite_session_id="slack:C1:T1",- context=SimpleNamespace(- platform="slack",- platform_specific={- "task_execution_id": "run-two",- "task_trigger_kind": "agent_run",- "agent_session_target": {- "id": "sesk8m4q2p7x",- "agent_backend": "codex",- "native_session_id": "thread-existing",- },- },- ),- subagent_name=None,+ session_key="avibe::project::proj-1",+ base_session_id="session-1:subagent:reviewer",+ composite_session_id="avibe:session-1",+ subagent_name="reviewer",subagent_model=None,subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),)- transport = SimpleNamespace(send_request=AsyncMock(return_value={"turn": {"id": "turn-2"}}))-- with tempfile.TemporaryDirectory() as tmpdir:- with patch("config.paths.get_runtime_dir", return_value=Path(tmpdir)):- await agent._start_turn(transport, request, "thread-existing")- env_script = Path(tmpdir) / "codex-caller-env" / "session-1.sh"- script_text = env_script.read_text()++ await agent._start_turn(+ transport,+ request,+ "thread-subagent",+ developer_instructions="stable prompt",+ )++ agent.sessions.get_agent_session_row_id.assert_called_once_with(+ "avibe::project::proj-1",+ "session-1:subagent:reviewer",+ "codex",+ )+ agent.sessions.set_agent_session_runtime_marker.assert_called_once_with(+ "ses-backend",+ backend="codex",+ native_session_id="thread-subagent",+ key=CODEX_PROMPT_STRATEGY_METADATA_KEY,+ value={+ "thread_id": "thread-subagent",+ "strategy": "collaboration",+ "sha256": agent._prompt_fingerprint("stable prompt"),+ },+ )++ async def test_start_turn_honors_explicit_null_model_instead_of_cached_route(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "routing-model", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.sessions = SimpleNamespace()+ agent._thread_model_settings = {+ "session-1": ("thread-1", "gpt-5.4", "high"),+ }+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ vibe_agent_model=None,+ vibe_agent_reasoning_effort=None,+ vibe_agent_model_explicit=True,+ vibe_agent_reasoning_effort_explicit=True,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=False,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions=None,+ )++ params = transport.send_request.await_args.args[1]+ self.assertIsNone(params["model"])+ self.assertIsNone(params["effort"])+ self.assertNotIn("collaborationMode", params)+ self.assertNotIn("session-1", agent._thread_model_settings)++ async def test_start_turn_fails_when_fallback_strategy_cannot_persist(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(return_value=None),+ set_agent_session_runtime_marker=Mock(return_value=False),+ )+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(+ side_effect=[{}, {"turn": {"id": "turn-1"}}],+ ),+ )++ with self.assertRaisesRegex(+ CodexPromptRefreshUnavailableError,+ "Could not prepare the fallback prompt strategy",+ ):+ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ calls = transport.send_request.await_args_list+ self.assertEqual(+ [call.args[0] for call in calls],+ [],+ )+ self.assertNotIn("session-1", agent._thread_prompt_strategies)+ self.assertNotIn("session-1", getattr(agent, "_thread_developer_instructions", {}))++ async def test_start_turn_repairs_marker_without_reinjecting_known_prompt(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, None, None)),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(return_value=None),+ set_agent_session_runtime_marker=Mock(+ side_effect=[True, False, False, True]+ ),+ )+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(+ side_effect=[{}, {"turn": {"id": "turn-1"}}],+ ),+ )++ with self.assertRaisesRegex(+ CodexPromptRefreshUnavailableError,+ "Could not persist the fallback prompt strategy",+ ):+ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ self.assertEqual(+ [rpc.args[0] for rpc in transport.send_request.await_args_list],+ ["thread/inject_items", "turn/start"],+ )+ self.assertEqual(+ agent._thread_prompt_strategies["session-1"],+ ("thread-1", "fallback"),+ )+ self.assertNotIn("session-1", agent._thread_unpersisted_prompts)++ async def test_start_turn_reuses_persisted_fallback_prompt_after_process_restart(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ marker = {+ "thread_id": "thread-1",+ "strategy": "fallback",+ "sha256": agent._prompt_fingerprint("stable prompt"),+ }+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(return_value=marker),+ set_agent_session_runtime_marker=Mock(),+ )+ agent._thread_developer_instructions = {}+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ self.assertEqual(+ [call.args[0] for call in transport.send_request.await_args_list],+ ["turn/start"],+ )+ agent.sessions.get_agent_session_runtime_marker.assert_called_once_with(+ "ses-runtime",+ backend="codex",+ native_session_id="thread-1",+ key="codex_prompt_strategy",+ )+ agent.sessions.set_agent_session_runtime_marker.assert_not_called()+ self.assertEqual(+ agent._thread_developer_instructions["session-1"],+ ("thread-1", "stable prompt"),+ )+ self.assertEqual(+ agent._thread_prompt_strategies["session-1"],+ ("thread-1", "fallback"),+ )++ async def test_start_turn_disables_refresh_for_invalid_persisted_prompt_marker(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(+ return_value={+ "thread_id": "thread-1",+ "strategy": "future-strategy",+ }+ ),+ set_agent_session_runtime_marker=Mock(),+ )+ agent._thread_developer_instructions = {}+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="current prompt",+ )++ self.assertEqual(+ [call.args[0] for call in transport.send_request.await_args_list],+ ["turn/start"],+ )+ self.assertNotIn(+ "collaborationMode",+ transport.send_request.await_args_list[0].args[1],+ )+ agent.sessions.set_agent_session_runtime_marker.assert_not_called()+ self.assertEqual(+ agent._thread_prompt_strategies["session-1"],+ ("thread-1", "unavailable"),+ )++ def test_prompt_marker_read_failure_uses_localized_error_path(self):+ agent = object.__new__(CodexAgent)+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(side_effect=OSError("database busy"))+ )++ with self.assertRaisesRegex(+ CodexPromptRefreshUnavailableError,+ "Could not resolve the Codex prompt strategy",+ ):+ agent._read_persisted_prompt_strategy_marker(+ "thread-1",+ agent_session_id="ses-runtime",+ )++ async def test_start_turn_reuses_persisted_collaboration_after_inconclusive_probe(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ marker = {+ "thread_id": "thread-1",+ "strategy": "collaboration",+ "sha256": agent._prompt_fingerprint("stable prompt"),+ }+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(return_value=marker),+ set_agent_session_runtime_marker=Mock(),+ )+ agent._thread_developer_instructions = {}+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=False,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ self.assertEqual(+ [call.args[0] for call in transport.send_request.await_args_list],+ ["collaborationMode/list", "turn/start"],+ )+ params = transport.send_request.await_args_list[1].args[1]+ self.assertEqual(+ params["collaborationMode"]["settings"]["developer_instructions"],+ "stable prompt",+ )+ agent.sessions.set_agent_session_runtime_marker.assert_not_called()+ self.assertEqual(+ agent._thread_prompt_strategies["session-1"],+ ("thread-1", "collaboration"),+ )++ async def test_start_turn_fails_closed_when_collaboration_reprobe_is_negative(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ marker = {+ "thread_id": "thread-1",+ "strategy": "collaboration",+ "sha256": agent._prompt_fingerprint("stable prompt"),+ }+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(return_value=marker),+ )+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=False,+ send_request=AsyncMock(side_effect=TimeoutError("probe unavailable")),+ )++ with self.assertRaisesRegex(+ RuntimeError,+ "did not confirm collaboration mode support",+ ):+ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ transport.send_request.assert_awaited_once_with("collaborationMode/list", {})++ async def test_start_turn_clears_sticky_collaboration_mode_with_explicit_null_model(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "routing-model", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.sessions = SimpleNamespace(+ set_agent_session_runtime_marker=Mock(return_value=True),+ )+ agent._thread_developer_instructions = {+ "session-1": ("thread-1", "stable prompt"),+ }+ agent._thread_prompt_strategies = {+ "session-1": ("thread-1", "collaboration"),+ }+ agent._thread_model_settings = {+ "session-1": ("thread-1", "gpt-5.4", "high"),+ }+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ vibe_agent_model=None,+ vibe_agent_reasoning_effort=None,+ vibe_agent_model_explicit=True,+ vibe_agent_reasoning_effort_explicit=True,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(+ side_effect=[{}, {"turn": {"id": "turn-1"}}],+ ),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ calls = transport.send_request.await_args_list+ self.assertEqual([call.args[0] for call in calls], ["thread/inject_items", "turn/start"])+ turn_params = calls[1].args[1]+ self.assertIsNone(turn_params["collaborationMode"])+ self.assertIsNone(turn_params["model"])+ self.assertIsNone(turn_params["effort"])+ self.assertEqual(+ agent._thread_prompt_strategies["session-1"],+ ("thread-1", "fallback"),+ )++ async def test_start_turn_clears_persisted_collaboration_before_model_less_fallback(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, None, None)),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ marker = {+ "thread_id": "thread-1",+ "strategy": "collaboration",+ "sha256": agent._prompt_fingerprint("stable prompt"),+ }+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(return_value=marker),+ set_agent_session_runtime_marker=Mock(return_value=True),+ )+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=False,+ send_request=AsyncMock(+ side_effect=[{}, {}, {"turn": {"id": "turn-1"}}],+ ),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ calls = transport.send_request.await_args_list+ self.assertEqual(+ [call.args[0] for call in calls],+ ["collaborationMode/list", "thread/inject_items", "turn/start"],+ )+ self.assertIsNone(calls[2].args[1]["collaborationMode"])+ self.assertEqual(+ agent._thread_prompt_strategies["session-1"],+ ("thread-1", "fallback"),+ )++ async def test_start_turn_retries_a_pending_collaboration_clear_after_restart(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, None, None)),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ marker = {+ "thread_id": "thread-1",+ "strategy": "collaboration",+ "sha256": agent._prompt_fingerprint("stable prompt"),+ }++ def read_marker(*_args, **_kwargs):+ return dict(marker)++ def write_marker(*_args, **kwargs):+ marker.clear()+ marker.update(kwargs["value"])+ return True++ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(side_effect=read_marker),+ set_agent_session_runtime_marker=Mock(side_effect=write_marker),+ )+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ failed_transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(side_effect=[{}, TimeoutError("connection lost")]),+ )++ with self.assertRaisesRegex(+ CodexPromptRefreshUnavailableError,+ "cleared the previous collaboration prompt",+ ):+ await agent._start_turn(+ failed_transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ self.assertEqual(marker["strategy"], "fallback_pending_clear")+ self.assertEqual(+ marker["sha256"],+ agent._prompt_fingerprint("stable prompt"),+ )++ # Simulate a controller restart: only the durable transitional marker remains.+ agent._thread_prompt_strategies = {}+ agent._thread_developer_instructions = {}+ resumed_transport = SimpleNamespace(+ supports_turn_collaboration_mode=False,+ send_request=AsyncMock(+ side_effect=[{}, {"turn": {"id": "turn-2"}}],+ ),+ )++ await agent._start_turn(+ resumed_transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ resumed_calls = resumed_transport.send_request.await_args_list+ self.assertEqual(+ [call.args[0] for call in resumed_calls],+ ["collaborationMode/list", "turn/start"],+ )+ self.assertIsNone(resumed_calls[1].args[1]["collaborationMode"])+ self.assertEqual(marker["strategy"], "fallback")+ self.assertNotIn("pending_collaboration_clear", marker)+ self.assertEqual(+ agent._thread_prompt_strategies["session-1"],+ ("thread-1", "fallback"),+ )++ async def test_start_turn_clears_collaboration_without_reinjecting_after_unknown_injection(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, None, None)),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ marker = {+ "thread_id": "thread-1",+ "strategy": "collaboration",+ "sha256": agent._prompt_fingerprint("stable prompt"),+ }++ def read_marker(*_args, **_kwargs):+ return dict(marker)++ def write_marker(*_args, **kwargs):+ marker.clear()+ marker.update(kwargs["value"])+ return True++ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(side_effect=read_marker),+ set_agent_session_runtime_marker=Mock(side_effect=write_marker),+ )+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ failed_transport = SimpleNamespace(+ supports_turn_collaboration_mode=False,+ send_request=AsyncMock(+ side_effect=[{}, TimeoutError("injection outcome unknown")],+ ),+ )++ with self.assertRaisesRegex(TimeoutError, "injection outcome unknown"):+ await agent._start_turn(+ failed_transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ self.assertEqual(marker["strategy"], "fallback_pending_clear_injection")+ self.assertEqual(+ agent._thread_prompt_strategies["session-1"],+ ("thread-1", "fallback_pending_clear_injection"),+ )++ # Simulate a controller restart: recovery has only the write-ahead marker.+ agent._thread_prompt_strategies = {}+ agent._thread_developer_instructions = {}+ resumed_transport = SimpleNamespace(+ supports_turn_collaboration_mode=False,+ send_request=AsyncMock(+ side_effect=[{}, {"turn": {"id": "turn-2"}}],+ ),+ )++ await agent._start_turn(+ resumed_transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ resumed_calls = resumed_transport.send_request.await_args_list+ self.assertEqual(+ [call.args[0] for call in resumed_calls],+ ["collaborationMode/list", "turn/start"],+ )+ self.assertIsNone(resumed_calls[1].args[1]["collaborationMode"])+ self.assertEqual(marker["strategy"], "unavailable")+ self.assertNotIn("sha256", marker)+ self.assertEqual(+ agent._thread_prompt_strategies["session-1"],+ ("thread-1", "unavailable"),+ )++ def test_prompt_strategy_rebinds_a_stale_native_session_before_retry(self):+ agent = object.__new__(CodexAgent)+ agent.sessions = SimpleNamespace(+ set_agent_session_runtime_marker=Mock(side_effect=[False, True]),+ )+ agent.bind_agent_session_id = Mock(return_value="ses-runtime")+ request = SimpleNamespace(+ base_session_id="session-1",+ context=SimpleNamespace(platform_specific={}),+ )++ persisted = agent._persist_prompt_strategy(+ request,+ "thread-1",+ "stable prompt",+ strategy="collaboration",+ agent_session_id="ses-runtime",+ )++ self.assertTrue(persisted)+ agent.bind_agent_session_id.assert_called_once_with(request, "thread-1")+ self.assertEqual(+ agent.sessions.set_agent_session_runtime_marker.call_count,+ 2,+ )++ async def test_start_turn_persists_changed_fallback_prompt(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=Mock(+ return_value={+ "thread_id": "thread-1",+ "strategy": "fallback",+ "sha256": agent._prompt_fingerprint("old prompt"),+ }+ ),+ set_agent_session_runtime_marker=Mock(return_value=True),+ )+ agent._thread_developer_instructions = {}+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="avibe:session-1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="changed prompt",+ )++ self.assertEqual(+ [call.args[0] for call in transport.send_request.await_args_list],+ ["thread/inject_items", "turn/start"],+ )+ prompt_sha = agent._prompt_fingerprint("changed prompt")+ agent.sessions.set_agent_session_runtime_marker.assert_has_calls(+ [+ call(+ "ses-runtime",+ backend="codex",+ native_session_id="thread-1",+ key="codex_prompt_strategy",+ value={+ "thread_id": "thread-1",+ "strategy": "fallback_pending_injection",+ "sha256": prompt_sha,+ },+ ),+ call(+ "ses-runtime",+ backend="codex",+ native_session_id="thread-1",+ key="codex_prompt_strategy",+ value={+ "thread_id": "thread-1",+ "strategy": "fallback",+ "sha256": prompt_sha,+ },+ ),+ ]+ )++ async def test_start_turn_does_not_reuse_cached_effort_for_an_explicit_model_change(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.5", None)),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent._thread_model_settings = {+ "session-1": ("thread-1", "gpt-5.4", "high"),+ }+ agent.ensure_agent_session_id = Mock()+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="slack:C1:T1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ params = transport.send_request.await_args.args[1]+ self.assertEqual(params["model"], "gpt-5.5")+ self.assertNotIn("effort", params)+ self.assertEqual(params["collaborationMode"]["settings"]["model"], "gpt-5.5")+ self.assertIsNone(params["collaborationMode"]["settings"]["reasoning_effort"])++ async def test_start_turn_preserves_explicit_effort_while_restoring_cached_model(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, None, "xhigh")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent._thread_model_settings = {+ "session-1": ("thread-1", "gpt-5.4", "high"),+ }+ agent.ensure_agent_session_id = Mock()+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="slack:C1:T1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ params = transport.send_request.await_args.args[1]+ self.assertEqual(params["model"], "gpt-5.4")+ self.assertEqual(params["effort"], "xhigh")+ self.assertEqual(params["collaborationMode"]["settings"]["model"], "gpt-5.4")+ self.assertEqual(params["collaborationMode"]["settings"]["reasoning_effort"], "xhigh")++ async def test_start_turn_changes_only_collaboration_instructions_when_prompt_changes(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.ensure_agent_session_id = Mock()+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="slack:C1:T1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )++ for prompt in ("prompt one", "prompt two"):+ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions=prompt,+ )++ first = transport.send_request.await_args_list[0].args[1]+ second = transport.send_request.await_args_list[1].args[1]+ first_mode = first.pop("collaborationMode")+ second_mode = second.pop("collaborationMode")+ self.assertEqual(first, second)+ self.assertEqual(first_mode["settings"]["developer_instructions"], "prompt one")+ self.assertEqual(second_mode["settings"]["developer_instructions"], "prompt two")++ async def test_start_turn_falls_back_once_when_collaboration_mode_is_unsupported(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.ensure_agent_session_id = Mock()+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="slack:C1:T1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(+ side_effect=[+ RuntimeError("unknown field collaborationMode: experimental API unsupported"),+ {},+ {"turn": {"id": "turn-1"}},+ ]+ ),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ calls = transport.send_request.await_args_list+ self.assertIn("collaborationMode", calls[0].args[1])+ self.assertEqual(calls[1].args[0], "thread/inject_items")+ self.assertEqual(+ calls[1].args[1]["items"][0]["content"][0]["text"],+ "stable prompt",+ )+ self.assertNotIn("collaborationMode", calls[2].args[1])+ self.assertFalse(transport.supports_turn_collaboration_mode)++ async def test_start_turn_uses_injection_after_collaboration_probe_fails(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),+ )+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.ensure_agent_session_id = Mock()+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="slack:C1:T1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ transport = SimpleNamespace(+ supports_turn_collaboration_mode=False,+ send_request=AsyncMock(+ side_effect=[{}, {"turn": {"id": "turn-1"}}],+ ),+ )++ await agent._start_turn(+ transport,+ request,+ "thread-1",+ developer_instructions="stable prompt",+ )++ calls = transport.send_request.await_args_list+ self.assertEqual(calls[0].args[0], "thread/inject_items")+ self.assertEqual(+ calls[0].args[1]["items"][0]["content"][0]["text"],+ "stable prompt",+ )+ self.assertNotIn("collaborationMode", calls[1].args[1])++ async def test_start_turn_uses_sandbox_policy_object(self):+ from core.native_dispatch_phase import (+ DISPATCH_PHASE_PREWRITE,+ backend_dispatch_attempted,+ set_dispatch_phase,+ )++ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.ensure_agent_session_id = Mock()+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="slack:C1:T1",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)++ async def _send_at_native_boundary(*_args, **_kwargs):+ self.assertIs(backend_dispatch_attempted(request.context), True)+ return {"turn": {"id": "turn-1"}}++ transport = SimpleNamespace(send_request=AsyncMock(side_effect=_send_at_native_boundary))++ thread_id = await agent._start_turn(transport, request, "thread-1")++ self.assertEqual(thread_id, "thread-1")+ agent.ensure_agent_session_id.assert_called_once_with(request)+ transport.send_request.assert_awaited_once_with(+ "turn/start",+ {+ "threadId": "thread-1",+ "input": [{"type": "text", "text": "hello"}],+ "approvalPolicy": "never",+ "sandboxPolicy": {"type": "dangerFullAccess"},+ },+ )+ agent.controller.get_codex_overrides.assert_called_once_with(request.context)++ async def test_start_turn_writes_current_caller_env_script_for_reused_threads(self):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))+ agent.codex_config = SimpleNamespace(default_model=None)+ agent.ensure_agent_session_id = Mock()+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ request = SimpleNamespace(+ session_key="channel-1",+ base_session_id="session-1",+ composite_session_id="slack:C1:T1",+ context=SimpleNamespace(+ platform="slack",+ platform_specific={+ "task_execution_id": "run-two",+ "task_trigger_kind": "agent_run",+ "agent_session_target": {+ "id": "sesk8m4q2p7x",+ "agent_backend": "codex",+ "native_session_id": "thread-existing",+ },+ },+ ),+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ )+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"turn": {"id": "turn-2"}}))++ with tempfile.TemporaryDirectory() as tmpdir:+ with patch("config.paths.get_runtime_dir", return_value=Path(tmpdir)):+ await agent._start_turn(transport, request, "thread-existing")+ env_script = Path(tmpdir) / "codex-caller-env" / "session-1.sh"+ script_text = env_script.read_text()params = transport.send_request.await_args.args[1]self.assertNotIn("config", params)@@ -3772,9 +5219,17 @@ class CodexTransportCommandTests(unittest.IsolatedAsyncioTestCase):class _FakeStdin:def __init__(self):self._closing = False+ self._request_events = {+ 1: asyncio.Event(),+ 2: asyncio.Event(),+ }def write(self, data):writes.append(data.decode())+ message = json.loads(data)+ request_id = message.get("id")+ if request_id in self._request_events:+ self._request_events[request_id].set()async def drain(self):return None@@ -3786,12 +5241,22 @@ class CodexTransportCommandTests(unittest.IsolatedAsyncioTestCase):self._closing = Trueclass _FakeStdout:- def __init__(self):- self._lines = [b'{"jsonrpc":"2.0","id":1,"result":{}}\n']+ def __init__(self, stdin):+ self._stdin = stdin+ self._next_response_id = 1async def readline(self):- if self._lines:- return self._lines.pop(0)+ if self._next_response_id <= 2:+ response_id = self._next_response_id+ await self._stdin._request_events[response_id].wait()+ self._next_response_id += 1+ return json.dumps(+ {+ "jsonrpc": "2.0",+ "id": response_id,+ "result": {"data": []} if response_id == 2 else {},+ }+ ).encode() + b"\n"await asyncio.Event().wait()return b""@@ -3802,7 +5267,7 @@ class CodexTransportCommandTests(unittest.IsolatedAsyncioTestCase):class _FakeProcess:def __init__(self):self.stdin = _FakeStdin()- self.stdout = _FakeStdout()+ self.stdout = _FakeStdout(self.stdin)self.stderr = _FakeStderr()self.pid = 123self.returncode = None@@ -3833,7 +5298,7 @@ class CodexTransportCommandTests(unittest.IsolatedAsyncioTestCase):"title": "Avibe","version": "1.0.0",},- "capabilities": {"experimentalApi": False},+ "capabilities": {"experimentalApi": True},},)transport = Transport(@@ -3911,6 +5376,51 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent._transport_last_activity["/tmp/work"], 0.0)self.assertEqual(agent._session_last_activity, {})+ async def test_request_user_input_returns_valid_empty_answers(self):+ agent = self._agent()++ result = await agent._on_server_request(+ "/tmp/work",+ 8,+ "item/tool/requestUserInput",+ {+ "threadId": "thread-1",+ "turnId": "turn-1",+ "itemId": "item-1",+ "isBlocking": True,+ "questions": [],+ },+ )++ self.assertEqual(result, {"answers": {}})++ async def test_current_time_request_returns_protocol_shape(self):+ agent = self._agent()++ with patch.object(_MODULE.time, "time", return_value=1234.9):+ result = await agent._on_server_request(+ "/tmp/work",+ 9,+ "currentTime/read",+ {"threadId": "thread-1"},+ )++ self.assertEqual(result, {"currentTimeAt": 1234})++ async def test_unhandled_experimental_server_request_is_rejected(self):+ agent = self._agent()++ with self.assertRaisesRegex(+ NotImplementedError,+ "Unsupported Codex server request: item/permissions/requestApproval",+ ):+ await agent._on_server_request(+ "/tmp/work",+ 10,+ "item/permissions/requestApproval",+ {"itemId": "item-1"},+ )+def test_turn_start_refreshes_the_cwd_transport_clock(self):agent = self._agent()agent._transport_last_activity = {"/tmp/work": 0.0}diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.pyindex 36e393502..01a09c531 100644--- a/tests/test_codex_transport.py+++ b/tests/test_codex_transport.py@@ -51,9 +51,11 @@ class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):],)- async def wait_for_initialize(_method, _params):- initialize_started.set()- await asyncio.Event().wait()+ async def wait_for_initialize(method, _params):+ if method == "initialize":+ initialize_started.set()+ await asyncio.Event().wait()+ return {}async def stop_transport():transport._cleanup_tasks()@@ -104,10 +106,81 @@ class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):"title": "Avibe","version": "1.0.0",},- "capabilities": {"experimentalApi": False},+ "capabilities": {"experimentalApi": True},},)+ async def test_start_probes_turn_collaboration_mode_support(self):+ class _Stream:+ async def readline(self):+ await asyncio.Event().wait()++ process = SimpleNamespace(+ pid=123,+ returncode=None,+ stdin=None,+ stdout=_Stream(),+ stderr=_Stream(),+ )+ transport = CodexTransport(binary="codex", cwd="/tmp")+ transport.send_request = AsyncMock(+ side_effect=[{}, {"data": [{"mode": "default"}]}]+ )+ transport.send_notification = AsyncMock()+ transport.stop = AsyncMock(side_effect=transport._cleanup_tasks)++ with (+ patch(+ "modules.agents.codex.transport.asyncio.create_subprocess_exec",+ new=AsyncMock(return_value=process),+ ),+ patch("modules.agents.codex.transport.process_identity", return_value={}),+ patch("modules.agents.codex.transport.log_process_snapshot"),+ ):+ await transport.start()++ self.assertTrue(transport.supports_turn_collaboration_mode)+ self.assertEqual(+ [call.args[0] for call in transport.send_request.await_args_list],+ ["initialize", "collaborationMode/list"],+ )+ transport.stop.assert_not_awaited()+ transport._cleanup_tasks()++ async def test_start_falls_back_when_turn_collaboration_probe_is_unsupported(self):+ class _Stream:+ async def readline(self):+ await asyncio.Event().wait()++ process = SimpleNamespace(+ pid=123,+ returncode=None,+ stdin=None,+ stdout=_Stream(),+ stderr=_Stream(),+ )+ transport = CodexTransport(binary="codex", cwd="/tmp")+ transport.send_request = AsyncMock(+ side_effect=[{}, RuntimeError("method not found")]+ )+ transport.send_notification = AsyncMock()+ transport.stop = AsyncMock(side_effect=transport._cleanup_tasks)++ with (+ patch(+ "modules.agents.codex.transport.asyncio.create_subprocess_exec",+ new=AsyncMock(return_value=process),+ ),+ patch("modules.agents.codex.transport.process_identity", return_value={}),+ patch("modules.agents.codex.transport.log_process_snapshot"),+ ):+ await transport.start()++ self.assertFalse(transport.supports_turn_collaboration_mode)+ self.assertTrue(transport.is_initialized)+ transport.stop.assert_not_awaited()+ transport._cleanup_tasks()+def test_app_server_policy_disables_competing_host_surfaces(self):disabled = set(AVIBE_APP_SERVER_CONFIG_OVERRIDES)@@ -120,6 +193,7 @@ class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):"features.multi_agent=false","features.plugins=false","features.terminal_visualization_instructions=false",+ "skills.include_instructions=false",}.issubset(disabled))# ``agents`` is a role-definition table in older supported Codexdiff --git a/tests/test_harness_skill_guidance.py b/tests/test_harness_skill_guidance.pyindex 06f3cb4fd..3c4d8b3e1 100644--- a/tests/test_harness_skill_guidance.py+++ b/tests/test_harness_skill_guidance.py@@ -4,6 +4,8 @@ import reimport shlexfrom pathlib import Path+from core.system_prompt_injection import build_system_prompt_injection+from modules.im.base import MessageContextfrom vibe import cli@@ -33,7 +35,7 @@ def _embedded_cli_examples(body: str) -> list[str]:return sorted(found)-def test_avibe_skills_teach_current_harness_defaults() -> None:+def test_avibe_compatibility_skill_teaches_current_harness_defaults() -> None:for path in ("skills/use-avibe/SKILL.md",):body = _read(path)@@ -56,17 +58,29 @@ def test_avibe_skills_teach_current_harness_defaults() -> None:assert "follows the caller or source Session cwd" not in body-def test_injected_harness_prompt_examples_parse_against_the_real_cli() -> None:- """CLI examples in the injected prompt are live callers, so they must parse.+def test_harness_guidance_examples_parse_against_the_real_cli() -> None:+ """CLI examples in the prompt and its routed Skill must parse.The agent reads this prompt and runs what it finds. An example that argparserejects — a renamed flag, a dropped one, a form that never existed — teachesthe agent a call that fails at runtime. `tests/test_agent_tool_policy.py`- guards the same rule for the native-scheduler denial strings; this guards the- Harness prompt itself, which is where scheduled-command guidance lives.+ guards the same rule for the native-scheduler denial strings. Harness+ operational detail now lives in ``use-avibe-harness`` while the always-on+ prompt retains only routing and live safety boundaries."""- examples = _embedded_cli_examples(_read("core/system_prompt_injection.py"))+ prompt = build_system_prompt_injection(+ context=MessageContext(+ user_id="user",+ channel_id="channel",+ platform="avibe",+ platform_specific={"agent_session_id": "ses-test"},+ ),+ current_agent_backend="codex",+ )+ examples = _embedded_cli_examples(+ prompt + "\n" + _read("skills/use-avibe-harness/SKILL.md")+ )assert examples, "no embedded vibe task/watch examples found — did the regex drift?"parser = cli.build_parser()@@ -130,6 +144,20 @@ def test_use_avibe_skill_keeps_its_broad_scope_without_a_session_lifecycle_protoassert text not in body+def test_use_avibe_harness_owns_the_extracted_harness_protocol() -> None:+ body = _read("skills/use-avibe-harness/SKILL.md")++ assert "Avibe Harness turns user intent into durable Agent work" in body+ assert "Avibe Harness is the first-choice automation layer" in body+ assert "### Mental model" in body+ assert "### Inspecting Harness state" in body+ assert "### Choosing the right Harness shape" in body+ assert "Watch waiter contract" in body+ assert "That existing-Session send is a P1 delivery by default" in body+ assert "### Agents" in body+ assert "### Mentions in user messages" in body++def test_background_watch_skill_defaults_to_current_session() -> None:body = _read("skills/background-watch-hook/SKILL.md")diff --git a/tests/test_managed_skills.py b/tests/test_managed_skills.pyindex b588a7b6e..68da52ea9 100644--- a/tests/test_managed_skills.py+++ b/tests/test_managed_skills.py@@ -542,6 +542,27 @@ def test_catalog_paginates_stably_without_exposing_directories(tmp_path: Path) -assert render_skill_catalog_prompt([]) == ""+def test_catalog_rendering_is_byte_stable_for_any_input_order(tmp_path: Path) -> None:+ skills = []+ for name in ("zeta", "alpha", "middle"):+ skill_file = _write_skill(+ tmp_path / "skills",+ name,+ name,+ f"Description for {name}",+ )+ skill = parse_skill_file(skill_file, priority=(1, 0, 1))+ assert skill is not None+ skills.append(skill)++ forward = render_skill_catalog_prompt(skills)+ reverse = render_skill_catalog_prompt(list(reversed(skills)))++ assert forward == reverse+ assert forward.index("- alpha:") < forward.index("- middle:")+ assert forward.index("- middle:") < forward.index("- zeta:")++def test_manual_only_skill_is_loadable_but_not_advertised(tmp_path: Path) -> None:skill_file = tmp_path / "manual" / "SKILL.md"skill_file.parent.mkdir()@@ -618,6 +639,11 @@ def test_system_prompt_catalog_reflects_add_edit_and_delete_each_render(tmp_pathbefore = build_system_prompt_injection(skills_cwd=cwd)skill_file = _write_skill(cwd / ".agents" / "skills", "live", "live", "First")after_install = build_system_prompt_injection(skills_cwd=cwd)+ skill_file.write_text(+ "---\nname: live\ndescription: First\n---\nBody changed without catalog metadata\n",+ encoding="utf-8",+ )+ after_body_update = build_system_prompt_injection(skills_cwd=cwd)skill_file.write_text("---\nname: live\ndescription: Updated\n---\nUpdated body\n",encoding="utf-8",@@ -628,7 +654,9 @@ def test_system_prompt_catalog_reflects_add_edit_and_delete_each_render(tmp_pathassert "## Skills" not in beforeassert "- live: First" in after_install+ assert after_body_update == after_installassert "- live: Updated" in after_update+ assert after_update != after_body_updateassert "## Skills" not in after_delete@@ -1518,6 +1546,26 @@ def test_publication_charges_file_growth_at_copy_time(publish_builtin_skills(source_root=source, destination_root=destination)+def test_authoritative_builtin_source_contains_prompt_modules() -> None:+ source = managed_skills.builtin_skills_source()++ expected = {+ "use-avibe-harness": "Avibe Harness turns user intent into durable Agent work",+ "use-avibe-vault": "the child process receives static secrets as environment variables",+ "use-show-pages": "Every Show Page URL is agent-readable without page-specific code",+ }+ for name, migrated_text in expected.items():+ skill = parse_skill_file(+ source / name / "SKILL.md",+ priority=(0, 0, 0),+ include_body=True,+ )+ assert skill is not None+ assert skill.name == name+ assert skill.body is not None+ assert migrated_text in skill.body++def test_builtin_source_ignores_an_unrelated_top_level_skills_directory(tmp_path: Path,monkeypatch,diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex 915e0213a..856641763 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -53,6 +53,8 @@ def _load_message_handler_class():vibe_agent_backend: str | None = Nonevibe_agent_model: str | None = Nonevibe_agent_reasoning_effort: str | None = None+ vibe_agent_model_explicit: bool = False+ vibe_agent_reasoning_effort_explicit: bool = Falsevibe_agent_system_prompt: str | None = Nonefiles: list | None = None@@ -1332,6 +1334,9 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):await handler.handle_user_message(context, "hello")+ _agent_name, request = controller.agent_service.requests[0]+ self.assertTrue(request.vibe_agent_model_explicit)+ self.assertFalse(request.vibe_agent_reasoning_effort_explicit)sessions_store.materialize_agent_session_route.assert_called_once_with("ses_wb",agent_id="agent-default",diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex a6a314645..9df23d78e 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -26,6 +26,10 @@ from modules.agents.base import AgentRequestfrom modules.agents.model_hub import launch_for_contextfrom modules.agents.service import AgentServicefrom modules.agents.opencode.agent import OpenCodeAgent+from modules.agents.opencode.server import (+ OpenCodeManagedPolicyRefreshPendingError,+ OpenCodeRuntimeConfigInvalidError,+)from modules.agents.opencode.poll_loop import (OpenCodePollLoop,_settlement_assistant_message,@@ -42,6 +46,38 @@ class _StubConfig(BaseIMConfig):return None+def test_opencode_policy_refresh_failure_is_localized() -> None:+ agent = OpenCodeAgent.__new__(OpenCodeAgent)+ agent.controller = type(+ "Controller",+ (),+ {"config": type("Config", (), {"language": "zh"})()},+ )()++ display = agent._server_start_error_display_text(+ OpenCodeManagedPolicyRefreshPendingError("internal diagnostic")+ )++ assert "仍在完成已有回合" in display+ assert "internal diagnostic" not in display+++def test_opencode_runtime_config_failure_is_localized() -> None:+ agent = OpenCodeAgent.__new__(OpenCodeAgent)+ agent.controller = type(+ "Controller",+ (),+ {"config": type("Config", (), {"language": "zh"})()},+ )()++ display = agent._server_start_error_display_text(+ OpenCodeRuntimeConfigInvalidError("internal diagnostic")+ )++ assert "运行时配置" in display+ assert "internal diagnostic" not in display++class _StubClient(BaseIMClient):def __init__(self, name: str, *, supports_editing: bool = True, run_until_stopped: bool = False):super().__init__(_StubConfig())@@ -1334,6 +1370,7 @@ def test_opencode_normal_text_matching_legacy_question_prefix_is_processed():def test_opencode_process_message_removes_active_poll_when_question_tool_aborts():removed = []ack_removed = []+ retirement_order = []request_context = MessageContext(user_id="u",@@ -1358,6 +1395,7 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(return Noneasync def mark_run_inactive(self, session_id):+ retirement_order.append(("marker", session_id))return Nonedef get_default_agent_from_config(self):@@ -1390,6 +1428,7 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(return Nonedef remove_active_poll(self, session_id):+ retirement_order.append(("poll", session_id))removed.append(session_id)class _PollLoop:@@ -1452,6 +1491,10 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(asyncio.run(agent._process_message(request))+ assert retirement_order == [+ ("marker", "oc-session"),+ ("poll", "oc-session"),+ ]assert removed == ["oc-session"]assert ack_removed == ["base"]@@ -2702,9 +2745,10 @@ def test_opencode_restored_poll_settles_error_after_retry_budget(monkeypatch):prompt_started_at=time.time(),)- asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))+ terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))- assert removed == ["oc-session"]+ assert terminal is True+ assert removed == []assert any(item[0] == "result" and item[2] is True for item in emitted)assert all("No response from OpenCode" not in str(item) for item in results)assert any("certificate failed" in (item[1] or "") for item in emitted)@@ -2832,10 +2876,11 @@ def test_opencode_restored_poll_keeps_empty_completion_successful():)loop = OpenCodePollLoop(_Agent())- asyncio.run(loop.run_restored_poll_loop(poll))+ terminal = asyncio.run(loop.run_restored_poll_loop(poll))assert diagnostics == []- assert removed == ["oc-session"]+ assert terminal is True+ assert removed == []assert emitted == [("notify",@@ -2942,10 +2987,11 @@ def test_opencode_restored_poll_settles_after_consecutive_transport_failures(prompt_started_at=time.time(),)- asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))+ terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))assert aborted == [("oc-restored-transport-dead", "/tmp/work")]- assert removed == ["oc-restored-transport-dead"]+ assert terminal is True+ assert removed == []assert any(item[0] == "notify" and item[1] == "error.opencodePollTransportFailure:3"for item in emitted@@ -3037,11 +3083,12 @@ def test_opencode_restored_poll_consumes_original_timeout_budget():prompt_started_at=time.time() - 1,)- asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))+ terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))assert list_calls == []assert aborted == [("oc-restored-timeout", "/tmp/work")]- assert removed == ["oc-restored-timeout"]+ assert terminal is True+ assert removed == []assert [item[0] for item in emitted] == ["notify", "notify", "result"]assert emitted[1][1] == "error.opencodeActiveTurnTimeout:0.05"assert emitted[2][1:] == (@@ -3552,7 +3599,7 @@ def test_mh_chan_001_opencode_restored_poll_records_source_failure():},)- asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))+ terminal = asyncio.run(OpenCodePollLoop(_Agent()).run_restored_poll_loop(poll))assert model_hub_failures == [(@@ -3561,7 +3608,8 @@ def test_mh_chan_001_opencode_restored_poll_records_source_failure():"NativeSessionEndedBeforeResult - OpenCode 已结束,但没有产出模型回复。",)]- assert removed == ["oc-restored-error"]+ assert terminal is True+ assert removed == []assert [item[0] for item in emitted] == ["notify", "notify", "result"]assert emitted[1][1] == ("OpenCode 错误:NativeSessionEndedBeforeResult - "diff --git a/tests/test_opencode_caller_context.py b/tests/test_opencode_caller_context.pyindex 101c5e9de..39cffa2a6 100644--- a/tests/test_opencode_caller_context.py+++ b/tests/test_opencode_caller_context.py@@ -3,9 +3,14 @@ from __future__ import annotationsfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timedelta, timezoneimport json+import osfrom pathlib import Path+import shutil+import subprocessimport threading+import pytest+from core import git_runtimefrom modules.agents.opencode import caller_context as bridge@@ -21,11 +26,70 @@ def test_ensure_plugin_installed_writes_global_opencode_plugin(tmp_path: Path, massert result.changed is Truesource = path.read_text(encoding="utf-8")assert '"shell.env"' in source+ assert '"experimental.chat.system.transform"' in sourceassert "AVIBE_OPENCODE_CALLER_CONTEXT_PATH" in source+ assert "Skills provide specialized instructions and workflows" in source+ assert "</available_skills>" in source+ assert "if (!bindingPath" in source+ assert "output.system.splice" in sourceassert bridge.ensure_plugin_installed().changed is False+def test_plugin_removes_native_catalog_without_touching_managed_catalog(+ tmp_path: Path,+ monkeypatch,+) -> None:+ node = shutil.which("node")+ if node is None:+ pytest.skip("Node.js is required to execute the OpenCode runtime plugin")+ xdg_home = tmp_path / "xdg"+ monkeypatch.setenv("XDG_CONFIG_HOME", str(xdg_home))+ plugin = bridge.ensure_plugin_installed().path+ native = (+ "before\n"+ "Skills provide specialized instructions and workflows for specific tasks.\n"+ "Use the skill tool to load a skill when a task matches its description.\n"+ "<available_skills>\n"+ " <skill><name>native-only</name></skill>\n"+ "</available_skills>\n"+ "after"+ )+ managed = "## Skills\n\n### Available skills\n- managed-only: Managed by Avibe."+ script = f"""+import {{ AvibeCallerContextPlugin }} from {json.dumps(plugin.as_uri())}+const hooks = await AvibeCallerContextPlugin()+const output = {{ system: {json.dumps([native, managed])} }}+await hooks["experimental.chat.system.transform"]({{}}, output)+process.stdout.write(JSON.stringify(output.system))+"""+ env = os.environ.copy()+ env["AVIBE_OPENCODE_CALLER_CONTEXT_PATH"] = str(tmp_path / "bindings.json")+ completed = subprocess.run(+ [node, "--input-type=module", "--eval", script],+ check=True,+ capture_output=True,+ env=env,+ text=True,+ timeout=10,+ )++ assert json.loads(completed.stdout) == ["before\nafter", managed]++ direct_env = os.environ.copy()+ direct_env.pop("AVIBE_OPENCODE_CALLER_CONTEXT_PATH", None)+ direct = subprocess.run(+ [node, "--input-type=module", "--eval", script],+ check=True,+ capture_output=True,+ env=direct_env,+ text=True,+ timeout=10,+ )++ assert json.loads(direct.stdout) == [native, managed]++def test_bind_session_writes_env_binding(tmp_path: Path, monkeypatch) -> None:avibe_home = tmp_path / "avibe"monkeypatch.setenv("AVIBE_HOME", str(avibe_home))diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.pyindex cab6b6814..b3aa16618 100644--- a/tests/test_opencode_restore_polls.py+++ b/tests/test_opencode_restore_polls.py@@ -50,6 +50,7 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "enremoved: list[str] = []request_sessions: list[tuple[str, str, str, str]] = []prompt_calls: list[dict] = []+ inactive_runs: list[str] = []class _Server:def __init__(self):@@ -58,6 +59,7 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "enself.status = {"type": "busy"}self.status_error = Noneself.mark_run_active_error = None+ self.mark_run_inactive_error = Noneasync def list_messages(self, session_id, directory):# One in-progress assistant message → the session is "still active",@@ -72,6 +74,9 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "enreturn Noneasync def mark_run_inactive(self, session_id):+ if self.mark_run_inactive_error is not None:+ raise self.mark_run_inactive_error+ inactive_runs.append(session_id)return Noneasync def get_session_status(self, session_id, directory):@@ -84,8 +89,7 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "enclass _PollLoop:async def run_restored_poll_loop(self, poll_info):- active_polls.pop(poll_info.opencode_session_id, None)- return None+ return Trueasync def remove_restored_ack(self, poll_info):return None@@ -147,6 +151,7 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "enagent._get_server = _get_serveragent.controller.agent_service = SimpleNamespace(agents={"opencode": agent}, _turn_gates={})agent._test_prompt_calls = prompt_calls+ agent._test_inactive_runs = inactive_runsagent._test_server = serverreturn agent, status_writes, removed, request_sessions@@ -229,7 +234,7 @@ def test_restore_binding_failure_does_not_strand_durable_poll(monkeypatch) -> Noassert asyncio.run(run()) == 1assert attempts == 3- assert removed == []+ assert removed == ["oc-1"]def test_restore_retries_binding_for_the_active_poll_lifetime(monkeypatch) -> None:@@ -249,8 +254,7 @@ def test_restore_retries_binding_for_the_active_poll_lifetime(monkeypatch) -> Noasync def run_restored_poll_loop(self, _poll_info):for _ in range(100):if attempts >= 4:- agent.sessions.remove_active_poll("oc-1")- return+ return Trueawait asyncio.sleep(0)raise AssertionError("restored binding was not retried")@@ -293,8 +297,7 @@ def test_restore_delayed_binding_does_not_replace_a_newer_turn(monkeypatch) -> Nasync def run_restored_poll_loop(self, _poll_info):for _ in range(100):if len(attempts) >= 4:- agent.sessions.remove_active_poll("oc-1")- return+ return Trueawait asyncio.sleep(0)raise AssertionError("restored binding was not retried")@@ -650,6 +653,7 @@ def test_restore_reconciles_definitive_missing_start_attempt() -> None:assert asyncio.run(agent.restore_active_polls()) == 0assert reconciled == [("logical-missing", ATTEMPT_ID, "opencode")]assert removed == ["oc-1"]+ assert agent._test_inactive_runs == ["oc-1"]def test_restore_keeps_accepted_steer_with_post_assistant_user_evidence() -> None:@@ -707,6 +711,58 @@ def test_restore_does_not_treat_initial_user_prompt_as_steer_evidence() -> None:assert asyncio.run(agent.restore_active_polls()) == 0assert removed == ["oc-1"]+ assert agent._test_inactive_runs == ["oc-1"]+++def test_restore_continues_after_inactive_marker_cannot_be_persisted() -> None:+ stale_poll = _make_poll(+ platform="avibe",+ base_session_id="ses_stale",+ opencode_session_id="oc-stale",+ )+ active_poll = _make_poll(+ platform="avibe",+ base_session_id="ses_active",+ opencode_session_id="oc-active",+ )+ active_polls = {"oc-stale": stale_poll, "oc-active": active_poll}+ agent, _, removed, _ = _build_agent(active_polls)++ async def _list_messages(session_id, directory):+ del directory+ if session_id == "oc-stale":+ return []+ return [{"info": {"role": "assistant", "time": {}}}]++ async def _get_session_status(session_id, directory):+ del directory+ return {"type": "idle" if session_id == "oc-stale" else "busy"}++ async def _mark_run_inactive(session_id):+ if session_id == "oc-stale":+ raise OSError("read-only pid file")++ agent._test_server.list_messages = _list_messages+ agent._test_server.get_session_status = _get_session_status+ agent._test_server.mark_run_inactive = _mark_run_inactive++ assert asyncio.run(agent.restore_active_polls()) == 1++ assert removed == ["oc-active"]+ assert active_polls == {"oc-stale": stale_poll}+++def test_terminal_poll_is_preserved_when_inactive_marker_cannot_be_persisted() -> None:+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")+ active_polls = {"oc-1": poll}+ agent, _, removed, _ = _build_agent(active_polls)+ agent._test_server.mark_run_inactive_error = OSError("read-only pid file")++ retired = asyncio.run(agent._retire_active_poll(agent._test_server, "oc-1"))++ assert retired is False+ assert removed == []+ assert active_polls == {"oc-1": poll}def test_restore_excludes_baseline_assistant_from_steer_evidence() -> None:diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.pyindex 351d8e66e..02b15222d 100644--- a/tests/test_opencode_server.py+++ b/tests/test_opencode_server.py@@ -42,6 +42,10 @@ def _load_server_module():SERVER_MODULE = _load_server_module()+OpenCodeManagedPolicyRefreshPendingError = (+ SERVER_MODULE.OpenCodeManagedPolicyRefreshPendingError+)+OpenCodeRuntimeConfigInvalidError = SERVER_MODULE.OpenCodeRuntimeConfigInvalidErrorOpenCodeServerManager = SERVER_MODULE.OpenCodeServerManager@@ -125,6 +129,29 @@ class _FakeSession:class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):+ def test_managed_runtime_config_accepts_jsonc_and_disables_native_skill(self):+ content = SERVER_MODULE._managed_runtime_config_content(+ b'''\xef\xbb\xbf{+ // OpenCode accepts JSONC in this inherited override.+ "permission": "ask",+ "tools": {"bash": true,},+ }'''+ )++ self.assertEqual(+ json.loads(content),+ {+ "permission": {"*": "ask", "skill": "deny"},+ "tools": {"bash": True, "skill": False},+ },+ )++ def test_managed_runtime_config_uses_typed_validation_errors(self):+ for content in ("{invalid", "[]", '{"permission":[]}'):+ with self.subTest(content=content):+ with self.assertRaises(OpenCodeRuntimeConfigInvalidError):+ SERVER_MODULE._managed_runtime_config_content(content)+async def test_start_server_reaps_a_live_process_after_cold_start_timeout(self):manager = OpenCodeServerManager(binary="opencode", port=4096)process = types.SimpleNamespace(pid=4321, returncode=None)@@ -160,7 +187,17 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(manager._clear_pid_file.call_count, 2)self.assertIsNone(manager._process)self.assertIsNone(manager._process_loop)- self.assertEqual(create_process.await_args.kwargs["env"]["OPENCODE_CONFIG_CONTENT"], user_config)+ self.assertEqual(+ json.loads(create_process.await_args.kwargs["env"]["OPENCODE_CONFIG_CONTENT"]),+ {+ "permission": {"*": "ask", "skill": "deny"},+ "tools": {"skill": False},+ },+ )+ self.assertEqual(+ create_process.await_args.kwargs["env"]["OPENCODE_DISABLE_EXTERNAL_SKILLS"],+ "1",+ )def test_terminate_instance_sync_stops_unadopted_managed_server(self):with tempfile.TemporaryDirectory() as tmp_dir:@@ -425,7 +462,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):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]+ manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "caller_context_path": manager._caller_context_path(), "owner_pid": SERVER_MODULE._CURRENT_OWNER_PID, "runtime_policy_revision": SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION} # type: ignore[method-assign]manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]with patch.object(@@ -447,7 +484,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):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]+ manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "caller_context_path": manager._caller_context_path(), "owner_pid": SERVER_MODULE._CURRENT_OWNER_PID, "runtime_policy_revision": SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION} # type: ignore[method-assign]manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]with patch.object(@@ -485,6 +522,128 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(started, [True])self.assertFalse(manager._caller_context_plugin_refresh_pending)+ async def test_ensure_running_restarts_idle_adopted_server_with_stale_runtime_policy(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: { # type: ignore[method-assign]+ "pid": 123,+ "port": 4096,+ "caller_context_path": manager._caller_context_path(),+ "active_run_sessions": [],+ "runtime_policy_revision": "previous-policy",+ }+ manager._get_pid_command = lambda pid: "opencode serve --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),+ ):+ base_url = await manager.ensure_running()++ self.assertEqual(base_url, "http://127.0.0.1:4096")+ manager._restart_for_auth_refresh_locked.assert_awaited_once()+ manager._start_server.assert_awaited_once()++ async def test_ensure_running_reconciles_orphaned_adopted_run_before_policy_refresh(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ manager._pid_file = Path(tmp_dir) / "opencode_server.json"+ manager._pid_file.write_text(+ json.dumps(+ {+ "pid": 123,+ "port": 4096,+ "caller_context_path": manager._caller_context_path(),+ "active_run_sessions": ["ses-orphan"],+ "runtime_policy_revision": "previous-policy",+ }+ ),+ encoding="utf-8",+ )+ manager.set_active_poll_session_ids_provider(set)+ 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._get_pid_command = lambda pid: "opencode serve --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),+ ):+ base_url = await manager.ensure_running()++ self.assertEqual(base_url, "http://127.0.0.1:4096")+ manager._restart_for_auth_refresh_locked.assert_awaited_once()+ manager._start_server.assert_awaited_once()+ payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))+ self.assertEqual(payload["active_run_sessions"], [])++ async def test_ensure_running_keeps_adopted_run_with_durable_poll(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ manager.set_active_poll_session_ids_provider(lambda: {"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: { # type: ignore[method-assign]+ "pid": 123,+ "port": 4096,+ "caller_context_path": manager._caller_context_path(),+ "active_run_sessions": ["ses-active"],+ "runtime_policy_revision": "previous-policy",+ }+ manager._get_pid_command = lambda pid: "opencode serve --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.assertRaises(OpenCodeManagedPolicyRefreshPendingError):+ await manager.ensure_running()++ self.assertEqual(manager._active_run_sessions, {"ses-active"})+ manager._restart_for_auth_refresh_locked.assert_not_awaited()+ manager._start_server.assert_not_awaited()++ async def test_ensure_running_keeps_adopted_run_when_poll_reconciliation_fails(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)++ def unavailable_polls() -> set[str]:+ raise OSError("sessions unavailable")++ manager.set_active_poll_session_ids_provider(unavailable_polls)+ 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: { # type: ignore[method-assign]+ "pid": 123,+ "port": 4096,+ "caller_context_path": manager._caller_context_path(),+ "active_run_sessions": ["ses-unknown"],+ "runtime_policy_revision": "previous-policy",+ }+ manager._get_pid_command = lambda pid: "opencode serve --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.assertRaises(OpenCodeManagedPolicyRefreshPendingError):+ await manager.ensure_running()++ self.assertEqual(manager._active_run_sessions, set())+ manager._restart_for_auth_refresh_locked.assert_not_awaited()+ manager._start_server.assert_not_awaited()+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]@@ -499,7 +658,10 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):"ensure_plugin_installed",return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),):- with self.assertRaisesRegex(RuntimeError, "adopted or active server"):+ with self.assertRaisesRegex(+ OpenCodeManagedPolicyRefreshPendingError,+ "adopted or active server",+ ):await manager.ensure_running()manager._restart_for_auth_refresh_locked.assert_not_awaited()@@ -539,6 +701,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):"port": 4096,"caller_context_path": adopted_path,"active_run_sessions": ["ses-active"],+ "runtime_policy_revision": SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION,}manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]manager._caller_context_path = lambda: "/new-avibe-home/runtime/opencode_caller_context.json" # type: ignore[method-assign]@@ -567,12 +730,71 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))self.assertEqual(payload["active_run_sessions"], ["ses-active"])+ self.assertEqual(+ payload["runtime_policy_revision"],+ SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION,+ )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_mark_run_inactive_preserves_active_state_when_pid_write_fails(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ with tempfile.TemporaryDirectory() as tmp_dir:+ manager._pid_file = Path(tmp_dir) / "opencode_server.json"+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]+ manager._write_pid_file(123)+ await manager.mark_run_active("ses-active")++ with patch.object(+ Path,+ "write_text",+ side_effect=OSError("read-only pid file"),+ ):+ with self.assertRaisesRegex(OSError, "read-only pid file"):+ await manager.mark_run_inactive("ses-active")++ self.assertEqual(manager._active_run_sessions, {"ses-active"})+ payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))+ self.assertEqual(payload["active_run_sessions"], ["ses-active"])++ async def test_mark_run_inactive_preserves_other_adopted_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._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]+ manager._write_pid_file(123)+ payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))+ payload["active_run_sessions"] = ["ses-completed", "ses-other-platform"]+ manager._pid_file.write_text(json.dumps(payload), encoding="utf-8")++ await manager.mark_run_inactive("ses-completed")++ self.assertEqual(manager._active_run_sessions, {"ses-other-platform"})+ payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))+ self.assertEqual(payload["active_run_sessions"], ["ses-other-platform"])++ async def test_mark_run_active_preserves_adopted_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._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]+ manager._write_pid_file(123)+ payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))+ payload["active_run_sessions"] = ["ses-other-platform"]+ manager._pid_file.write_text(json.dumps(payload), encoding="utf-8")++ await manager.mark_run_active("ses-new")++ self.assertEqual(manager._active_run_sessions, {"ses-new", "ses-other-platform"})+ payload = json.loads(manager._pid_file.read_text(encoding="utf-8"))+ self.assertEqual(+ payload["active_run_sessions"],+ ["ses-new", "ses-other-platform"],+ )+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()}@@ -586,8 +808,9 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):*,caller_context_path=SERVER_MODULE._USE_CURRENT_CALLER_CONTEXT_PATH,owner_pid=SERVER_MODULE._CURRENT_OWNER_PID,+ runtime_policy_revision=SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION,):- writes.append((pid, caller_context_path, owner_pid))+ writes.append((pid, caller_context_path, owner_pid, runtime_policy_revision))pid_info.clear()pid_info.update({"pid": pid, "port": 4096})if isinstance(caller_context_path, str) and caller_context_path:@@ -597,7 +820,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):await manager._cleanup_orphaned_managed_server()- self.assertEqual(writes, [(222, None, None)])+ self.assertEqual(writes, [(222, None, None, None)])self.assertNotIn("caller_context_path", pid_info)async def test_ensure_running_rejects_unmanaged_healthy_server(self):@@ -663,6 +886,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):"port": 4096,"started_at": 2.0,"caller_context_path": manager._caller_context_path(),+ "runtime_policy_revision": SERVER_MODULE._MANAGED_RUNTIME_POLICY_REVISION,}manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.pyindex b788e6056..eb45a1360 100644--- a/tests/test_reply_enhancer_platform.py+++ b/tests/test_reply_enhancer_platform.py@@ -94,6 +94,18 @@ class _StubAgent(BaseAgent):return None+def _resolved_core_skills(*, manual_only: bool = False) -> list[SimpleNamespace]:+ return [+ SimpleNamespace(+ name=name,+ description=f"{name} workflow",+ directory=Path("/tmp") / name,+ disable_model_invocation=manual_only,+ )+ for name in ("use-show-pages", "use-avibe-vault", "use-avibe-harness")+ ]++class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):def test_prompt_can_exclude_quick_replies(self):with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):@@ -147,67 +159,80 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertIn("file:///Users/test/.codex/generated_images/thread-id/image-file.png", prompt)self.assertIn("Never emit variables, placeholder paths, or sandbox paths like `/mnt/data/...`", prompt)- def test_prompt_includes_vault_guidance(self):- with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):- prompt = build_system_prompt_injection(include_quick_replies=False)+ def test_prompt_routes_vault_work_to_builtin_skill(self):+ with (+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),+ patch("core.managed_skills.resolve_skills", return_value=_resolved_core_skills()),+ ):+ prompt = build_system_prompt_injection(+ include_quick_replies=False,+ skills_cwd=Path("/tmp/project"),+ )self.assertIn("## Vault", prompt)- self.assertIn("prefer Avibe Vault: agents reference secrets by name, tag, or skill tag", prompt)- self.assertIn("Static secret: a regular secret value", prompt)- self.assertIn("Keypair secret: a signing key", prompt)- self.assertIn("Because protected secrets are end-to-end encrypted", prompt)- self.assertNotIn("irreversible operations", prompt)- self.assertIn("never run commands that may print env vars", prompt)- self.assertNotIn("With `vibe vault fetch` and `vibe vault sign`, the agent does not receive", prompt)- self.assertIn("Avibe automatically asks the user to decrypt and authorize access", prompt)- self.assertIn("it does not replay the command for you", prompt)- self.assertIn("run the same `run` / `fetch` command again", prompt)- self.assertIn("Avibe creates a browser signing request and returns immediately", prompt)- self.assertIn("Do not rerun `sign`", prompt)- self.assertIn("follow the callback instruction to read the completed request result", prompt)- self.assertIn("vibe vault request OPENAI_API_KEY", prompt)- self.assertIn("Request that the user add a missing static secret.", prompt)- self.assertIn("ask the user to create a keypair secret in the Vault UI", prompt)- self.assertIn("do not request or store private-key material as a static secret", prompt)+ self.assertIn("load the `use-avibe-vault` Skill", prompt)+ self.assertNotIn("vibe vault request OPENAI_API_KEY", prompt)self.assertNotIn("$<OPENAI_API_KEY>", prompt)- self.assertNotIn("clickable placeholder", prompt)- self.assertIn("vibe vault find --kind static --protection protected", prompt)- self.assertIn("vibe vault find openai --tag prod", prompt)- self.assertIn("vibe vault tags", prompt)- self.assertNotIn("vibe vault discover", prompt)- self.assertIn("vibe vault run --env OPENAI_API_KEY,GITHUB_TOKEN", prompt)- self.assertIn("vibe vault run --tag deploy", prompt)- self.assertIn("vibe vault fetch --auth GITHUB_PAT", prompt)- self.assertIn("vibe vault access PROD_DB_URL", prompt)- self.assertIn("Request approval before a protected `run`", prompt)- self.assertIn("For protected `fetch`, run `vibe vault fetch`", prompt)- self.assertIn("vibe vault sign WALLET_KEY", prompt)- self.assertNotIn("vibe vault await <request_id>", prompt)- self.assertNotIn("vibe vault sign WALLET_KEY --skill", prompt)- self.assertNotIn("vibe vault sign WALLET_KEY --tag", prompt)-- def test_prompt_includes_vault_web_placeholder_only_for_web_chat(self):- web_context = MessageContext(- user_id="U1",- channel_id="C1",- platform="avibe",- platform_specific={"agent_session_id": "sesk8m4q2p7x"},++ skill = (Path(__file__).resolve().parents[1] / "skills" / "use-avibe-vault" / "SKILL.md").read_text()+ self.assertIn("vibe vault request OPENAI_API_KEY", skill)+ self.assertIn("$<OPENAI_API_KEY>", skill)+ self.assertIn("Do not rerun `sign`", skill)+ self.assertIn("the child process receives static secrets as environment variables", skill)++ def test_vault_routing_prompt_is_platform_independent(self):+ contexts = [+ MessageContext(+ user_id="U1",+ channel_id="C1",+ platform=platform,+ platform_specific={"agent_session_id": "sesk8m4q2p7x"},+ )+ for platform in ("avibe", "slack")+ ]++ with (+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),+ patch("core.managed_skills.resolve_skills", return_value=_resolved_core_skills()),+ ):+ prompts = [+ build_system_prompt_injection(+ include_quick_replies=False,+ context=context,+ skills_cwd=Path("/tmp/project"),+ )+ for context in contexts+ ]++ self.assertEqual(+ prompts[0].split("## Vault", 1)[1].split("## Harness", 1)[0],+ prompts[1].split("## Vault", 1)[1].split("## Harness", 1)[0],)- slack_context = MessageContext(+ self.assertNotIn("$<OPENAI_API_KEY>", prompts[0])++ def test_prompt_does_not_route_extracted_skills_when_they_are_unavailable(self):+ context = MessageContext(user_id="U1",channel_id="C1",- platform="slack",+ platform="avibe",platform_specific={"agent_session_id": "sesk8m4q2p7x"},)+ with (+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),+ patch("core.managed_skills.resolve_skills", return_value=[]),+ ):+ prompt = build_system_prompt_injection(+ include_quick_replies=False,+ context=context,+ skills_cwd=Path("/tmp/project"),+ )- with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):- web_prompt = build_system_prompt_injection(include_quick_replies=False, context=web_context)- slack_prompt = build_system_prompt_injection(include_quick_replies=False, context=slack_context)-- self.assertIn("$<OPENAI_API_KEY>", web_prompt)- self.assertIn("clickable placeholder in your reply", web_prompt)- self.assertNotIn("$<OPENAI_API_KEY>", slack_prompt)- self.assertNotIn("clickable placeholder in your reply", slack_prompt)+ self.assertNotIn("## Vault", prompt)+ self.assertNotIn("load the `use-avibe-vault` Skill", prompt)+ self.assertNotIn("load the `use-show-pages` Skill", prompt)+ self.assertNotIn("load the `use-avibe-harness` Skill", prompt)+ self.assertIn("History contract:", prompt)+ self.assertIn("### Agents", prompt)def test_prompt_can_exclude_show_pages(self):context = MessageContext(@@ -217,11 +242,15 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):platform_specific={"agent_session_id": "sesk8m4q2p7x"},)- with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):+ with (+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),+ patch("core.managed_skills.resolve_skills", return_value=_resolved_core_skills()),+ ):prompt = build_system_prompt_injection(include_show_pages=False,include_quick_replies=False,context=context,+ skills_cwd=Path("/tmp/project"),)self.assertNotIn("## Show Pages", prompt)@@ -1747,7 +1776,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(reply.text, "Done.")self.assertEqual([button.text for button in reply.buttons], ["Wiki", "Done"])- def test_prompt_includes_harness_architecture_and_memory_context(self):+ def test_prompt_keeps_harness_routing_and_moves_operational_detail_to_skill(self):context = MessageContext(user_id="U1",channel_id="C1",@@ -1777,293 +1806,107 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):with (patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),- patch("core.show_git.show_git_checkpointing_active", return_value=True),- # The tool-policy paragraphs vary with SDK hook support, so pin it- # rather than let the installed SDK decide what this test asserts.- # Pinned to True on purpose: a Codex prompt must not inherit the- # Claude enforcement claim just because that SDK happens to be- # installed alongside it.patch("core.system_prompt_injection._claude_sdk_hooks_available", return_value=True),+ patch("core.managed_skills.resolve_skills", return_value=_resolved_core_skills()),):prompt = build_system_prompt_injection(include_quick_replies=True,context=context,enabled_agents=enabled_agents,current_agent_backend="codex",+ skills_cwd=Path("/tmp/project"),)self.assertIn("## Show Pages", prompt)- self.assertIn("`vibe show path`", prompt)- self.assertIn("`vibe show status`", prompt)- self.assertIn("`vibe show update --visibility private`", prompt)- self.assertIn("`Accept: text/markdown`", prompt)- self.assertIn("use headings for sections, lists for sequences or groups", prompt)- self.assertIn("`<table>` for genuinely tabular data", prompt)- self.assertIn("`data-agent-hidden`", prompt)- self.assertIn('`agent-note="..."`', prompt)- self.assertIn("History is saved automatically around each turn", prompt)- self.assertIn("`git -C <workspace> status / log / diff / show`", prompt)- self.assertIn("Restore only via `git restore --source=<ref> -- <path>`", prompt)- self.assertIn("Never move HEAD, switch branches, rewrite history, or run gc", prompt)- self.assertIn("Never add remotes, push, or publish the workspace anywhere", prompt)- self.assertNotIn("`vibe show path --session-id sesk8m4q2p7x`", prompt)- self.assertIn("Make the page work reasonably on mobile", prompt)- self.assertIn("managed React/Vite apps", prompt)- self.assertIn("Tailwind CSS v4 utility classes are built in", prompt)- self.assertIn("restyle the built-in `@/components/ui/*` components", prompt)- self.assertIn('must keep `@import "tailwindcss";` and `@import "@avibe/show-ui/theme.css";` at the top', prompt)- self.assertIn("Theme with standard shadcn variables", prompt)- self.assertIn("values are complete CSS colors usable directly through `var(...)`", prompt)- self.assertIn('under `.dark` or `[data-theme="dark"]` for dark mode', prompt)- self.assertIn("import `cn` from `@/lib/utils`", prompt)- self.assertNotIn("theme through the `@avibe/show-ui/theme` CSS variables", prompt)- self.assertNotIn("Ready to visualize", prompt)- self.assertIn("@/components/ui/progress", prompt)- self.assertNotIn("Excalidraw-style static SVG/PNG diagrams", prompt)- self.assertNotIn("Avibe Cloud is not connected", prompt)+ self.assertIn("load the `use-show-pages` Skill", prompt)+ self.assertNotIn("`vibe show status`", prompt)self.assertIn("## Harness", prompt)- self.assertNotIn("## Scheduled tasks, watches, and hooks", prompt)- self.assertIn("Avibe Harness turns user intent into durable Agent work", prompt)- self.assertIn("context, owner, trigger, session continuity, delivery target, and observable progress", prompt)- self.assertIn("Avibe Harness is the first-choice automation layer", prompt)- self.assertIn("route through `vibe agent`, `vibe task`, and `vibe watch` before backend-native subagents", prompt)- self.assertIn("native workflow tools, backend-native skills", prompt)- self.assertIn("Do not default to backend-native automation just because the backend exposes it", prompt)- self.assertIn("Use backend-native config, skills, subagents, or workflow tools only when the user explicitly asks for backend-native behavior", prompt)- # This is a Codex session, and only the Claude session handler installs- # the tool-layer gate, so the prompt must claim no enforcement here even- # though the Claude SDK is importable (pinned above).+ self.assertIn("load the `use-avibe-harness` Skill", prompt)self.assertIn("Backend-native background work is not gated in this runtime", prompt)- self.assertNotIn("blocked at the tool layer", prompt)- self.assertNotIn("only partly blocked", prompt)self.assertIn("Route that work through the Harness instead", prompt)- self.assertIn("Never detach with `nohup` or a trailing `&` for work whose result you need", prompt)- self.assertIn("what outcome is the user trying to secure", prompt)- self.assertIn("If the answer is an operating loop, build a Harness instead of only doing the visible step", prompt)- self.assertIn("### Mental model", prompt)- self.assertIn("| Agent | Reusable role: backend, model, prompt, description, enabled state | Work needs a stable specialist identity |", prompt)- self.assertIn("| Session | Continuing context for one Agent work lineage | Work should continue or fork context |", prompt)- self.assertIn("Relationship: Scope routes work; Agent defines who acts; Session holds continuity", prompt)- self.assertIn("Current session id: `sesk8m4q2p7x`", prompt)- self.assertEqual(prompt.count("Current session id: `sesk8m4q2p7x`"), 2)- self.assertNotIn("Current Agent backend", prompt)- self.assertNotIn("copying `sesk8m4q2p7x` into the command", prompt)- self.assertNotIn("generic reply destination", prompt)- self.assertNotIn("delivery address", prompt)- self.assertNotIn("Legacy session key:", prompt)- self.assertNotIn("--session-key", prompt)- self.assertNotIn("Channel-level session key:", prompt)- self.assertIn("### Inspecting Harness state", prompt)- self.assertIn("Use `vibe harness status` first for active Runs", prompt)- self.assertIn(- "Use `vibe data query` for deeper guarded read-only SQL before changing a Harness",- prompt,- )- self.assertIn("select name from sqlite_master where type='table' order by name", prompt)- self.assertIn("schema discovery, current session lookup, existing task/watch inspection, Agent run history", prompt)- self.assertIn("### Choosing the right Harness shape", prompt)- self.assertIn("| Independent Agent delegation | `vibe agent run --agent <agent-name>` |", prompt)- self.assertIn("| Continue a pointed Session | `vibe agent run --session-id ...` |", prompt)- self.assertIn(- "| Inspect queued Workbench Session input | `vibe session queue list <session-id>` |",- prompt,- )- self.assertIn(- "| Remove one queued Workbench Session input | `vibe session queue remove <session-id> <message-id>` |",- prompt,- )- self.assertIn(- "| Promote an existing queued Session head now | `vibe session send-now <session-id>` |",- prompt,- )- self.assertIn("| Branch from current Session context | `vibe agent run --fork-self ...` |", prompt)- self.assertIn("Tasks created from an Avibe Agent shell continue this conversation by default", prompt)- self.assertIn("`vibe task add` creates a time-triggered saved Agent message", prompt)- self.assertIn("Watches created from an Avibe Agent shell follow up in this conversation by default", 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("exit `0` only for one NEW reportable event", prompt)- self.assertIn("default `75`) keeps either a once or forever Watch waiting", prompt)- self.assertIn("it retires a once Watch and re-arms a forever Watch", prompt)- self.assertIn("must therefore return an allowed retry code, not `64`", prompt)- self.assertIn("waits five seconds after a follow-up settles before re-arming", prompt)- self.assertIn("six successful events within 60 seconds", prompt)- delegate_guidance = (- "Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work to another Agent. "- "By default this creates a background Session in the caller's scope and returns immediately; when the run "- "completes, the final result is sent back to this conversation. Background Sessions stay out of the session "- "list and never deliver outward, but remain visible in the Agents run graph, where the user can open their "- "full chat history or promote them at any time. Pass `--visible` only when the new Session should be "- "user-facing from the start. Pass `--sync` only when the current process must wait for the result. Pass "- "`--no-callback` only when you intentionally want no automatic follow-up and will inspect the run later; "- "pass `--callback-session-id <id>` only to route the final result elsewhere. Add `--scope-id <scopes.id>` "- "only when placing the new Session in a specific existing scope."- )- self.assertIn(delegate_guidance, prompt)- self.assertNotIn("Outside an Agent shell, a caller-less run", prompt)- self.assertIn("Pass `--sync` only when the current process must wait for the result", prompt)- self.assertIn(- "That existing-Session send is a P1 delivery by default",- prompt,- )- self.assertIn(- "an explicit user request is one signal, not a prerequisite",- prompt,- )- self.assertIn(- "Both commands work for Workbench and IM Sessions",- prompt,- )- self.assertIn(- "vibe agent run --session-id <id> --send-now --message ...",- prompt,- )- self.assertIn(- "vibe session send-now <id>",- prompt,- )- self.assertIn(- "vibe session queue list <id>",- prompt,- )- self.assertIn(- "vibe session queue remove <id> <message-id>",- prompt,- )- self.assertIn(- "Always list first and use the returned stable message id",- prompt,- )- self.assertIn(- "explicitly selects that same content-bearing P1 behavior",- prompt,- )- self.assertIn(- "it does not promote an older queued message",- prompt,- )- self.assertIn(- "this content-free P1 promotes the exact existing FIFO head",- prompt,- )- self.assertIn(- "that head steers the same logical/native Turn",- prompt,- )- self.assertIn(- "if the Session is idle, it starts as a new Turn",- prompt,- )- self.assertNotIn(- "Both forms require a Web/Workbench Session, interrupt through the shared Stop path",- prompt,- )- self.assertNotIn("content-P0 admission", prompt)- self.assertIn(- "never falls back to Stop",- prompt,- )- self.assertNotIn("Add `--same-scope` to require the caller/source scope", prompt)- self.assertIn("Use `vibe agent run --fork-self --message ...` when work should branch from this current Session", prompt)- self.assertIn("Forks keep the source Session backend, scope, and cwd by default", prompt)- self.assertIn("It does not change that Session's cwd, scope, Agent, model, or reasoning settings", prompt)- self.assertNotIn("`--prefix` is legacy-compatible", prompt)- self.assertNotIn("`--post-to` is a delivery override", prompt)- self.assertIn("Prefer `--same-scope` or `--scope-id <scopes.id>` for new Session placement", prompt)- self.assertNotIn("--deliver-key", prompt)- self.assertIn("Manage existing work with `vibe task <list|show|pause|resume|run|remove>`", prompt)- self.assertIn("`vibe watch <list|show|pause|resume|remove>`", prompt)- self.assertIn("`vibe runs <list|show|cancel>`", prompt)- self.assertIn("The CLI exposes more options than this prompt lists", prompt)- self.assertIn("`vibe <command> <subcommand> --help`", prompt)- self.assertIn("### Agents", prompt)+ self.assertNotIn("### Mental model", prompt)+ self.assertNotIn("Watch waiter contract", prompt)+ self.assertEqual(prompt.count("Current session id: `sesk8m4q2p7x`"), 1)self.assertIn("| Agent Name | Backend | Agent Description |", prompt)self.assertIn("| codex | codex | Codex compatibility Agent for existing sessions |", prompt)self.assertIn(r"| release-auditor | claude | Review releases \| verify follow-up risk |", prompt)self.assertIn("| review-bot | codex | Name needs prompt-safe normalization |", prompt)- self.assertIn("generated from currently enabled Agents at prompt-injection time", prompt)- self.assertIn("The `Agent Name` column is command-safe", prompt)- self.assertNotIn("CLI Token", prompt)- self.assertIn("Use the `Agent Name` value exactly as listed in shell commands", prompt)- self.assertIn("`--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing", prompt)- self.assertIn("Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate background Session", prompt)- self.assertIn(- "Use `vibe session update --visible|--hidden` (`--visibility foreground|background`)",- prompt,- )- self.assertIn("`--fork-self` creates a new Agent Session from this current Session's native backend context", prompt)- self.assertIn("`--fork-session <id>` creates a new Agent Session from that explicit source Session's native backend context", prompt)- self.assertIn("vibe agent run --agent <agent-name> --message ...", prompt)- self.assertIn("vibe agent run --agent <agent-name> --session-id ... --message ...", prompt)- self.assertIn("Async callbacks return to this conversation by default", prompt)- self.assertNotIn("Reuse an existing Session only with Agents whose `Backend` matches", prompt)- self.assertIn("With `--fork-self` or `--fork-session`, pass `--agent`, `--model`, or `--reasoning-effort` only as forked-Session overrides", prompt)- self.assertIn("`--sync` changes waiting behavior, not session identity", prompt)- self.assertIn("synchronous runs wait for the result and are still recorded in `vibe runs`", prompt)- self.assertNotIn("--create-session-per-run", prompt)- self.assertIn("Create or update Agents only when it captures a reusable role", prompt)+ self.assertLess(prompt.index("| codex |"), prompt.index("| release-auditor |"))+ self.assertLess(prompt.index("| release-auditor |"), prompt.index("| review-bot |"))self.assertIn("## Memory and Project Context", prompt)- self.assertIn("A shared user context and preferences file is available at ", prompt)self.assertIn("/tmp/user_preferences.md", prompt)- self.assertIn("Use the right memory surface", prompt)- self.assertIn("project lessons, conventions, architecture, workflows, and pointers go to the nearest relevant `AGENTS.md`", prompt)- self.assertIn("`AGENTS.md` is an index, not a log", prompt)- self.assertIn("update by consolidating and abstracting instead of merely appending", prompt)- self.assertIn("Use the current platform `slack`", prompt)- self.assertIn("`slack/<user_id>`", prompt)- self.assertNotIn("slack/U1", prompt)- self.assertIn("Only record durable, factual, reusable information there.", prompt)- self.assertIn("Keep entries short, deduplicated, and free of secrets unless the user explicitly asks.", prompt)- self.assertIn("use `vibe data query` to recover Sessions and Messages by keyword, time, scope, Agent, or run history", prompt)- def test_show_pages_prompt_reports_history_unavailable_without_git(self):+ skill = (Path(__file__).resolve().parents[1] / "skills" / "use-avibe-harness" / "SKILL.md").read_text()+ self.assertIn("Avibe Harness turns user intent into durable Agent work", skill)+ self.assertIn("### Mental model", skill)+ self.assertIn("Watch waiter contract", skill)+ self.assertIn("vibe harness status", skill)+ self.assertIn("vibe watch add", skill)++ def test_prompt_is_byte_stable_when_agent_input_order_changes(self):context = MessageContext(user_id="U1",channel_id="C1",platform="slack",platform_specific={"agent_session_id": "sesk8m4q2p7x"},)+ enabled_agents = [+ SimpleNamespace(name="zeta", normalized_name="zeta", backend="codex", description="Last"),+ SimpleNamespace(name="Alpha", normalized_name="alpha", backend="claude", description="First"),+ SimpleNamespace(name="beta", normalized_name="beta", backend="opencode", description="Middle"),+ ]- with (- patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),- patch("core.show_git.show_git_checkpointing_active", return_value=False),- ):- prompt = build_system_prompt_injection(include_quick_replies=True, context=context)+ with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):+ forward = build_system_prompt_injection(+ include_quick_replies=False,+ context=context,+ enabled_agents=enabled_agents,+ current_agent_backend="codex",+ )+ reverse = build_system_prompt_injection(+ include_quick_replies=False,+ context=context,+ enabled_agents=reversed(enabled_agents),+ current_agent_backend="codex",+ )- self.assertIn("Automatic Show Page history is unavailable", prompt)- self.assertNotIn("History is saved automatically around each turn", prompt)- self.assertNotIn("git restore --source", prompt)+ self.assertEqual(forward, reverse)+ self.assertLess(forward.index("| alpha |"), forward.index("| beta |"))+ self.assertLess(forward.index("| beta |"), forward.index("| zeta |"))- def test_show_pages_prompt_rechecks_mid_session_ownership_flip(self):- session_id = "sesk8m4q2p7x"+ def test_show_page_runtime_state_selects_one_history_contract(self):context = MessageContext(user_id="U1",channel_id="C1",platform="slack",- platform_specific={"agent_session_id": session_id},+ platform_specific={"agent_session_id": "sesk8m4q2p7x"},)- workspace = paths.get_show_page_dir(session_id)- workspace.mkdir(parents=True)- with (- patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),- patch("core.show_git.show_git_checkpointing_active", return_value=True),- ):- managed_prompt = build_system_prompt_injection(include_quick_replies=True, context=context)- (workspace / ".git").mkdir()- self_managed_prompt = build_system_prompt_injection(include_quick_replies=True, context=context)- (workspace / ".git").rmdir()- managed_again_prompt = build_system_prompt_injection(include_quick_replies=True, context=context)-- self.assertIn("History is saved automatically around each turn", managed_prompt)- self.assertNotIn("shadow history continues automatically", managed_prompt)- self.assertIn("Avibe's shadow history continues automatically", self_managed_prompt)- self.assertIn("addresses the **user's repo**, not Avibe history", self_managed_prompt)- self.assertIn("Only if the user explicitly asks to recover from Avibe history", self_managed_prompt)- self.assertNotIn("Read freely: `git -C <workspace>", self_managed_prompt)- self.assertNotIn("Restore only via `git restore", self_managed_prompt)- self.assertIn("History is saved automatically around each turn", managed_again_prompt)- self.assertNotIn("shadow history continues automatically", managed_again_prompt)+ with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):+ with patch("core.show_git.show_git_checkpointing_active", return_value=False):+ unavailable = build_system_prompt_injection(include_quick_replies=True, context=context)+ with (+ patch("core.show_git.show_git_checkpointing_active", return_value=True),+ patch("core.show_git._workspace_is_self_managed", return_value=False),+ ):+ managed = build_system_prompt_injection(include_quick_replies=True, context=context)+ with (+ patch("core.show_git.show_git_checkpointing_active", return_value=True),+ patch("core.show_git._workspace_is_self_managed", return_value=True),+ ):+ self_managed = build_system_prompt_injection(include_quick_replies=True, context=context)++ self.assertIn("History is saved automatically around each turn", managed)+ self.assertNotIn("Avibe's shadow history continues automatically", managed)+ self.assertIn("Avibe's shadow history continues automatically", self_managed)+ self.assertNotIn("History is saved automatically around each turn", self_managed)+ self.assertIn("Automatic Show Page history is unavailable", unavailable)+ self.assertNotIn("History is saved automatically around each turn", unavailable)+ skill = (Path(__file__).resolve().parents[1] / "skills" / "use-show-pages" / "SKILL.md").read_text()+ self.assertNotIn("History is saved automatically around each turn", skill)+ self.assertNotIn("Avibe's shadow history continues automatically in the background", skill)+ self.assertNotIn("Automatic Show Page history is unavailable", skill)+ self.assertIn("one active history", skill)def test_prompt_does_not_render_empty_agents_as_invokable_table_row(self):context = MessageContext(@@ -2092,7 +1935,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertNotIn("| (none) |", missing_store_prompt)self.assertNotIn("| (none) |", empty_store_prompt)- def test_show_pages_prompt_mentions_avibe_cloud_when_not_connected(self):+ def test_show_page_detail_lives_in_skill_and_cloud_state_stays_in_prompt(self):context = MessageContext(user_id="U1",channel_id="C1",@@ -2100,19 +1943,39 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):platform_specific={"agent_session_id": "sesk8m4q2p7x"},)- with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):- prompt = build_system_prompt_injection(+ with (+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),+ patch("core.managed_skills.resolve_skills", return_value=_resolved_core_skills()),+ ):+ disconnected = build_system_prompt_injection(include_quick_replies=False,avibe_cloud_connected=False,context=context,+ skills_cwd=Path("/tmp/project"),+ )+ connected = build_system_prompt_injection(+ include_quick_replies=False,+ avibe_cloud_connected=True,+ context=context,+ skills_cwd=Path("/tmp/project"),)- self.assertIn("## Show Pages", prompt)- self.assertIn("⚠️ Avibe Cloud is not connected", prompt)- self.assertIn("register an avibe.bot account", prompt)- self.assertIn("`vibe remote pair`", prompt)-- def test_show_pages_prompt_allows_literal_typescript_braces(self):+ self.assertNotEqual(disconnected, connected)+ self.assertIn("load the `use-show-pages` Skill", disconnected)+ self.assertNotIn("`vibe show path`", disconnected)+ self.assertIn("Avibe Cloud is not connected", disconnected)+ self.assertNotIn("Avibe Cloud is not connected", connected)++ skill = (Path(__file__).resolve().parents[1] / "skills" / "use-show-pages" / "SKILL.md").read_text()+ self.assertIn("`vibe show path`", skill)+ self.assertIn("`Accept: text/markdown`", skill)+ self.assertIn("export async function GET(request)", skill)+ self.assertIn("[show-annotation]", skill)+ self.assertIn("vibe show mark", skill)+ self.assertIn("They include Show Page motion for changed text", skill)+ self.assertNotIn("Avibe Cloud is not connected", skill)++ def test_disabled_show_pages_are_not_advertised_through_the_skill_catalog(self):context = MessageContext(user_id="U1",channel_id="C1",@@ -2120,36 +1983,87 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):platform_specific={"agent_session_id": "sesk8m4q2p7x"},)- with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):+ skills = [+ SimpleNamespace(+ name="use-show-pages",+ description="Show Page workflow",+ directory=Path("/tmp/show-pages"),+ disable_model_invocation=False,+ ),+ SimpleNamespace(+ name="use-avibe-vault",+ description="Vault workflow",+ directory=Path("/tmp/vault"),+ disable_model_invocation=False,+ ),+ ]+ with (+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),+ patch("core.managed_skills.resolve_skills", return_value=skills),+ ):prompt = build_system_prompt_injection(+ include_show_pages=False,include_quick_replies=False,context=context,+ skills_cwd=Path("/tmp/project"),)- self.assertIn("`vibe show path`", prompt)- self.assertNotIn("`vibe show path --session-id sesk8m4q2p7x`", prompt)- self.assertIn("export async function GET(request) { return Response.json({ ok: true }) }", prompt)+ self.assertNotIn("load the `use-show-pages` Skill", prompt)+ self.assertNotIn("- use-show-pages:", prompt)+ self.assertIn("- use-avibe-vault:", prompt)- def test_show_pages_prompt_includes_annotation_capability_guidance(self):+ def test_manual_only_core_skills_are_not_advertised_or_routed(self):context = MessageContext(user_id="U1",channel_id="C1",- platform="slack",+ platform="avibe",platform_specific={"agent_session_id": "sesk8m4q2p7x"},)+ with (+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),+ patch(+ "core.managed_skills.resolve_skills",+ return_value=_resolved_core_skills(manual_only=True),+ ),+ ):+ prompt = build_system_prompt_injection(+ include_quick_replies=False,+ context=context,+ skills_cwd=Path("/tmp/project"),+ )- with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):+ self.assertNotIn("load the `use-show-pages` Skill", prompt)+ self.assertNotIn("load the `use-avibe-vault` Skill", prompt)+ self.assertNotIn("load the `use-avibe-harness` Skill", prompt)+ self.assertNotIn("- use-show-pages:", prompt)+ self.assertNotIn("- use-avibe-vault:", prompt)+ self.assertNotIn("- use-avibe-harness:", prompt)+ self.assertIn("History contract:", prompt)+ self.assertIn("### Agents", prompt)++ def test_missing_skill_binding_does_not_advertise_routes(self):+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="avibe",+ platform_specific={"agent_session_id": "sesk8m4q2p7x"},+ )+ with patch.object(+ paths,+ "get_user_preferences_path",+ return_value=Path("/tmp/user_preferences.md"),+ ):prompt = build_system_prompt_injection(include_quick_replies=False,context=context,+ skills_cwd=None,)- guidance = """### Show Page annotations & reverse marks-- Users can annotate your Show Page; each annotation arrives as a chat message tagged [show-annotation] with its event id. Some messages end with a ready-to-run reply command — whether to reply on the page or respond by editing the page content is your call, per scenario.-- After reworking a page area you may leave a short callout: `vibe show mark <selector-or-anchor> --message '...'` (same target replaces), or an `agent-note="..."` attribute on elements you author. Marks retire once read — leave at most 1-2 per turn.-- Inspect/withdraw: `vibe show marks` / `vibe show unmark <id|target> ...`; toggle the user's annotation mode: `vibe show annotate --on|--off [--mode smart|screenshot]`."""- self.assertIn(guidance, prompt)- self.assertNotIn("prefer replying on the page", prompt)+ self.assertNotIn("load the `use-show-pages` Skill", prompt)+ self.assertNotIn("load the `use-avibe-vault` Skill", prompt)+ self.assertNotIn("load the `use-avibe-harness` Skill", prompt)+ self.assertIn("History contract:", prompt)+ self.assertIn("### Agents", prompt)def test_prompt_uses_fallback_platform_for_unannotated_context(self):context = MessageContext(diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.pyindex 7a14e950d..f1c9dbed3 100644--- a/tests/test_sqlite_sessions_store.py+++ b/tests/test_sqlite_sessions_store.py@@ -301,6 +301,66 @@ def test_save_state_does_not_relabel_existing_anchor_row_to_different_backend(tmservice.close()+def test_runtime_marker_is_bound_to_exact_active_native_session(tmp_path: Path) -> None:+ service = SQLiteSessionsService(tmp_path / "vibe.sqlite")+ try:+ with service.engine.begin() as conn:+ scope_id = resolve_scope_from_legacy_key(+ conn,+ "avibe::project::proj_1",+ now="2026-09-04T00:00:00Z",+ )+ assert scope_id is not None+ session_id = create_agent_session_row(+ conn,+ scope_id=scope_id,+ agent_backend="codex",+ agent_variant="codex",+ session_anchor="ses-runtime",+ native_session_id="thread-1",+ workdir="/tmp",+ metadata={"keep": "unchanged"},+ require_workdir=False,+ )++ marker = {"thread_id": "thread-1", "sha256": "abc123"}+ assert service.set_agent_session_runtime_marker(+ session_id,+ backend="codex",+ native_session_id="thread-1",+ key="codex_fallback_prompt",+ value=marker,+ )+ assert (+ service.get_agent_session_runtime_marker(+ session_id,+ backend="codex",+ native_session_id="thread-1",+ key="codex_fallback_prompt",+ )+ == marker+ )+ row = service.get_agent_session_by_id(session_id)+ assert row is not None+ assert json.loads(row["metadata_json"])["keep"] == "unchanged"++ assert not service.set_agent_session_runtime_marker(+ session_id,+ backend="codex",+ native_session_id="thread-replaced",+ key="codex_fallback_prompt",+ value={"thread_id": "thread-replaced", "sha256": "new"},+ )+ assert service.get_agent_session_runtime_marker(+ session_id,+ backend="codex",+ native_session_id="thread-1",+ key="codex_fallback_prompt",+ ) == marker+ finally:+ service.close()++def test_save_state_skips_import_when_archived_row_owns_anchor(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"service = SQLiteSessionsService(db_path)diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 8166d7068..d059198f0 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -401,6 +401,9 @@"claudeCredentialTypeInvalid": "Choose either API key or auth token for the Claude Code credential.","claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Switch back to the original working directory to continue that session, or start a new Claude Code session from the current directory.","sessionGeneric": "An error occurred: {error}",+ "codexPromptRefreshUnavailable": "Codex could not confirm that it can safely refresh Avibe's instructions for this existing session. Check or update Codex, then retry this turn.",+ "opencodePolicyRefreshPending": "OpenCode is still finishing an existing turn and cannot restart with Avibe's current Skill policy yet. Retry after that turn finishes.",+ "opencodeRuntimeConfigInvalid": "OpenCode could not start because OPENCODE_CONFIG_CONTENT is invalid. Fix the runtime configuration and retry.","resultAttachmentUploadFailed": "Failed to upload attachment. Want me to split the result into multiple messages?","resultDeliveryFailed": "⚠️ Message delivery failed. The content may be too long or incompatible. Ask me to resend it.","fileAttachmentUploadFailedWithLink": "⚠️ I could not deliver {filename} as a WeChat file. You can download it from Avibe after signing in if prompted:\n{url}",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex e881054b1..4babaab1e 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -401,6 +401,9 @@"claudeCredentialTypeInvalid": "Claude Code 凭据类型只能选择 API Key 或 Auth Token。","claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请切回原来的工作目录继续该会话,或在当前目录开始一个新的 Claude Code 会话。","sessionGeneric": "发生错误:{error}",+ "codexPromptRefreshUnavailable": "Codex 无法确认能否安全刷新此现有会话的 Avibe 指令。请检查或升级 Codex 后重试本回合。",+ "opencodePolicyRefreshPending": "OpenCode 仍在完成已有回合,暂时无法按 Avibe 当前的 Skill 策略重启。请在该回合结束后重试。",+ "opencodeRuntimeConfigInvalid": "OpenCode 无法启动,因为 OPENCODE_CONFIG_CONTENT 无效。请修正运行时配置后重试。","resultAttachmentUploadFailed": "附件上传失败。要我改成拆分成多条消息发送吗?","resultDeliveryFailed": "⚠️ 消息投递失败,内容可能过长或格式不兼容。你可以让我重新发送一次。","fileAttachmentUploadFailedWithLink": "⚠️ {filename} 没能作为微信文件直接发送。你可以通过 Avibe 下载;如提示登录,请先登录:\n{url}",