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(cli): unify Agent-facing CLI grammar (#2973)
Call Whitec7f55dc62a28
diff --git a/AGENTS.md b/AGENTS.mdindex 86eb0a75f..460fdbef4 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -242,7 +242,11 @@ there rather than expanding this index.- default to English for comments, docs, logs, and user-facing copy- use non-English text only when required for localization/i18n-- backend user-facing strings must go through `vibe/i18n/`+- backend user-facing strings for IM, Web, and notifications must go through `vibe/i18n/`+- the `vibe` CLI is Agent-facing: its help, errors, hints, and notices are+ English, written in code, and never read the configured UI language. A message+ the CLI shares with a localized surface (such as the Doctor report the Web+ panel shows) keeps its catalog key, and the CLI renders its English entry- frontend user-facing strings must go through `ui/src/i18n/en.json` and `ui/src/i18n/zh.json`- never hardcode user-visible display text in handlers, platform adapters, or React componentsdiff --git a/core/managed_skills.py b/core/managed_skills.pyindex 0b513b786..408ab5fb5 100644--- a/core/managed_skills.py+++ b/core/managed_skills.py@@ -16,7 +16,7 @@ from typing import Any, Sequenceimport yamlfrom config import paths-from core.prompt_registry import RenderedPromptBlock, join_prompt_blocks, render_prompt, render_prompt_block+from core.prompt_registry import RenderedPromptBlock, join_prompt_blocks, render_prompt_blocktry:import tomllib@@ -1046,21 +1046,6 @@ def catalog_page(skills: Sequence[ManagedSkill], page: int) -> tuple[Sequence[Mareturn pages[page - 1], page + 1 if page < len(pages) else None-def render_skill_list(- skills: Sequence[ManagedSkill],- *,- page: int = 1,- more_notice: str | None = None,-) -> str:- entries, next_page = catalog_page(skills, page)- lines = _skill_list_rows(entries)- if next_page is not None:- lines.append(- more_notice or render_prompt("skills-more-notice", next_page=next_page)- )- return "\n".join(lines)--def _skill_list_rows(entries: Sequence[ManagedSkill]) -> list[str]:return [f"- {skill.name}: {skill.description}" for skill in entries]diff --git a/core/prompts/harness-agents.md b/core/prompts/harness-agents.mdindex 6b2dcc8dd..2e55d0c6b 100644--- a/core/prompts/harness-agents.md+++ b/core/prompts/harness-agents.md@@ -12,7 +12,7 @@ Rules:- `--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.-- `--model` and `--reasoning-effort` set the model of the new Session a run creates (a blank new Session, `--create-session`, or a fork), and that Session keeps it; they are not valid with `--session-id`. With `--fork-self` or `--fork-session`, `--agent`, `--model`, and `--reasoning-effort` override the forked Session only when the requested Agent backend matches the source Session backend.+- `--model` and `--reasoning-effort` set the model of the new Session a run creates (a blank new Session or a fork), and that Session keeps it; they are not valid with `--session-id`. With `--fork-self` or `--fork-session`, `--agent`, `--model`, and `--reasoning-effort` override the forked Session 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.diff --git a/core/prompts/skills.md b/core/prompts/skills.mdindex 119b0356d..9fde7cc38 100644--- a/core/prompts/skills.md+++ b/core/prompts/skills.md@@ -1,6 +1,6 @@## SkillsSkills provide specialized instructions and workflows for specific tasks.-Consider whether any available Skills would help in the current situation. Load those you choose with `vibe skill load -- <name>`; reuse any already loaded in this conversation.+Consider whether any available Skills would help in the current situation. Load those you choose with `vibe skill load -- <name> [<name> ...]`; reuse any already loaded in this conversation.If the user requests a Skill by exact name, use that Skill.For non-explicit requests, only load Skill names listed here or returned by `vibe skill list`; do not guess names.diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex e96c5d13f..bbcc90164 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -11445,7 +11445,7 @@ class ScheduledTaskService:if deliver_key:delivery_target = parse_session_key(deliver_key)if delivery_target.platform != session_target.platform:- raise ValueError("--deliver-key must stay on the same platform as the session target")+ raise ValueError("the stored delivery target must stay on the same platform as the session target")return delivery_targetif post_to == "channel":return ParsedSessionKey(@@ -11456,7 +11456,7 @@ class ScheduledTaskService:)if post_to == "thread":if not session_target.thread_id:- raise ValueError("--post-to thread requires a thread-bound session target or an explicit --deliver-key")+ raise ValueError("stored thread delivery requires a thread-bound session target or an explicit delivery target")return session_targetreturn session_targetdiff --git a/docs/CLI.md b/docs/CLI.mdindex b84bfbd68..c578863c2 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -15,15 +15,66 @@ vibe stop # Stop all services## Commands+The `vibe` CLI is mostly called by Agents, so every command follows one grammar+and one output rule.++### Grammar++- **Naming a Session.** `--session-id <id>` is the only way to name a Session.+ A command that acts on one Session (`vibe session get`, `update`, `send-now`,+ `queue list`, `queue remove`, the `vibe show` commands) defaults to the caller+ Session from `AVIBE_SESSION_ID`, as the [Session-owned lists](#session-owned-lists)+ do. Outside an Avibe Agent shell there is no default, and the command fails+ with `missing_caller_session`.+- **Naming anything else.** Agent names, run, task, watch, and Vault secret+ ids, and a queued message id are positional:+ `vibe session queue remove <message-id> --session-id <id>`.+- **Message text.** `--message` or `--message-file`, on every command that sends+ or stores a message.+- **Visibility.** `--visible` makes a new or forked Session from `vibe agent run`+ user-facing (new delegated Sessions are background by default).+ `vibe session update` takes `--visible` or `--hidden`.+- **One spelling.** There are no aliases, hidden compatibility flags, or+ deprecated commands; a removed spelling fails as an unknown argument.++### Output++- **Agent-facing commands** (`agent`, `runs`, `harness`, `session`, `task`,+ `watch`, `show`, `vault`, `data query`, `data skill-usage`, `skill list`, and+ `status`) print one JSON object on stdout:+ `{"schema_version": 1, "ok": true, "kind": "<kind>", ...fields}`. They accept+ `--json`, which changes nothing.+- **Failures** of those commands, and every argument error, print the same+ envelope on stderr with `"ok": false`, `"kind": "error"`, a stable `code`, the+ `error` text, and when useful a `hint`, `help_command`, and `details`. The exit+ status is nonzero.+- **Content commands** print the content itself: `vibe skill load` prints Skill+ text, `vibe computer` prints its compact observation format (`--json` returns+ the raw driver payload), `vibe vault run` passes through the output of the+ command it runs, and `vibe debug prompt export` prints its export document.+- **Operator commands** for a person at a terminal print text. `version`,+ `check-update`, `doctor`, `runtime`, `remote` subcommands, `screenshot`, and+ `data retention` print the JSON envelope with `--json`. The service lifecycle+ commands `start`, `stop`, `restart`, `upgrade`, and the guided `vibe remote`+ setup only print progress text and take no `--json`.+- **Language.** CLI help, errors, hints, and notices are English, whatever the+ configured UI language. IM, the Web UI, and notifications follow the+ configured language; the Web doctor panel shows the same diagnostics as+ `vibe doctor` in that language.+### Bounded list outputAgent-facing collection commands share one pagination contract: `vibe agent list`,-`vibe agent models`, `vibe runs list`, `vibe session list`, Vault list/find/tags,-Show Page list/marks, `vibe data query`, `vibe task list`, and `vibe watch list`.-They return 20 rows by default, accept `--page` and `--limit`, cap a page at 100,-and never provide an unpaginated `--all` bypass. Follow-`pagination.next_command` for the next page and use the corresponding `show` or-`get` command for full record detail.+`vibe agent models`, `vibe runs list`, `vibe session list`,+`vibe session queue list`, Vault list/find/tags, Show Page list/marks,+`vibe data query`, `vibe task list`, and `vibe watch list`. They return 20 rows+by default and accept `--page` and `--limit`. A page holds at most 100 rows: a+larger `--limit` reads 100, and `pagination.limit` reports the limit used. A+`--limit` or `--page` below 1 is an `invalid_pagination` error. There is no+unpaginated `--all` bypass. Follow `pagination.next_command` for the next page+and use the corresponding `show` or `get` command for full record detail.+`vibe skill list` pages the same Skill catalog the system prompt shows, so it+takes `--page` only.List rows carry only what is needed to decide the next step and omit null,empty, and zero-valued fields, so an absent field means unset. `vibe task show`,@@ -144,6 +195,9 @@ vibe status**Output:**```json{+ "schema_version": 1,+ "ok": true,+ "kind": "service_status","state": "running","running": true,"pid": 12345@@ -163,15 +217,17 @@ their native Skill catalogs on Avibe-dispatched Turns.```bashvibe skill list [--page N]-vibe skill load -- <name>+vibe skill load -- <name> [<name> ...]```-`list` prints the currently available names and descriptions in stable order,-25 per page. Page 1 is also included in the Agent's system prompt; use the-next-page command shown in the output when more Skills are available. `load`-prints only the selected Skill body inside a `skill_content` element. Its-`directory` attribute is an absolute path so the Agent can read references and-run scripts stored beside `SKILL.md`.+`list` returns the currently available names and descriptions in stable order+as `skills`, with a `pagination` object. Page 1 is also included in the Agent's+system prompt; follow `pagination.next_command` when more Skills are available.+`load` prints each named Skill body inside its own `skill_content` element, in+the order given. Its `directory` attribute is an absolute path so the Agent can+read references and run scripts stored beside `SKILL.md`. An unknown name still+prints the Skills that loaded, then fails with a `skill_not_found` error that+lists the `missing` and `loaded` names.Avibe discovers existing Skills without moving them:@@ -338,6 +394,7 @@ Run diagnostic checks on your configuration.```bashvibe doctor+vibe doctor --json```Run safe first-phase repairs explicitly:@@ -403,7 +460,7 @@ vibe remote startvibe remote stop```-Use `--json` on these subcommands for machine-readable output.+Use `--json` on these subcommands for the JSON envelope.### `vibe screenshot`@@ -417,29 +474,34 @@ vibe screenshot --json**Behavior:**- Saves to `~/.vibe_remote/screenshots/` by default-- Prints the saved file path, or a JSON payload with `--json`+- Prints the saved file path, or the JSON envelope with `--json`- Stays at the CLI layer only; it does not add IM commands, bot buttons, or agent prompt injection### `vibe session`-List, inspect, and rename Agent sessions. `list` and `get` are read-only; `update`-changes the title only. Archived sessions are soft-deleted and never surfaced.+List, inspect, update, and drive Agent sessions. `list` and `get` are read-only;+`update` changes the title, visibility, or scope. Archived sessions are+soft-deleted and never surfaced.```bashvibe session list # active sessions, 20 per page by default, newest activity firstvibe session list --type slack # filter by platform (avibe = Web/Workbench)-vibe session list --page 2 --limit 50 # request page 2 with 50 rows (maximum 100)-vibe session get sesk8m4q2p7x # full detail for one session-vibe session get # inside an Avibe Agent shell, show the caller Session-vibe session update sesk8m4q2p7x --title 'Release review' # pass "" to clear the title+vibe session list --page 2 --limit 50 # request page 2 with 50 rows (at most 100)+vibe session get # inside an Avibe Agent shell, the caller Session+vibe session get --session-id sesk8m4q2p7x # full detail for another Sessionvibe session update --title 'Release review' # inside an Avibe Agent shell+vibe session update --session-id sesk8m4q2p7x --title '' # clear the title+vibe session update --session-id sesk8m4q2p7x --hidden # background-only; --visible promotes it+vibe session queue list --session-id sesk8m4q2p7x # queued messages in FIFO order+vibe session queue remove msg_queued123 --session-id sesk8m4q2p7x+vibe session send-now --session-id sesk8m4q2p7x # promote the exact queue head```-`--type` accepts a platform id: `avibe` (Web/Workbench), `slack`, `discord`,-`telegram`, `lark`, `wechat`. For richer filtering — by agent, time range, message-content, or cross-table joins — `list` and `get` point you to `vibe data query`.-When `get` or `update` runs inside an Avibe-injected Agent shell, the session id-may be omitted and defaults to the caller Session from `AVIBE_SESSION_ID`.+Every command except `list` acts on one Session: `--session-id`, or the caller+Session inside an Avibe Agent shell (see [Grammar](#grammar)). `--type` accepts+a platform id: `avibe` (Web/Workbench), `slack`, `discord`, `telegram`, `lark`,+`wechat`. For richer filtering — by agent, time range, message content, or+cross-table joins — use `vibe data query`.### `vibe runs`@@ -487,8 +549,9 @@ Use `vibe task add --help` and `vibe task update --help` for the full command suWhen `vibe task add` runs inside an Avibe-injected Agent shell, `--session-id`may be omitted. Avibe defaults the task target to the caller Session from`AVIBE_SESSION_ID`; the printed definition's `session_id` shows the resolved-target. Explicit `--session-id`, session creation flags, and delivery flags-still win.+target. Explicit `--session-id` and session creation flags still win. To target+an IM channel or thread that has no Session yet, create one with+`--create-session` (or `--create-session-per-run`) and `--scope-id`.A pure command task (`--on-failure none`, the default) skips that caller-sessiondefault and takes no session, scope, or agent flags. Successful runs are silent;@@ -518,9 +581,6 @@ and every other command records the directory you ran `vibe task add` from. Fora message task `--cwd` still places the Session it creates, and is still refusedfor one that already exists.-`--session-key` remains accepted for older scripts, but new tasks should use-the Agent Session ID shown in the active Avibe prompt.-### `vibe agent run`Run an Agent directly. Runs are async by default and do not store a scheduled@@ -530,35 +590,36 @@ task definition. Use `--sync` only when the terminal should wait for completion.vibe agent run --no-callback --agent release-reviewer --message 'Review the latest deployment result.'vibe agent run --sync --agent release-reviewer --message 'Review the latest deployment result and print it here.'vibe agent run --no-callback --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'-vibe agent run --session-id sesk8m4q2p7x --send-now --message 'Apply this correction in the current turn.'+vibe agent run --session-id sesk8m4q2p7x --queue --message 'Do this after the current turn.'vibe agent run --no-callback --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'vibe agent run --session-id sesworker123 --callback-session-id sescaller456 --message 'Run the delegated investigation.'-vibe agent run --no-callback --create-session --scope-id slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'+vibe agent run --no-callback --scope-id slack::channel::C999 --visible --agent release-reviewer --message 'Post the deployment summary.'vibe agent run --close-after --no-callback --agent release-reviewer --message 'Run a disposable batch review.'```+Without `--session-id` or a fork flag, the run creates a new background Session+for `--agent`; `--same-scope` or `--scope-id` places it, and `--visible` makes it+user-facing.+With an existing `--session-id`, the default admission is P1: Avibe steers thenew Run into an active native Turn, starts it immediately when idle, or moves thesame Delivery to the durable P3 queue after a definitive refusal/not-active-receipt. It does not interrupt the active Turn.--`--send-now` is valid only with an existing `--session-id` and explicitly selects-the normal content-bearing P1 behavior: the new message steers an active native-Turn, starts immediately when idle, and falls back to P3 after a definitive-refusal. It never promotes an older queued message. `vibe session send-now` is-the content-free P1 operation: it promotes the exact existing FIFO head without-adding a message. A stale head is refused rather than replaced by the next queued-item, and neither command calls Stop.+receipt. It does not interrupt the active Turn, and it never promotes an older+queued message. `--queue` puts the new Run in the P3 queue behind the active+Turn instead. `vibe session send-now` is the content-free P1 operation: it+promotes the exact existing FIFO head without adding a message. A stale head is+refused rather than replaced by the next queued item, and neither command calls+Stop.Use `--fork-session <session-id>` when a new Agent Session should branch froman existing Session's native backend context instead of starting blank. The newSession keeps the source backend. `--agent`, `--model`, and`--reasoning-effort` can override the forked Session only when the Agent backendstays the same; a cross-backend fork is rejected. Do not combine-`--fork-session` with `--session-id` or `--create-session`.+`--fork-session` with `--session-id`.`--model` and `--reasoning-effort` set the model of any new Session the run-creates (a blank new Session, `--create-session`, or a fork), and the Session+creates (a blank new Session or a fork), and the Sessionkeeps it for its later turns. They are refused with `--session-id`; an existingSession's model is changed in the Web UI's Session model picker. The pair thenew Session will run on (each override over the default it would otherwise@@ -583,9 +644,6 @@ from ordinary delivery: if the target run also posts to its IM scope, the callerSession still receives the result. Process messages such as system notes, toolcalls, and intermediate assistant updates are not included.-`vibe hook send` is kept only as a deprecated compatibility entrypoint. New-automation should use `vibe agent run`.-Use `--close-after` for a new or forked Session when the Agent runtime should bereleased after the Run settles while the Session, transcript, and Run record stayavailable. It is rejected for `--session-id`, which targets an existing Session@@ -659,8 +717,8 @@ including `--timeout` (per-cycle timeout in seconds), `--lifetime-timeout`(total wall-clock limit), `--forever`, `--retry-exit-code`, `--retry-delay`,`--name`, and session creation flags. Watches share `--session-id`,`--create-session`, `--create-session-per-run`, `--same-scope`, and `--scope-id`-semantics with `vibe task`; direct `vibe agent run` uses `--create-session`-for one-shot session creation. `vibe watch remove` hides the watch from management+semantics with `vibe task`; `vibe agent run` creates a new Session whenever it+names no `--session-id` and no fork. `vibe watch remove` hides the watch from managementviews while preserving existing run history in SQLite. Prefer `vibe watch`over ad-hoc `nohup` jobs when theuser wants a managed background task with a guaranteed follow-up message.@@ -675,6 +733,7 @@ Show the installed version.```bashvibe version+vibe version --json```### `vibe check-update`@@ -683,6 +742,7 @@ Check if a newer version is available.```bashvibe check-update+vibe check-update --json```### `vibe upgrade`diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex 666898735..d5554a535 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -14,14 +14,55 @@ vibe stop # 停止所有服务## 命令详解+`vibe` CLI 主要由 Agent 调用,因此所有命令遵循同一套语法和同一条输出规则。++### 语法++- **指定 Session。** 只用 `--session-id <id>` 指定 Session。作用于单个 Session 的+ 命令(`vibe session get`、`update`、`send-now`、`queue list`、`queue remove`+ 以及各个 `vibe show` 命令)和 [Session 归属的列表](#session-归属的列表) 一样,+ 默认使用 `AVIBE_SESSION_ID` 对应的调用方 Session。在 Avibe Agent shell 之外+ 没有默认值,命令以 `missing_caller_session` 失败。+- **指定其他对象。** Agent 名称,run、task、watch、Vault secret 的 id,以及排队+ 消息的 id 都是位置参数:`vibe session queue remove <message-id> --session-id <id>`。+- **消息文本。** 所有发送或保存消息的命令都使用 `--message` 或 `--message-file`。+- **可见性。** `--visible` 让 `vibe agent run` 新建或 fork 的 Session 面向用户+ (新建的委派 Session 默认在后台)。`vibe session update` 使用 `--visible` 或+ `--hidden`。+- **只有一种写法。** 没有别名、隐藏的兼容参数或已弃用的命令;已移除的写法会作为+ 未知参数报错。++### 输出++- **面向 Agent 的命令**(`agent`、`runs`、`harness`、`session`、`task`、`watch`、+ `show`、`vault`、`data query`、`data skill-usage`、`skill list` 和 `status`)+ 在 stdout 输出一个 JSON 对象:+ `{"schema_version": 1, "ok": true, "kind": "<kind>", ...字段}`。它们接受+ `--json`,但不改变任何行为。+- **失败**:这些命令的失败以及所有参数错误,都会在 stderr 输出同样的信封,其中+ `"ok": false`、`"kind": "error"`,并带有稳定的 `code`、`error` 文本,必要时还有+ `hint`、`help_command` 和 `details`。退出码非零。+- **内容型命令**直接输出内容:`vibe skill load` 输出 Skill 正文,`vibe computer`+ 输出精简的观察格式(`--json` 返回驱动的原始负载),`vibe vault run` 原样转出所运行+ 命令的输出,`vibe debug prompt export` 输出它的导出文档。+- **运维命令**面向终端前的用户,输出文本。`version`、`check-update`、`doctor`、+ `runtime`、`remote` 子命令、`screenshot` 和 `data retention` 加 `--json` 时输出+ JSON 信封。服务生命周期命令 `start`、`stop`、`restart`、`upgrade` 以及引导式+ `vibe remote` 配置只输出进度文本,不接受 `--json`。+- **语言。** CLI 的帮助、错误、提示和通知始终是英文,与配置的界面语言无关。IM、+ Web UI 和通知遵循配置的语言;Web 诊断面板用该语言显示与 `vibe doctor` 相同的诊断。+### 有界列表输出面向 Agent 的集合命令共用同一套分页契约:`vibe agent list`、`vibe agent models`、-`vibe runs list`、`vibe session list`、Vault 的 list/find/tags、Show Page 的-list/marks、`vibe data query`、`vibe task list` 和 `vibe watch list`。默认返回-20 条,支持 `--page` 和 `--limit`,单页最多 100 条,且不提供无分页的 `--all`-绕过。使用 `pagination.next_command` 继续翻页;完整记录详情通过对应的 `show`-或 `get` 命令获取。+`vibe runs list`、`vibe session list`、`vibe session queue list`、Vault 的+list/find/tags、Show Page 的 list/marks、`vibe data query`、`vibe task list` 和+`vibe watch list`。默认返回 20 条,支持 `--page` 和 `--limit`。单页最多 100 条:+更大的 `--limit` 按 100 读取,`pagination.limit` 报告实际使用的上限。小于 1 的+`--limit` 或 `--page` 返回 `invalid_pagination` 错误。不提供无分页的 `--all` 绕过。+使用 `pagination.next_command` 继续翻页;完整记录详情通过对应的 `show` 或 `get`+命令获取。`vibe skill list` 与 system prompt 中的 Skill 目录分页一致,因此只接受+`--page`。列表行只携带决定下一步所需的字段,并省略 null、空值和零值字段,因此缺失的字段即表示未设置。`vibe task show`、`vibe watch show`、`vibe runs show`、`vibe session get`@@ -119,6 +160,9 @@ vibe status**输出示例:**```json{+ "schema_version": 1,+ "ok": true,+ "kind": "service_status","state": "running","running": true,"pid": 12345@@ -136,13 +180,16 @@ Avibe 为 Claude、Codex 和 OpenCode 提供统一的托管 Skill Catalog,并```bashvibe skill list [--page N]-vibe skill load -- <name>+vibe skill load -- <name> [<name> ...]```-`list` 按稳定顺序输出当前可用的名称和描述,每页最多 25 个。第 1 页也会注入-Agent 的 system prompt;如有更多 Skill,按输出中的命令查看下一页。`load` 只在-`skill_content` 标签中输出所选 Skill 的正文。标签的 `directory` 属性是绝对路径,-Agent 可以据此读取 `SKILL.md` 同目录下的 reference 或运行 script。+`list` 按稳定顺序以 `skills` 返回当前可用的名称和描述,并附带 `pagination` 对象。+第 1 页也会注入 Agent 的 system prompt;如有更多 Skill,按+`pagination.next_command` 查看下一页。`load` 按给定顺序,把每个 Skill 的正文+分别放在各自的 `skill_content` 标签中输出。标签的 `directory` 属性是绝对路径,+Agent 可以据此读取 `SKILL.md` 同目录下的 reference 或运行 script。遇到未知名称时,+已加载的 Skill 仍会输出,随后以 `skill_not_found` 错误失败,并列出 `missing` 和+`loaded` 的名称。Avibe 会直接发现现有 Skill,无需迁移:@@ -246,6 +293,7 @@ vibe data skill-usage --clear --yes --json```bashvibe doctor+vibe doctor --json```显式运行安全的一期修复:@@ -309,7 +357,7 @@ vibe remote startvibe remote stop```-这些子命令都支持 `--json` 输出,便于脚本调用。+这些子命令加 `--json` 时输出 JSON 信封。### `vibe screenshot`@@ -323,26 +371,29 @@ vibe screenshot --json**行为:**- 默认保存到 `~/.vibe_remote/screenshots/`-- 默认输出保存路径;加 `--json` 时输出机器可读的 JSON+- 默认输出保存路径;加 `--json` 时输出 JSON 信封- 只作为 CLI 层能力存在;不新增 IM 命令、bot 按钮,也不注入 Agent prompt### `vibe session`-列出、查看并重命名 Agent 会话。`list` 与 `get` 是只读视图;`update` 只改标题。已归档会话视为软删除,任何情况下都不会被列出。+列出、查看、更新并操作 Agent 会话。`list` 与 `get` 是只读视图;`update` 修改标题、可见性或 scope。已归档会话视为软删除,任何情况下都不会被列出。```bashvibe session list # 未归档会话,默认每页 20 条,按最近活跃倒序vibe session list --type slack # 按平台过滤(avibe = Web/Workbench)vibe session list --page 2 --limit 50 # 第 2 页,每页 50 条(最多 100)-vibe session get sesk8m4q2p7x # 单个会话的完整明细vibe session get # 在 Avibe Agent shell 内查看调用方 Session-vibe session update sesk8m4q2p7x --title 'Release review' # 传 "" 可清空标题+vibe session get --session-id sesk8m4q2p7x # 其他会话的完整明细vibe session update --title 'Release review' # 在 Avibe Agent shell 内+vibe session update --session-id sesk8m4q2p7x --title '' # 清空标题+vibe session update --session-id sesk8m4q2p7x --hidden # 只在后台;--visible 恢复显示+vibe session queue list --session-id sesk8m4q2p7x # 按 FIFO 顺序列出排队消息+vibe session queue remove msg_queued123 --session-id sesk8m4q2p7x+vibe session send-now --session-id sesk8m4q2p7x # 提升精确的队头```-`--type` 取平台 id:`avibe`(Web/Workbench)、`slack`、`discord`、`telegram`、`lark`、`wechat`。需要更高级的筛选——按 Agent、时间段、消息内容或跨表联查——`list` 与 `get` 的返回都会引导你使用 `vibe data query`。-当 `get` 或 `update` 运行在 Avibe 已注入 caller context 的 Agent shell 内时,-可以省略 session id,并默认使用 `AVIBE_SESSION_ID` 对应的调用方 Session。+除 `list` 外,每个命令都作用于一个 Session:`--session-id`,或在 Avibe Agent shell+内默认的调用方 Session(见 [语法](#语法))。`--type` 取平台 id:`avibe`(Web/Workbench)、`slack`、`discord`、`telegram`、`lark`、`wechat`。需要更高级的筛选——按 Agent、时间段、消息内容或跨表联查——请使用 `vibe data query`。### `vibe runs`@@ -389,7 +440,9 @@ vibe task remove <task-id>当 `vibe task add` 运行在 Avibe 已注入 caller context 的 Agent shell 内时,可以省略 `--session-id`。Avibe 会把任务目标默认到 `AVIBE_SESSION_ID`对应的调用方 Session;输出的 definition 中的 `session_id` 就是解析后的目标。-显式 `--session-id`、session creation 参数和 delivery 参数仍然优先。+显式 `--session-id` 和 session creation 参数仍然优先。要投递到还没有 Session 的+IM 频道或话题,请用 `--create-session`(或 `--create-session-per-run`)配合+`--scope-id` 创建。纯命令任务(`--on-failure none`,即默认值)不会套用上面这条调用方 Session 默认,也不接受 session、scope 或 agent 相关参数。执行成功时完全静默;执行失败会记录一条@@ -415,9 +468,6 @@ Session:`vibe task add` 时所在的目录。对 message 任务,`--cwd` 仍然用于放置它创建的Session,且在目标 Session 已存在时仍然会被拒绝。-`--session-key` 仍兼容旧脚本,但新任务应使用当前 Avibe prompt-里展示的 Agent Session ID。-### `vibe agent run`直接运行一个 Agent。Run 默认异步,并且不会创建持久化任务定义。只有终端需要等待完成时才使用@@ -427,27 +477,30 @@ Session,且在目标 Session 已存在时仍然会被拒绝。vibe agent run --no-callback --agent release-reviewer --message 'Review the latest deployment result.'vibe agent run --sync --agent release-reviewer --message 'Review the latest deployment result and print it here.'vibe agent run --no-callback --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'-vibe agent run --session-id sesk8m4q2p7x --send-now --message 'Apply this correction in the current turn.'+vibe agent run --session-id sesk8m4q2p7x --queue --message 'Do this after the current turn.'vibe agent run --no-callback --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'vibe agent run --session-id sesworker123 --callback-session-id sescaller456 --message 'Run the delegated investigation.'-vibe agent run --no-callback --create-session --scope-id slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'+vibe agent run --no-callback --scope-id slack::channel::C999 --visible --agent release-reviewer --message 'Post the deployment summary.'vibe agent run --close-after --no-callback --agent release-reviewer --message 'Run a disposable batch review.'```-`--send-now` 只能和现有 `--session-id` 一起使用,它显式选择普通的带内容 P1-语义:新消息会 steering 进活动 native Turn,Session 空闲时立即启动;只有明确-拒绝后才回退到 P3。它不会提升更早的排队消息。`vibe session send-now` 是无内容-P1 操作,只提升现有的精确 FIFO 队头,不新增消息。过期队头会被拒绝,而不会改为-提升下一条;两个命令都不会调用 Stop。+没有 `--session-id` 也没有 fork 参数时,这次运行会为 `--agent` 新建一个后台+Session;`--same-scope` 或 `--scope-id` 决定它的位置,`--visible` 让它面向用户。++指定现有 `--session-id` 时,默认是 P1:新消息会 steering 进活动 native Turn,+Session 空闲时立即启动;只有明确拒绝后才回退到 P3。它不会打断活动 Turn,也不会+提升更早的排队消息。`--queue` 则把新 Run 放进活动 Turn 之后的 P3 队列。+`vibe session send-now` 是无内容 P1 操作,只提升现有的精确 FIFO 队头,不新增消息。+过期队头会被拒绝,而不会改为提升下一条;两个命令都不会调用 Stop。当一个新 Agent Session 需要从现有 Session 的 native backend 上下文分叉,而不是空白开始时,使用 `--fork-session <session-id>`。新 Session 会保持源 Session 的 backend。只有 backend 不变时,才可以通过 `--agent`、`--model`、`--reasoning-effort`覆盖 fork 后 Session 的 Agent、模型或推理强度;跨 backend fork 会被拒绝。-不要把 `--fork-session` 和 `--session-id` 或 `--create-session` 混用。+不要把 `--fork-session` 和 `--session-id` 混用。`--model` 和 `--reasoning-effort` 可以为这次运行创建的任何新 Session(空白新-Session、`--create-session` 或 fork)设置模型,该 Session 之后的轮次会沿用它。+Session 或 fork)设置模型,该 Session 之后的轮次会沿用它。它们不能与 `--session-id` 一起使用;已有 Session 的模型在 Web UI 的 Session 模型选择器中修改。新 Session 实际运行的组合(覆盖值加上它原本沿用的默认值)会按 Agent的模型目录检查:Vibey 的 Model Hub 菜单不提供的模型或推理强度,或菜单无法加载时,@@ -467,9 +520,6 @@ Session、`--create-session` 或 fork)设置模型,该 Session 之后的轮即使目标 run 已经把结果发到了自己的 IM scope,调用方 Session 仍然会收到结果并触发一次跟进 Agent 消息。system、tool call、assistant 中间过程消息不会包含在 callback 里。-`vibe hook send` 仅作为 deprecated 兼容入口保留。新的自动化入口应使用-`vibe agent run`。-对于新建或 fork 的 Session,如果希望 Run 结束后释放 Agent runtime,同时保留Session、transcript 和 Run 记录,可以使用 `--close-after`。它不能和`--session-id` 一起使用,因为现有 Session 自己管理 runtime 生命周期。@@ -534,9 +584,9 @@ definition。对已删除的 definition 执行 `pause`、`resume`、`update`、`waiter 命令放在 `--` 后面;或者通过 `--shell` 传入一整段 shell 字符串。完整参数请看 `vibe watch add --help`,包括 `--timeout`、`--lifetime-timeout`、`--forever`、`--retry-exit-code`、`--retry-delay`、`--name` 和 session creation 参数。-watch 与 `vibe task`、`vibe agent run` 共用 `--session-id`、`--create-session`、-`--same-scope` 和 `--scope-id` 语义;`--create-session-per-run`-只属于 `vibe task` 和 `vibe watch` 这类 stored definitions。需要可管理、可暂停、可查看的+watch 与 `vibe task` 共用 `--session-id`、`--create-session`、+`--create-session-per-run`、`--same-scope` 和 `--scope-id` 语义;`vibe agent run`+在没有 `--session-id` 也没有 fork 时总会新建 Session。需要可管理、可暂停、可查看的后台等待任务时,优先使用 `vibe watch`,不要随手起 `nohup`。`--timeout` 默认是 21600 秒;显式传入 `--timeout 0` 会关闭单次 cycle 的超时限制,任何正数值都会原样持久化。waiter 以 `--retry-exit-code` 中的退出码退出@@ -548,6 +598,7 @@ watch 与 `vibe task`、`vibe agent run` 共用 `--session-id`、`--create-sessi```bashvibe version+vibe version --json```### `vibe check-update`@@ -556,6 +607,7 @@ vibe version```bashvibe check-update+vibe check-update --json```### `vibe upgrade`diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex 49117abea..3208c02e6 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -523,13 +523,22 @@ These are important user-facing controls, but they are not text commands:The `vibe` executable controls the local service and async automation features.-All Agent-facing collection commands use `--page` / `--limit`, default to 20-compact rows, and cap each page at 100. They never expose an unpaginated `--all`-mode. Continue with `pagination.next_command`; inspect one record with its-`show` or `get` command. List rows omit null, empty, and zero-valued fields;+All Agent-facing collection commands use `--page` / `--limit` and default to 20+compact rows. A page holds at most 100 rows; a larger `--limit` reads 100 and+`pagination.limit` reports the limit used. They never expose an unpaginated+`--all` mode. Continue with `pagination.next_command`; inspect one record with+its `show` or `get` command. List rows omit null, empty, and zero-valued fields;`--brief` on `vibe task show`, `vibe watch show`, `vibe runs show`,`vibe session get`, and `vibe agent show` prints exactly the list row.+Every command follows one grammar: `--session-id <id>` is the only way to name a+Session, and single-Session commands default to the caller Session inside an+Avibe Agent shell. Agent-facing commands print the JSON envelope+(`schema_version`, `ok`, `kind`, fields) and accept `--json` as a no-op; operator+commands print text, and most of them print the envelope with `--json`. CLI text+is English. There are no command or flag aliases. See+[CLI Reference](CLI.md#commands) for the full grammar and output rule.+## 5.1 Top-level CLI commands| Command | Purpose |@@ -538,7 +547,7 @@ mode. Continue with `pagination.next_command`; inspect one record with its| `vibe start` | Start the service and Web UI if needed; reuse already-running processes; `--no-open-browser` suppresses the browser launch || `vibe stop` | Stop the service and UI; also terminates OpenCode server || `vibe restart` | Stop then start again |-| `vibe status` | Print runtime status JSON |+| `vibe status` | Print runtime status as the JSON envelope || `vibe doctor` | Run diagnostics; `vibe doctor repair` applies explicit safe repairs || `vibe remote` | Guided Avibe Cloud remote Web UI setup || `vibe screenshot` | Capture a local desktop screenshot |@@ -620,7 +629,7 @@ Recommended usage:vibe status```-- prints runtime status JSON+- prints runtime status as the JSON envelope (`kind: "service_status"`)- includes `generation_downgrade` when the running service is older than the last activated install, naming both versions and the launcher that selects the newer one### `vibe doctor`@@ -692,7 +701,7 @@ vibe screenshot --json- captures the local desktop as a PNG file- saves to `~/.vibe_remote/screenshots/` by default- prints the saved file path by default-- prints a machine-readable payload with `--json`+- prints the JSON envelope with `--json`- stays at the host CLI layer; it does not expose in-chat commands, bot buttons, or agent prompt injection### `vibe computer`@@ -772,13 +781,11 @@ vibe upgrade| `vibe task add` | Create a task || `vibe task update` | Update a task || `vibe task list` | List tasks |-| `vibe task ls` | Hidden alias of `list` || `vibe task show <task_id>` | Show one task || `vibe task pause <task_id>` | Pause a task || `vibe task resume <task_id>` | Resume a task || `vibe task run <task_id>` | Run immediately || `vibe task remove <task_id>` | Delete a task |-| `vibe task rm <task_id>` | Hidden alias of `remove` |### `vibe task add`@@ -946,17 +953,19 @@ point back to this command.### `vibe agent run````bash-vibe agent run (--session-id <session_id> | --create-session | --fork-session <session_id>)? (--message <text> | --message-file <file>) [options]+vibe agent run (--session-id <session_id> | --fork-session <session_id> | --fork-self)? (--message <text> | --message-file <file>) [options]```Important options:- `--agent`- `--session-id`+- `--queue`- `--fork-session`-- `--create-session`+- `--fork-self`- `--same-scope`- `--scope-id`+- `--visible`- `--model`- `--reasoning-effort`- `--close-after`@@ -964,13 +973,13 @@ Important options:- `--message`- `--message-file`-If neither `--session-id` nor a creation policy is provided, the run uses a-private no-delivery session and is best suited for sub-agent style calls.+Without `--session-id` or a fork, the run creates a new Session for `--agent`.+It is background by default, which suits sub-agent style calls; `--visible`+makes it user-facing, and `--same-scope` or `--scope-id` places it.Runs are asynchronous by default: the command queues the run, prints one `run`object with its `id` and `session_id`, and uses the callback policy to deliverthe final result later. Use `--sync` only when the terminal should wait for completion.-`--async` is still accepted for older scripts but is no longer required.`--close-after` applies to a new or forked Session. It releases that Agentruntime after the Run settles while keeping the Session, transcript, and Run@@ -978,22 +987,22 @@ record. It cannot target an existing `--session-id`.With an existing `--session-id`, the default is P1: steer the new Run into anactive native Turn, start it when idle, or move the same Delivery to P3 after a-definitive refusal/not-active receipt. `--queue` selects P3 without attempting a-steer. For an existing Session, `--send-now` explicitly selects the same-content-bearing P1 behavior; it targets the new message and never promotes older-queued work. `vibe session send-now` is the content-free P1 operation that-promotes the exact existing FIFO head without adding a message.+definitive refusal/not-active receipt; it targets the new message and never+promotes older queued work. `--queue` selects P3 without attempting a steer.+`vibe session send-now --session-id <id>` is the content-free P1 operation that+promotes the exact existing FIFO head without adding a message. Once the+Controller consumes the request, `vibe runs show <run-id>` shows the persisted+`metadata.delivery_outcome`.`--fork-session <session_id>` creates a new Agent Session by forking the sourceSession's native backend context. It is for alternate investigations ordelegated work that should keep the source context without mutating the sourceSession. Forks keep the same backend as the source; `--agent`, `--model`, and`--reasoning-effort` may override the forked Session only when the backend does-not change. Do not combine `--fork-session` with `--session-id` or-`--create-session`.+not change. Do not combine `--fork-session` with `--session-id`.`--model` and `--reasoning-effort` set the model of any new Session the run-creates (a blank new Session, `--create-session`, or a fork); the Session keeps+creates (a blank new Session or a fork); the Session keepsit. They are refused with `--session-id` (`model_override_with_existing_session`).The pair the new Session will run on (each override over the default it wouldotherwise keep) is checked: a Vibey model or effort its Model Hub menu does notdiff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.mdindex 11a079949..b5bfaf4b2 100644--- a/docs/COMMANDS_ZH.md+++ b/docs/COMMANDS_ZH.md@@ -501,11 +501,18 @@ bind vr-a3x9k2`vibe` 可执行文件负责管理本地服务与异步自动化能力。-所有面向 Agent 的集合命令都使用 `--page` / `--limit`,默认返回 20 条紧凑记录,-单页最多 100 条,并且不提供无分页的 `--all` 模式。按-`pagination.next_command` 继续翻页;单条完整详情通过对应的 `show` 或 `get` 命令获取。-列表行省略 null、空值和零值字段;`vibe task show`、`vibe watch show`、`vibe runs show`、-`vibe session get` 和 `vibe agent show` 加上 `--brief` 时只输出对应的列表行。+所有面向 Agent 的集合命令都使用 `--page` / `--limit`,默认返回 20 条紧凑记录。+单页最多 100 条;更大的 `--limit` 按 100 读取,`pagination.limit` 报告实际使用的+上限。不提供无分页的 `--all` 模式。按 `pagination.next_command` 继续翻页;单条完整+详情通过对应的 `show` 或 `get` 命令获取。列表行省略 null、空值和零值字段;+`vibe task show`、`vibe watch show`、`vibe runs show`、`vibe session get` 和+`vibe agent show` 加上 `--brief` 时只输出对应的列表行。++所有命令遵循同一套语法:只用 `--session-id <id>` 指定 Session,作用于单个 Session+的命令在 Avibe Agent shell 内默认使用调用方 Session。面向 Agent 的命令输出 JSON+信封(`schema_version`、`ok`、`kind` 和字段),接受 `--json` 但不改变行为;运维+命令输出文本,其中大多数加 `--json` 时输出该信封。CLI 文本始终是英文。命令和参数+都没有别名。完整的语法与输出规则见 [CLI 参考手册](CLI_ZH.md#命令详解)。## 5.1 顶层 CLI 命令@@ -515,7 +522,7 @@ bind vr-a3x9k2| `vibe start` | 按需启动服务与 Web UI;已运行时复用现有进程;`--no-open-browser` 可禁止自动打开浏览器 || `vibe stop` | 停止服务与 UI,同时终止 OpenCode server || `vibe restart` | 停止后重新启动 |-| `vibe status` | 输出运行状态 JSON |+| `vibe status` | 以 JSON 信封输出运行状态 || `vibe doctor` | 运行诊断;`vibe doctor repair` 显式执行安全修复 || `vibe remote` | 引导式配置 Avibe Cloud 远程 Web UI || `vibe screenshot` | 截取本机桌面截图 |@@ -596,7 +603,7 @@ vibe restart --delay-seconds 60vibe status```-- 输出运行状态 JSON+- 以 JSON 信封输出运行状态(`kind: "service_status"`)- 如果正在运行的服务比最近一次激活的安装更旧,会包含 `generation_downgrade`,写明两个版本以及选中较新安装的启动器### `vibe doctor`@@ -668,7 +675,7 @@ vibe screenshot --json- 截取本机桌面并保存为 PNG 文件- 默认保存到 `~/.vibe_remote/screenshots/`- 默认输出保存路径-- 加 `--json` 时输出机器可读的 JSON+- 加 `--json` 时输出 JSON 信封- 只停留在宿主机 CLI 层;不新增聊天命令、bot 按钮,也不注入 Agent prompt### `vibe version`@@ -709,13 +716,11 @@ vibe upgrade| `vibe task add` | 创建任务 || `vibe task update` | 更新任务 || `vibe task list` | 列出任务 |-| `vibe task ls` | `list` 的隐藏别名 || `vibe task show <task_id>` | 查看单个任务 || `vibe task pause <task_id>` | 暂停任务 || `vibe task resume <task_id>` | 恢复任务 || `vibe task run <task_id>` | 立即运行一次 || `vibe task remove <task_id>` | 删除任务 |-| `vibe task rm <task_id>` | `remove` 的隐藏别名 |### `vibe task add`@@ -732,7 +737,6 @@ vibe task add (--cron <表达式> | --at <时间戳>) (--shell <命令> | -- <ar- `--name`- `--session-id`-- `--send-now`- `--create-session`- `--create-session-per-run`- `--agent`@@ -876,17 +880,19 @@ vibe agent models --backend opencode --provider deepseek### `vibe agent run````bash-vibe agent run (--session-id <session_id> | --create-session | --fork-session <session_id>)? (--message <文本> | --message-file <文件>) [options]+vibe agent run (--session-id <session_id> | --fork-session <session_id> | --fork-self)? (--message <文本> | --message-file <文件>) [options]```重要参数:- `--agent`- `--session-id`+- `--queue`- `--fork-session`-- `--create-session`+- `--fork-self`- `--same-scope`- `--scope-id`+- `--visible`- `--model`- `--reasoning-effort`- `--close-after`@@ -894,32 +900,33 @@ vibe agent run (--session-id <session_id> | --create-session | --fork-session <s- `--message`- `--message-file`-如果不传 `--session-id` 或创建策略,run 会使用 private-no-delivery session,更适合 sub-agent 调用。+不传 `--session-id` 也不 fork 时,run 会为 `--agent` 新建一个 Session。它默认在+后台运行,适合 sub-agent 调用;`--visible` 让它面向用户,`--same-scope` 或+`--scope-id` 决定它的位置。Run 默认异步:命令会队列化 run,立即输出一个带 `id` 和 `session_id` 的 `run`对象,并按 callback 策略稍后投递最终结果。只有终端需要等待完成时才使用-`--sync`。`--async` 仍兼容旧脚本,但不再需要显式传入。+`--sync`。`--close-after` 适用于新建或 fork 的 Session。Run 结束后它会释放该 Agentruntime,同时保留 Session、transcript 和 Run 记录;不能和现有的`--session-id` 一起使用。对于现有 `--session-id`,默认投递是 P1:新消息会 steering 进活动 native Turn,-Session 空闲时立即启动;明确拒绝后,同一个 Delivery 才回退到 P3。`--queue` 会-直接选择 P3。`--send-now` 显式选择相同的带内容 P1 语义,只针对这条新消息,-不会提升更早的排队工作。`vibe session send-now` 是无内容 P1 操作,只提升现有的-精确 FIFO 队头,不新增消息。命令响应包含 `delivery_intent`,Controller 消费请求后,-`vibe runs show <run-id>` 会显示持久化的 `metadata.delivery_outcome`。+Session 空闲时立即启动;明确拒绝后,同一个 Delivery 才回退到 P3。它只针对这条新消息,+不会提升更早的排队工作。`--queue` 会直接选择 P3。+`vibe session send-now --session-id <id>` 是无内容 P1 操作,只提升现有的精确 FIFO+队头,不新增消息。Controller 消费请求后,`vibe runs show <run-id>` 会显示持久化的+`metadata.delivery_outcome`。`--fork-session <session_id>` 会基于源 Session 的 native backend 上下文创建一个新的Agent Session,适合在保留上下文的同时做分支调查或委派工作,而不修改源 Session。fork 会保持源 Session 的 backend;只有 backend 不变时,`--agent`、`--model`和 `--reasoning-effort` 才能覆盖 fork 后 Session 的 Agent、模型或推理强度。-不要把 `--fork-session` 和 `--session-id` 或 `--create-session` 混用。+不要把 `--fork-session` 和 `--session-id` 混用。`--model` 和 `--reasoning-effort` 可以为这次运行创建的任何新 Session(空白新-Session、`--create-session` 或 fork)设置模型,该 Session 会沿用它。与+Session 或 fork)设置模型,该 Session 会沿用它。与`--session-id` 一起使用会被拒绝(`model_override_with_existing_session`)。新 Session实际运行的组合(覆盖值加上它原本沿用的默认值)会被检查:Vibey 的 Model Hub 菜单不提供的模型或推理强度,或菜单无法加载时,会被拒绝(`session_model_unavailable`);claudediff --git a/docs/plans/agent-message-priority.md b/docs/plans/agent-message-priority.mdindex f61e7f86f..c59fd208c 100644--- a/docs/plans/agent-message-priority.md+++ b/docs/plans/agent-message-priority.md@@ -108,7 +108,7 @@ instead of claiming equivalent durability.| --- | --- | --- || Web composer | P3 | Starts when idle; otherwise joins the FIFO backlog. || Ordinary IM message | P1 | Steers the active Turn or starts when idle; a definitive refusal falls back to P3. |-| Existing-Session Agent Run | P1 | Same as ordinary IM. `--queue` selects P3. `--send-now` explicitly selects the same content-bearing P1 behavior and never promotes older queued work. |+| Existing-Session Agent Run | P1 | Same as ordinary IM. `--queue` selects P3. The new message never promotes older queued work. || Watch, Hook, Webhook | P1 | Continues the target Session without interrupting it. || Show annotation | P1 | Delivers the annotation to the current Turn when possible. || Session callback | P1 | Delivers each completed child Run independently. |diff --git a/docs/plans/agent-run-harness.md b/docs/plans/agent-run-harness.mdindex 1eea4bdca..2991febd3 100644--- a/docs/plans/agent-run-harness.md+++ b/docs/plans/agent-run-harness.md@@ -108,7 +108,10 @@ Execution controls:### Deprecating `vibe hook send`-Compatibility window:+The compatibility window has closed: `vibe hook send` is removed, and stored+`hook_send` run records stay readable.++Compatibility window (historical):```bashvibe hook send ... -> vibe agent run ...diff --git a/docs/plans/agent-run-harness.zh.md b/docs/plans/agent-run-harness.zh.mdindex df780fb29..1bb1615ed 100644--- a/docs/plans/agent-run-harness.zh.md+++ b/docs/plans/agent-run-harness.zh.md@@ -103,7 +103,9 @@ vibe agent run \### 废弃 `vibe hook send`-兼容窗口:+兼容窗口已结束:`vibe hook send` 已移除,已存储的 `hook_send` run 记录仍可读取。++兼容窗口(历史):```bashvibe hook send ... -> vibe agent run ...diff --git a/docs/plans/agent-run-scope-semantics.md b/docs/plans/agent-run-scope-semantics.mdindex 27dded9a3..7d575c2fb 100644--- a/docs/plans/agent-run-scope-semantics.md+++ b/docs/plans/agent-run-scope-semantics.md@@ -94,11 +94,13 @@ sync runs, the route is recorded for future detach-to-async behavior.Session" filter's. Responses report the scope they read as `session_id` and`global`.- Lists of records that do not belong to a Session (`vibe agent list`,- `vibe skill list`, Vault lists, `vibe session list`) have no Session scope;- `vibe session ...` commands address the Session itself positionally.+ `vibe skill list`, Vault lists, `vibe session list`) have no Session scope.+- `--session-id <id>` is the only way to name a Session. Single-Session+ commands (`vibe session get|update|send-now|queue list|queue remove` and the+ `vibe show` commands) default to the caller Session from `AVIBE_SESSION_ID`;+ without a caller they fail with `missing_caller_session`, as lists do.- `vibe runs show` may default to `AVIBE_RUN_ID`.- `vibe runs cancel` stays explicit; no `--current-run` shortcut in this batch.-- Single-object session commands may default object id from `AVIBE_SESSION_ID`.- `vibe task add` / `vibe watch add` default their target session to`AVIBE_SESSION_ID` when they continue an existing session.- A task/watch `create-session-per-run` definition uses storeddiff --git a/docs/plans/agents-run-graph-and-session-visibility.md b/docs/plans/agents-run-graph-and-session-visibility.mdindex 278e3e4ec..27e23b8eb 100644--- a/docs/plans/agents-run-graph-and-session-visibility.md+++ b/docs/plans/agents-run-graph-and-session-visibility.md@@ -166,8 +166,7 @@ Principle: `agent_runs` remains the only store; views are projections.- no scope param + caller context → **caller session's scope**,`visibility='background'`; cwd rule unchanged (caller shell cwd).- `--same-scope` / `--scope-id` → as today; visibility defaults to- `background` for delegated runs; explicit `--visibility foreground`- opt-in.+ `background` for delegated runs; explicit `--visible` opt-in.- no caller and no scope (human CLI outside a session) → **standalone**(`scope_id=NULL`) + `visibility='background'` + show-workspace workdir.- task/watch `create_per_run` sessions → definition's `session_scope_id`@@ -192,7 +191,7 @@ Principle: `agent_runs` remains the only store; views are projections.- API: `PATCH /api/sessions/:id { visibility }`; scope move is a separateoperation (`{ scope_id }`, may be NULL for standalone) that does not touchthe session's snapshotted workdir.-- CLI: `vibe session update --visibility foreground|background` and+- CLI: `vibe session update --visible|--hidden` and`--scope-id <scopes.id>|none`; agent-facing so an agent can surface asession it wrongly backgrounded.- UI: graph detail panel buttons (`移到前台` / `隐藏`); session list row menudiff --git a/docs/plans/agents-run-graph-contract.md b/docs/plans/agents-run-graph-contract.mdindex c8e23be4d..345354f41 100644--- a/docs/plans/agents-run-graph-contract.md+++ b/docs/plans/agents-run-graph-contract.md@@ -106,7 +106,7 @@ Amendments (orchestrator-approved):- Errors: `400` invalid value; `404` unknown session. Changing `scope_id`never mutates the session's stored `workdir`.-CLI equivalent: `vibe session update [--visibility foreground|background]+CLI equivalent: `vibe session update [--session-id <id>] [--visible|--hidden][--scope-id <scopes.id>|none]`.## 3. Graph endpoint (M2 owns; shape frozen for both)diff --git a/docs/plans/dispatch-time-message-metadata.md b/docs/plans/dispatch-time-message-metadata.mdindex ee1bf77f7..472773872 100644--- a/docs/plans/dispatch-time-message-metadata.md+++ b/docs/plans/dispatch-time-message-metadata.md@@ -36,7 +36,7 @@ and a restart that recovers the batch renders the same line. The sources are:| Task on-failure Agent turn | `[Harness: Task <task id> "<name>" on-failure]` || Webhook | `[Harness: webhook <definition id> "<name>"]` || `vibe agent run` from an Agent shell | `[Harness: agent run <run id> from #<caller session>]` |-| `vibe agent run` outside an Agent shell, or `vibe hook send` | `[Harness: agent run <run id> from the CLI]` |+| `vibe agent run` outside an Agent shell | `[Harness: agent run <run id> from the CLI]` || Callback of a finished run | `[Harness: callback of run <run id> from #<run's session>]` || Vault request outcome | `[Harness: Vault request <request id>]` || `hook_send` run queued by a release before `vibe hook send` became an Agent run | `[Harness: hook send <run id>]` |diff --git a/skills/use-avibe-harness/SKILL.md b/skills/use-avibe-harness/SKILL.mdindex 9838ffe9d..2df32c0ac 100644--- a/skills/use-avibe-harness/SKILL.md+++ b/skills/use-avibe-harness/SKILL.md@@ -47,9 +47,9 @@ Useful Harness queries include schema discovery, current session lookup, existin| 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>` |+| Inspect queued Workbench Session input | `vibe session queue list --session-id <session-id>` |+| Remove one queued Workbench Session input | `vibe session queue remove <message-id> --session-id <session-id>` |+| Promote an existing queued Session head now | `vibe session send-now --session-id <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`, `vibe runs show` |@@ -65,15 +65,15 @@ Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegatesUse `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.-Any run that creates a new Session (a blank new Session from `--agent`, `--create-session`, or a fork) may set that Session's model with `--model` and `--reasoning-effort`; the Session keeps it for its later turns. A Vibey model or effort its Model Hub menu does not offer is refused; for claude and codex an unknown value is a warning. `vibe agent models <agent>` lists valid values.+Any run that creates a new Session (a blank new Session from `--agent`, or a fork) may set that Session's model with `--model` and `--reasoning-effort`; the Session keeps it for its later turns. A Vibey model or effort its Model Hub menu does not offer is refused; for claude and codex an unknown value is a warning. `vibe agent models <agent>` lists valid values.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.+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. The new message never promotes an older queued one. Use `vibe session send-now --session-id <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.+Coordinating Agents can inspect the same durable Workbench queue the user sees with `vibe session queue list --session-id <id>`. If one queued instruction has become obsolete, contradictory, or duplicated, remove that exact row with `vibe session queue remove <message-id> --session-id <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.+Use `vibe session update --session-id <id> --visible` or `--hidden` to promote or hide a persisted Session independently of its scope; without `--session-id` it updates this Session. 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.diff --git a/skills/use-avibe/references/harness.md b/skills/use-avibe/references/harness.mdindex cdddfba28..0c6e3a576 100644--- a/skills/use-avibe/references/harness.md+++ b/skills/use-avibe/references/harness.md@@ -15,10 +15,10 @@ Preferred CLI shape:- delegate to a visible sibling Session in the same scope from an Avibe Agent shell: `vibe agent run --agent '<agent-name>' --same-scope --message '...'`- wait for an Agent result in the terminal: `vibe agent run --sync --agent '<agent-name>' --message '...'`- continue a specific existing Session: `vibe agent run --session-id '<session-id>' --message '...'`-- explicitly steer a new message as P1 into the active Turn: `vibe agent run --session-id '<session-id>' --send-now --message '...'`-- steer an already-queued exact head without adding a message: `vibe session send-now '<session-id>'`-- inspect another Session's durable FIFO queue: `vibe session queue list '<session-id>'`-- remove one exact queued message after inspecting its stable ID: `vibe session queue remove '<session-id>' '<message-id>'`+- queue a new message behind the active Turn instead of steering it: `vibe agent run --session-id '<session-id>' --queue --message '...'`+- steer an already-queued exact head without adding a message: `vibe session send-now --session-id '<session-id>'`+- inspect another Session's durable FIFO queue: `vibe session queue list --session-id '<session-id>'`+- remove one exact queued message after inspecting its stable ID: `vibe session queue remove '<message-id>' --session-id '<session-id>'`- fork this Session for an alternate path: `vibe agent run --fork-self --message '...'`- fork another explicit Session for an alternate path: `vibe agent run --fork-session '<source-session-id>' --message '...'`- recurring task for this conversation: `vibe task add --cron '<expr>' --message '...'`; write cron weekdays as names (`mon` ... `sun`), since numeric weekdays are rejected@@ -39,10 +39,10 @@ Targeting and callbacks:- Use `--session-id <id>` only when the command should operate on a different existing Agent Session.- 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.- When coordinating another Workbench Session, decide whether its current turn should finish or be preempted from the work dependency, urgency, and cost of discarding in-flight work. An explicit user request is one signal, not a prerequisite.-- Add `--send-now` to explicitly select the normal content-bearing P1 behavior for an existing Session. It steers that new message into an active Turn, starts it when idle, and falls back to P3 only after a definitive refusal; it never promotes an older queued message.-- Use `vibe session send-now <session-id>` when a Session already has queued work and no new message should be added. This promotes the existing FIFO head.+- A new message to an existing Session is P1 by default: it steers into an active Turn, starts when idle, and falls back to P3 only after a definitive refusal; it never promotes an older queued message. Add `--queue` to put it in P3 behind the active Turn instead.+- Use `vibe session send-now --session-id <session-id>` when a Session already has queued work and no new message should be added. This promotes the existing FIFO head.- Both commands use the shared steering path for Workbench and IM Sessions. A refused or stale steer leaves the affected input durably queued and never falls back to Stop.-- Use `vibe session queue list <session-id>` before changing another Workbench Session's queue. If an instruction is obsolete, contradictory, or duplicated, remove that exact stable row with `vibe session queue remove <session-id> <message-id>`. Never guess a message ID or delete another row to simulate reordering.+- Use `vibe session queue list --session-id <session-id>` before changing another Workbench Session's queue. If an instruction is obsolete, contradictory, or duplicated, remove that exact stable row with `vibe session queue remove <message-id> --session-id <session-id>`. Never guess a message ID or delete another row to simulate reordering.- When `vibe agent run` creates a new Session, the default placement is private/background. Add `--same-scope` for a visible sibling Session in the same Workbench project or IM scope, or `--scope-id <scopes.id>` for a specific existing scope.- When a task, watch, or new Agent run creates a Session and `--cwd` is omitted, Avibe uses the command's current working directory. Forks keep the source Session cwd by default.- Async Agent runs return the final result to this conversation by default. Pass `--no-callback` only when you will inspect the run later with `vibe runs`. Pass `--callback-session-id <id>` only when the final result should return to a different Session.@@ -50,7 +50,7 @@ Targeting and callbacks:- `vibe task add` stores a message template — or, with `--shell` / a trailing `-- <argv>`, a command — and creates Runs when the time trigger fires. A command task runs with no Agent turn: silent on success, a failure notice on failure, `--on-failure agent` to escalate failures to an Agent.- `vibe watch add` uses `--message` as the instruction template for the Agent Run created after the waiter reaches a reportable state.- `--fork-self` forks this Session's native backend context. `--fork-session <id>` forks another explicit Session. Forks keep the source Session backend, scope, and cwd by default.-- `--model` and `--reasoning-effort` set the model of any new Session a run creates (blank, `--create-session`, or a fork); the Session keeps it, and they are refused with `--session-id`. Fork overrides stay narrow: `--agent`, `--model`, and `--reasoning-effort` can override the forked Session only if the backend stays the same. Do not combine fork flags with existing-session or session-creation flags.+- `--model` and `--reasoning-effort` set the model of any new Session a run creates (blank or a fork); the Session keeps it, and they are refused with `--session-id`. Fork overrides stay narrow: `--agent`, `--model`, and `--reasoning-effort` can override the forked Session only if the backend stays the same. Do not combine fork flags with `--session-id`.Operational guidance:diff --git a/skills/use-show-pages/SKILL.md b/skills/use-show-pages/SKILL.mdindex 66d9008bb..c29cdc8de 100644--- a/skills/use-show-pages/SKILL.md+++ b/skills/use-show-pages/SKILL.md@@ -51,7 +51,7 @@ These rules apply only to this Session's Show Page workspace and its Avibehistory. Avibe manages page checkpoints automatically; do not create versionsmanually for page edits.-Before operating on history, run `vibe show status --json`. Use its `path`+Before operating on history, run `vibe show status`. Use its `path`as `<show-workspace>` and inspect `history.mode`, `history.checkpointing_active`,and `history.git_dir`. Status is read-only; it does not initialize a repository.If checkpointing is inactive, do not assume new edits have automatic checkpointsdiff --git a/tests/scenarios/permissions/catalog.yaml b/tests/scenarios/permissions/catalog.yamlindex 252be08c6..ec02b0b8f 100644--- a/tests/scenarios/permissions/catalog.yaml+++ b/tests/scenarios/permissions/catalog.yaml@@ -346,7 +346,6 @@ scenarios:test:- tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_the_open_project_binds_the_signed_editor- tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_every_producer_refuses_an_unreachable_target- - tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_a_legacy_key_names_the_same_session- tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_the_callers_own_session_is_an_effective_target- tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_a_callback_is_admitted_before_the_run_is_reserved- tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_a_forbidden_project_target_is_refused@@ -365,10 +364,7 @@ scenarios:- tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_a_reserved_replacement_still_follows_the_session_it_makes- tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_clearing_the_agent_on_per_run_work_resolves_one- tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_the_callers_that_could_still_retarget_per_run_work- - tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_a_fresh_legacy_target_is_a_placement_not_a_blank- - tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_fresh_legacy_work_still_opens_for_the_callers_that_could- - tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_an_update_onto_a_fresh_legacy_target_is_admitted_too- tests/scenarios/permissions/test_effective_target_preflight.py::test_permissions_028_saved_control_keeps_the_definitions_own_authority- given: A signed caller names a Session it may not drive, by Session id, by legacy scope key whose thread exists or has never been opened, or by defaulting to its own, or repoints a stored definition at a destination it may or may not use+ given: A signed caller names a Session it may not drive, by Session id or by defaulting to its own, or repoints a stored definition at a destination it may or may not usewhen: A Run, a callback route, and a Task or Watch definition are produced or retargeted through the real CLI- then: Each producer refuses before writing, leaving Run definition Session and Scope counts and the stored row unchanged, a target whose Session does not exist yet is admitted as the placement it is rather than skipped for having no row, an edit that replaces its Session is judged on the destination it chooses rather than the one it abandons, work that becomes per-run admits the Agent each future fire will select with its follow-the-Session marker read from the edit's final policy, and permitted Editors Member Owner and local callers keep the reach they had while saved automation control keeps the definition's own authority+ then: Each producer refuses before writing, leaving Run definition Session and Scope counts and the stored row unchanged, an edit that replaces its Session is judged on the destination it chooses rather than the one it abandons, work that becomes per-run admits the Agent each future fire will select with its follow-the-Session marker read from the edit's final policy, and permitted Editors Member Owner and local callers keep the reach they had while saved automation control keeps the definition's own authoritydiff --git a/tests/scenarios/permissions/test_cli_invocation_authority.py b/tests/scenarios/permissions/test_cli_invocation_authority.pyindex 22ea659f8..7cae1da62 100644--- a/tests/scenarios/permissions/test_cli_invocation_authority.py+++ b/tests/scenarios/permissions/test_cli_invocation_authority.py@@ -363,7 +363,7 @@ def test_permissions_026_a_stale_snapshot_cannot_reach_a_command_that_forwards_itry:before = counts()- argv = ["agent", "run", "--create-session", "--message", "hi", "--async", "--no-callback"]+ argv = ["agent", "run", "--message", "hi", "--no-callback"]assert invoke(argv, caller=caller) == 1payload = _refusal(capsys)assert payload["code"] == "instance_access_forbidden"diff --git a/tests/scenarios/permissions/test_effective_target_preflight.py b/tests/scenarios/permissions/test_effective_target_preflight.pyindex 1e98d60dc..efa20799d 100644--- a/tests/scenarios/permissions/test_effective_target_preflight.py+++ b/tests/scenarios/permissions/test_effective_target_preflight.py@@ -51,9 +51,6 @@ from tests.scenarios.permissions.test_cli_invocation_authority import (EDITOR_EMAIL = "[email protected]"IM_SCOPE_KEY = "slack::channel::C123"IM_ANCHOR = "slack_C123"-#: A well-formed legacy key with no Scope and no Session behind it yet. Each case-#: suffixes it so one case's placement never becomes the next one's existing row.-FRESH_SCOPE_KEY = "slack::channel::C_NEW"@pytest.fixture(params=["personal", "organization"])@@ -307,7 +304,7 @@ def test_permissions_028_the_open_project_binds_the_signed_editor():@pytest.mark.parametrize("command",- ["agent_run", "hook_send", "task_add", "watch_add"],+ ["agent_run", "task_add", "watch_add"],)def test_permissions_028_every_producer_refuses_an_unreachable_target(targets, run_cli, command):"""PERMISSIONS-028: no producer writes work into a Session its caller cannot drive."""@@ -317,8 +314,7 @@ def test_permissions_028_every_producer_refuses_an_unreachable_target(targets, rbefore = state.counts()argv = {- "agent_run": ["agent", "run", "--session-id", standalone, "--message", "hi", "--async", "--no-callback"],- "hook_send": ["hook", "send", "--session-id", standalone, "--message", "hi"],+ "agent_run": ["agent", "run", "--session-id", standalone, "--message", "hi", "--no-callback"],"task_add": _message_task_argv("--session-id", standalone),"watch_add": _watch_argv("--session-id", standalone),}[command]@@ -333,31 +329,6 @@ def test_permissions_028_every_producer_refuses_an_unreachable_target(targets, rassert state.counts() == before-def test_permissions_028_a_legacy_key_names_the_same_session(targets, run_cli):- """PERMISSIONS-028: the deprecated scope key resolves to the row it would speak in."""-- state = targets- before = state.counts()-- code, payload = run_cli(- ["hook", "send", "--session-key", IM_SCOPE_KEY, "--message", "hi"],- kind=state.kind,- )- assert code == 1- assert payload["code"] == "session_not_found"- assert payload["details"]["session_id"] == state.sessions["legacy"]- assert state.counts() == before-- # A key naming a thread that does not exist yet is a creation, not a- # refusal: it is admitted as a placement instead (see below), so a local- # caller opening new IM work is unaffected by the gate.- fresh = run_cli(- ["hook", "send", "--session-key", "slack::channel::C999", "--message", "hi"],- role=None,- )- assert fresh[0] == 0--def test_permissions_028_the_callers_own_session_is_an_effective_target(targets, run_cli):"""PERMISSIONS-028: a target Avibe defaulted from the caller env is still checked."""@@ -391,7 +362,6 @@ def test_permissions_028_a_callback_is_admitted_before_the_run_is_reserved(targestate.agent.name,"--message","hi",- "--async","--callback-session-id",state.sessions["standalone"],],@@ -432,7 +402,7 @@ def test_permissions_028_an_unusable_agent_refuses_the_turn(targets, run_cli):before = state.counts()code, payload = run_cli(- ["agent", "run", "--session-id", state.sessions["open"], "--message", "hi", "--async", "--no-callback"],+ ["agent", "run", "--session-id", state.sessions["open"], "--message", "hi", "--no-callback"],kind=state.kind,)@@ -451,7 +421,7 @@ def test_permissions_028_a_permitted_editor_still_queues_the_turn(targets, run_cbefore = state.counts()code, payload = run_cli(- ["agent", "run", "--session-id", state.sessions["open"], "--message", "hi", "--async", "--no-callback"],+ ["agent", "run", "--session-id", state.sessions["open"], "--message", "hi", "--no-callback"],kind=state.kind,)assert code == 0, payload@@ -472,7 +442,7 @@ def test_permissions_028_runtime_management_and_local_callers_are_unchanged(targbefore = state.counts()code, payload = run_cli(- ["agent", "run", "--session-id", state.sessions["standalone"], "--message", "hi", "--async", "--no-callback"],+ ["agent", "run", "--session-id", state.sessions["standalone"], "--message", "hi", "--no-callback"],role=role,kind=state.kind,)@@ -911,95 +881,6 @@ def test_permissions_028_the_callers_that_could_still_retarget_per_run_work(assert BINDING_FOLLOWS_SESSION_METADATA_KEY not in after["metadata"][email protected]("command", ["hook_send", "task_add", "watch_add"])-def test_permissions_028_a_fresh_legacy_target_is_a_placement_not_a_blank(- targets, run_cli, command-):- """PERMISSIONS-028: a key whose thread nobody has opened yet is still a target.-- There is no Session to admit the caller TO, but the work being written says- where one will be created on the first dispatch -- the reservation writer's- question, asked one step earlier. Read as "no target, no question", the same- Editor who is refused the IM thread that exists was handed the one that does- not, and every future fire with it.- """-- state = targets- key = f"{FRESH_SCOPE_KEY}_{command}"- before = state.counts()-- argv = {- "hook_send": ["hook", "send", "--session-key", key, "--message", "hi"],- "task_add": _message_task_argv("--session-key", key),- "watch_add": _watch_argv("--session-key", key),- }[command]- code, payload = run_cli(argv, kind=state.kind)-- # An IM scope is not a Project, so no Personal Project bypass reaches this --- # the same answer the identical key gets once its Session exists.- assert code == 1- assert payload["code"] == "project_access_denied"- # Scopes included: resolving the key to ask the question must not leave the- # row the question was about.- assert state.counts() == before--[email protected]("role", ["member", "owner", None])-def test_permissions_028_fresh_legacy_work_still_opens_for_the_callers_that_could(- targets, run_cli, role-):- """PERMISSIONS-028: Member, Owner and a local caller keep opening new IM work."""-- state = targets- before = state.counts()-- code, payload = run_cli(- ["hook", "send", "--session-key", f"{FRESH_SCOPE_KEY}_{role}", "--message", "hi"],- role=role,- kind=state.kind,- )- assert code == 0, payload- assert state.counts()["runs"] == before["runs"] + 1--[email protected]("kind_of_work", ["task", "watch"])-def test_permissions_028_an_update_onto_a_fresh_legacy_target_is_admitted_too(- targets, run_cli, kind_of_work-):- """PERMISSIONS-028: an edit may not repoint saved work at a Scope it cannot reach.-- The definition keeps speaking in the target this edit names, so the target is- reauthorized -- and a Session that does not exist yet is reauthorized as the- placement it is, not skipped for having no row.- """-- state = targets- seeded = (- _message_task_argv("--session-id", state.sessions["standalone"], name="repoint")- if kind_of_work == "task"- else _watch_argv("--session-id", state.sessions["standalone"], name="repoint")- )- assert run_cli(seeded, role=None)[0] == 0- rows = state.task_rows() if kind_of_work == "task" else state.watch_rows()- definition_id = next(iter(rows))- before = state.counts()-- code, payload = run_cli(- [- kind_of_work,- "update",- definition_id,- "--session-key",- f"{FRESH_SCOPE_KEY}_update_{kind_of_work}",- ],- kind=state.kind,- )- assert code == 1- assert payload["code"] == "project_access_denied"- assert (state.task_rows() if kind_of_work == "task" else state.watch_rows()) == rows- assert state.counts() == before--def test_permissions_028_saved_control_keeps_the_definitions_own_authority(targets, run_cli):"""PERMISSIONS-028: pausing saved work is admission, not a reauthorization."""diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.pyindex 6dc07ca51..4c6c37580 100644--- a/tests/test_cli_agent_run_schema.py+++ b/tests/test_cli_agent_run_schema.py@@ -209,7 +209,7 @@ def test_agent_run_explicit_async_flag_remains_compatible(tmp_path: Path, capsysagent_store = cli.VibeAgentStore(db_path)agent_store.create(name="worker", backend="codex")request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hi"])+ args = _parse_agent_run(["--agent", "worker", "--no-callback", "--message", "hi"])with (patch("vibe.cli._agent_store", return_value=agent_store),@@ -416,7 +416,7 @@ def test_agent_run_async_defaults_callback_from_caller_env(tmp_path: Path, capsyassert stored["metadata"]["caller_context"]["session_id"] == caller_session["id"]-def test_agent_run_send_now_is_explicit_p1_on_an_existing_session(+def test_agent_run_existing_session_defaults_to_p1_steer(tmp_path: Path,capsys,) -> None:@@ -470,7 +470,6 @@ def test_agent_run_send_now_is_explicit_p1_on_an_existing_session(["--session-id",session_id,- "--send-now","--no-callback","--message","apply this correction",@@ -492,26 +491,6 @@ def test_agent_run_send_now_is_explicit_p1_on_an_existing_session(assert stored["metadata"]["delivery_intent"] == "steer"-def test_agent_run_send_now_rejects_a_new_session(capsys) -> None:- args = _parse_agent_run(- [- "--agent",- "worker",- "--send-now",- "--no-callback",- "--message",- "apply this correction",- ]- )-- result = cli.cmd_agent_run(args)-- assert result == 1- payload = json.loads(capsys.readouterr().err)- assert payload["code"] == "send_now_requires_existing_session"- assert "--session-id" in payload["hint"]--def test_agent_run_queue_persists_explicit_p3_intent(tmp_path: Path,capsys,@@ -587,7 +566,7 @@ def test_agent_run_queue_persists_explicit_p3_intent(assert stored["metadata"]["delivery_intent"] == "queue"-def test_agent_run_send_now_accepts_an_im_backed_session(+def test_agent_run_steers_an_im_backed_session_by_default(tmp_path: Path,capsys,) -> None:@@ -643,7 +622,6 @@ def test_agent_run_send_now_accepts_an_im_backed_session("worker","--session-id",session["id"],- "--send-now","--no-callback","--message","steer this",@@ -1128,7 +1106,6 @@ def test_agent_run_callback_conflict_does_not_reserve_session(tmp_path: Path, ca["--agent","worker",- "--async","--callback-session-id","ses-caller","--no-callback",@@ -1245,7 +1222,6 @@ def test_agent_run_fork_session_reserves_new_session_and_persists_metadata(tmp_p"gpt-5.2","--reasoning-effort","low",- "--async","--no-callback","--message","continue from here",@@ -1307,7 +1283,6 @@ def test_agent_run_fork_self_uses_caller_session_and_inherits_scope(tmp_path: Pa"--fork-self","--agent","reviewer",- "--async","--no-callback","--message","continue from here",@@ -1355,7 +1330,7 @@ def test_agent_run_create_same_scope_snapshots_scope_workdir(tmp_path: Path, capagent_store = cli.VibeAgentStore(db_path)agent_store.create(name="worker", backend="codex")request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- args = _parse_agent_run(["--agent", "worker", "--same-scope", "--async", "--no-callback", "--message", "hi"])+ args = _parse_agent_run(["--agent", "worker", "--same-scope", "--no-callback", "--message", "hi"])monkeypatch.chdir(invoke_dir)with (@@ -1402,7 +1377,7 @@ def test_agent_run_same_scope_rejects_standalone_caller(tmp_path: Path, capsys)agent_store.create(name="worker", backend="codex")request_store = cli.TaskExecutionStore(tmp_path / "task_requests")args = _parse_agent_run(- ["--agent", "worker", "--same-scope", "--async", "--no-callback", "--message", "hi"]+ ["--agent", "worker", "--same-scope", "--no-callback", "--message", "hi"])with (@@ -1427,7 +1402,6 @@ def test_agent_run_same_scope_rejects_standalone_fork_source(monkeypatch) -> Non"--fork-session","ses-standalone","--same-scope",- "--async","--no-callback","--message","hi",@@ -1452,7 +1426,6 @@ def test_agent_run_fork_defaults_to_source_scope_not_caller_scope(monkeypatch) -"worker","--fork-session","ses-source",- "--async","--no-callback","--message","hi",@@ -1500,7 +1473,6 @@ def test_agent_run_create_scope_id_snapshots_scope_workdir(tmp_path: Path, capsy"worker","--scope-id","avibe::project::proj_fork_cli",- "--async","--no-callback","--message","hi",@@ -1547,7 +1519,6 @@ def test_agent_run_create_scope_id_requires_existing_scope(tmp_path: Path, capsy"worker","--scope-id","avibe::project::missing",- "--async","--no-callback","--message","hi",@@ -1611,7 +1582,6 @@ def test_agent_run_create_scope_id_rejects_archived_project(tmp_path: Path, caps"worker","--scope-id",scope_id,- "--async","--no-callback","--message","hi",@@ -1647,7 +1617,6 @@ def test_agent_run_fork_rejects_cross_backend_agent(tmp_path: Path, capsys) -> Nsource_session_id,"--agent","claude-worker",- "--async","--no-callback","--message","hi",@@ -1691,7 +1660,6 @@ def test_only_fork_self_is_the_agents_own_fork(tmp_path: Path, capsys, flags, se*[source_session_id if flag == "SOURCE" else flag for flag in flags],"--agent","worker",- "--async","--no-callback","--message","try the other fix",@@ -1714,7 +1682,7 @@ def test_only_fork_self_is_the_agents_own_fork(tmp_path: Path, capsys, flags, seassert reserve.call_args.kwargs["self_fork"] is self_fork-def test_agent_run_fork_localizes_unavailable_source_agent(monkeypatch) -> None:+def test_agent_run_fork_reports_unavailable_source_agent_in_english_under_a_zh_ui(monkeypatch) -> None:from core.services.session_fork import (SESSION_AGENT_UNAVAILABLE_CODE,SESSION_AGENT_UNAVAILABLE_I18N_KEY,@@ -1745,8 +1713,8 @@ def test_agent_run_fork_localizes_unavailable_source_agent(monkeypatch) -> None:exc = exc_info.valueassert exc.code == SESSION_AGENT_UNAVAILABLE_CODE- assert str(exc) == i18n_t(f"{SESSION_AGENT_UNAVAILABLE_I18N_KEY}.message", "zh")- assert exc.hint == i18n_t(f"{SESSION_AGENT_UNAVAILABLE_I18N_KEY}.hint", "zh")+ assert str(exc) == i18n_t(f"{SESSION_AGENT_UNAVAILABLE_I18N_KEY}.message", "en")+ assert exc.hint == i18n_t(f"{SESSION_AGENT_UNAVAILABLE_I18N_KEY}.hint", "en")assert exc.details == {"source_session_id": "ses-source"}@@ -1763,7 +1731,7 @@ def test_agent_run_callerless_session_workdir_uses_show_workspace(tmp_path: Pathagent_store = cli.VibeAgentStore(db_path)agent_store.create(name="worker", backend="codex")request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hi"])+ args = _parse_agent_run(["--agent", "worker", "--no-callback", "--message", "hi"])monkeypatch.chdir(invoke_dir)with (@@ -1796,7 +1764,7 @@ def test_agent_run_explicit_cwd_wins(tmp_path: Path, capsys, monkeypatch) -> Nonagent_store.create(name="worker", backend="codex")request_store = cli.TaskExecutionStore(tmp_path / "task_requests")args = _parse_agent_run(- ["--agent", "worker", "--cwd", str(picked_dir), "--async", "--no-callback", "--message", "hi"]+ ["--agent", "worker", "--cwd", str(picked_dir), "--no-callback", "--message", "hi"])monkeypatch.chdir(invoke_dir)@@ -1815,7 +1783,7 @@ def test_agent_run_explicit_cwd_wins(tmp_path: Path, capsys, monkeypatch) -> Nondef test_agent_run_cwd_must_exist(tmp_path: Path, capsys) -> None:args = _parse_agent_run(- ["--agent", "worker", "--create-session", "--cwd", str(tmp_path / "missing"), "--async", "--message", "hi"]+ ["--agent", "worker", "--cwd", str(tmp_path / "missing"), "--message", "hi"])result = cli.cmd_agent_run(args)@@ -1829,7 +1797,7 @@ def test_agent_run_cwd_must_exist(tmp_path: Path, capsys) -> None:def test_agent_run_cwd_rejected_with_existing_session(capsys) -> None:"""An existing session keeps its own workdir — --cwd cannot re-route it."""- args = _parse_agent_run(["--session-id", "ses123", "--cwd", "/tmp", "--async", "--message", "hi"])+ args = _parse_agent_run(["--session-id", "ses123", "--cwd", "/tmp", "--message", "hi"])result = cli.cmd_agent_run(args)diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.pyindex d09b273aa..511b7555f 100644--- a/tests/test_cli_pagination.py+++ b/tests/test_cli_pagination.py@@ -7,8 +7,8 @@ import jsonimport reimport shlexfrom pathlib import Path-from types import SimpleNamespace-from unittest.mock import patch++import pytestimport pytest@@ -134,42 +134,59 @@ def test_injected_and_builtin_skill_commands_only_use_parser_supported_flags() -assert checked_commands >= 20-def test_managed_harness_session_queue_commands_name_real_subcommands() -> None:+def test_session_examples_in_guidance_parse_against_the_cli() -> None:+ """Every `vibe session ...` call the prompt or a built-in Skill teaches must parse.++ The flag check above cannot see a Session named positionally: `vibe session+ get <id>` mentions no flag. The session group names its Session only with+ `--session-id`, so an example that still passes it positionally fails here.+ """+context = MessageContext(user_id="user",channel_id="channel",platform="avibe",platform_specific={"agent_session_id": "ses-test"},)- 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()+ guidance = [build_system_prompt_injection(context=context)] + [+ path.read_text() for path in sorted((ROOT / "skills").rglob("*.md"))+ ]+ examples = sorted(set(re.findall(r"`(vibe session [^`\n]+)`", "\n".join(guidance))))+ assert any("queue remove" in example for example in examples), examples- assert "load the `use-avibe-harness` Skill" in prompt+ parser = cli.build_parser()+ for example in examples:+ argv = shlex.split(re.sub(r"<[^>]+>|\.\.\.", "x", example))[1:]+ try:+ parser.parse_args(argv)+ except SystemExit as exc:+ raise AssertionError(f"guidance teaches an unparseable session command: {example!r}") from exc- for command, expected_path in (- (- "vibe session queue list <session-id>",- ("session", "queue", "list"),- ),- (- "vibe session queue remove <session-id> <message-id>",- ("session", "queue", "remove"),- ),- ):- assert f"`{command}`" in harness_skill- _, path = _prompt_command_parser(command)- assert path == expected_path++ ("argv", "expected_limit", "error_code"),+ [+ (["--limit", "500"], 100, None),+ (["--limit", "100"], 100, None),+ (["--limit", "0"], None, "invalid_pagination"),+ (["--page", "0"], None, "invalid_pagination"),+ ],+)+def test_cli_limit_above_the_maximum_is_served_at_the_maximum(+ monkeypatch, tmp_path, capsys, argv, expected_limit, error_code+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ args = cli.build_parser().parse_args(["session", "list", *argv])++ result = cli.cmd_session_list(args)++ captured = capsys.readouterr()+ if error_code is None:+ assert result == 0+ assert json.loads(captured.out)["pagination"]["limit"] == expected_limit+ else:+ assert result == 1+ assert json.loads(captured.err)["code"] == error_code@pytest.mark.parametrize(diff --git a/tests/test_cli_screenshot_command.py b/tests/test_cli_screenshot_command.pyindex ea1ca9561..99851d7c2 100644--- a/tests/test_cli_screenshot_command.py+++ b/tests/test_cli_screenshot_command.py@@ -47,7 +47,9 @@ def test_cmd_screenshot_prints_json(capsys, monkeypatch) -> None:assert cli.cmd_screenshot(args) == 0payload = json.loads(capsys.readouterr().out)assert payload == {+ "schema_version": 1,"ok": True,+ "kind": "screenshot","path": "/tmp/vibe-screen.png","backend": "fake",}diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.pyindex ca497baa7..ed0bea13c 100644--- a/tests/test_cli_task_command.py+++ b/tests/test_cli_task_command.py@@ -40,11 +40,6 @@ def _parse_task_add(argv: list[str]):return parser.parse_args(["task", "add", *argv])-def _parse_hook_send(argv: list[str]):- parser = cli.build_parser()- return parser.parse_args(["hook", "send", *argv])--def _parse_agent_run(argv: list[str]):parser = cli.build_parser()return parser.parse_args(["agent", "run", *argv])@@ -94,7 +89,7 @@ def test_disabled_agent_cannot_run(tmp_path: Path, sqlite_schema_db_factory) ->db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")agent_store = cli.VibeAgentStore(db_path)agent_store.create(name="worker", backend="codex", enabled=False)- args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hello"])+ args = _parse_agent_run(["--agent", "worker", "--no-callback", "--message", "hello"])with patch("vibe.cli._agent_store", return_value=agent_store):result, payload = _capture_stderr_json(cli.cmd_agent_run, args)@@ -211,7 +206,7 @@ def test_agent_remove_cli_archives_agent(tmp_path: Path, capsys, sqlite_schema_dagent_store.close()-def test_agent_remove_cli_localizes_archive_refusal(tmp_path: Path, sqlite_schema_db_factory) -> None:+def test_agent_remove_cli_archive_refusal_is_english_under_a_zh_ui(tmp_path: Path, sqlite_schema_db_factory) -> None:agent_store = cli.VibeAgentStore(sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite"))try:agent_store.create(name="only-agent", backend="codex")@@ -230,13 +225,13 @@ def test_agent_remove_cli_localizes_archive_refusal(tmp_path: Path, sqlite_schemassert result == 1assert payload["code"] == "agent_no_default_replacement"- assert payload["error"] == "没有其他已启用 Agent 时,无法归档默认 Agent `only-agent`。"- assert payload["hint"] == "归档当前默认 Agent 前,请保留另一个已启用 Agent。"+ assert payload["error"] == "The default Agent `only-agent` cannot be archived without another enabled Agent."+ assert payload["hint"] == "Keep another enabled Agent available when archiving the current default."finally:agent_store.close()-def test_agent_remove_cli_localizes_invalid_reference_metadata() -> None:+def test_agent_remove_cli_invalid_reference_metadata_is_english_under_a_zh_ui() -> None:def refuse_archive(_name):raise cli.AgentReferenceRewriteError()@@ -252,11 +247,11 @@ def test_agent_remove_cli_localizes_invalid_reference_metadata() -> None:assert result == 1assert payload["code"] == "agent_reference_metadata_invalid"- assert payload["error"] == "任务或监控包含无效元数据,Avibe 无法更新 Agent 引用。"- assert payload["hint"] == "请修复或删除元数据异常的任务或监控,然后重试。"+ assert payload["error"] == "Avibe cannot update Agent references because a task or watch contains invalid metadata."+ assert payload["hint"] == "Repair or remove the malformed task or watch metadata, then try again."-def test_agent_update_and_enable_localize_archived_edit_refusal(tmp_path: Path, sqlite_schema_db_factory) -> None:+def test_agent_update_and_enable_archived_edit_refusal_is_english_under_a_zh_ui(tmp_path: Path, sqlite_schema_db_factory) -> None:agent_store = cli.VibeAgentStore(sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite"))try:agent_store.create(name="archive-fallback", backend="codex")@@ -279,8 +274,8 @@ def test_agent_update_and_enable_localize_archived_edit_refusal(tmp_path: Path,for result, payload in ((update_result, update_payload), (enable_result, enable_payload)):assert result == 1assert payload["code"] == "agent_archived_read_only"- assert payload["error"] == f"Agent `{archived.archived_name}` 已归档,无法编辑。"- assert payload["hint"] == "已归档 Agent 为只读状态,仅供现有持久引用继续使用。"+ assert payload["error"] == f"Agent `{archived.archived_name}` is archived and cannot be edited."+ assert payload["hint"] == "Archived Agents are read-only and remain available only to existing durable references."finally:agent_store.close()@@ -303,43 +298,19 @@ def test_agent_list_is_bounded_and_compact_by_default(tmp_path: Path, capsys, sqassert payload["pagination"]["next_command"] == "vibe agent list --page 2 --limit 20"-def test_task_add_rejects_unsupported_platform() -> None:- args = _parse_task_add(- [- "--session-key",- "foo::channel::C123",- "--cron",- "0 * * * *",- "--message",- "hello",- ]- )-- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack", "discord"})):- result, payload = _capture_stderr_json(cli.cmd_task_add, args)-- assert result == 1- assert payload["code"] == "unsupported_platform"- assert payload["details"]["requested_platform"] == "foo"- assert payload["help_command"] == "vibe task add --help"---def test_task_add_rejects_disabled_platform_even_with_credentials_present() -> None:- args = _parse_task_add(- [- "--session-key",- "discord::channel::C123",- "--cron",- "0 * * * *",- "--message",- "hello",- ]+def test_task_add_rejects_disabled_platform_even_with_credentials_present(+ tmp_path: Path, monkeypatch, sqlite_schema_db_factory+) -> None:+ _bare_terminal_caller(monkeypatch)+ db_path, agent_store = _caller_session_state(+ tmp_path, sqlite_schema_db_factory, session_id="sesDiscord", platform="discord", scope_type="channel", scope_key="C123")+ args = _parse_task_add(["--session-id", "sesDiscord", "--cron", "0 * * * *", "--message", "hello"])config = _configured_v2({"slack"})config.discord.bot_token = "configured-but-disabled"- with patch("vibe.cli._ensure_config", return_value=config):+ with _cli_state(db_path, agent_store), patch("vibe.cli._ensure_config", return_value=config):result, payload = _capture_stderr_json(cli.cmd_task_add, args)assert result == 1@@ -358,28 +329,6 @@ def test_supported_task_platforms_always_includes_avibe() -> None:assert "avibe" in cli._supported_task_platforms()-def test_task_add_rejects_avibe_session_key() -> None:- # avibe passes the platform gate but a bare session KEY has no agent session- # id, so the reply couldn't attach to a workbench session — must be rejected- # (target workbench sessions by --session-id instead).- args = _parse_task_add(- [- "--session-key",- "avibe::channel::ses3chKBjP5hy",- "--cron",- "0 * * * *",- "--message",- "hello",- ]- )- config = _configured_v2({"slack"})- with patch("vibe.cli._ensure_config", return_value=config):- result, payload = _capture_stderr_json(cli.cmd_task_add, args)-- assert result == 1- assert payload["code"] == "avibe_requires_session_id"--def test_task_help_describes_session_id_guidance(capsys) -> None:parser = cli.build_parser()@@ -413,23 +362,6 @@ def test_task_add_help_includes_examples_and_threadless_guidance(capsys) -> Noneassert "Write cron weekdays as names (mon, tue, ... sun)." in captured.out-def test_hook_send_help_describes_runtime_effects(capsys) -> None:- parser = cli.build_parser()-- with pytest.raises(SystemExit) as exc:- parser.parse_args(["hook", "send", "--help"])-- assert exc.value.code == 0- captured = capsys.readouterr()- assert "`vibe hook send` is a compatibility entrypoint." in captured.out- assert "New automation should use `vibe agent run`." in captured.out- assert "`vibe hook send` queues one deprecated asynchronous compatibility turn" in captured.out- assert "--post-to" not in captured.out- assert "`--message` and `--message-file` provide the one-shot async user message that will be queued immediately." in captured.out- assert "--session-id" in captured.out- assert "vibe agent run --session-id sesk8m4q2p7x --no-callback --message" in captured.out--def test_task_list_help_mentions_completed_one_shots_hidden_by_default(capsys) -> None:parser = cli.build_parser()@@ -459,21 +391,6 @@ def test_task_update_help_includes_partial_update_guidance(capsys) -> None:assert "Write cron weekdays as names (mon, tue, ... sun)." in captured.out-def test_hook_send_help_includes_examples_and_threadless_guidance(capsys) -> None:- parser = cli.build_parser()-- with pytest.raises(SystemExit) as exc:- parser.parse_args(["hook", "send", "--help"])-- assert exc.value.code == 0- captured = capsys.readouterr()- assert "`vibe hook send` queues one deprecated asynchronous compatibility turn" in captured.out- assert "--post-to" not in captured.out- assert "--deliver-key" not in captured.out- assert "--session-id" in captured.out- assert "vibe agent run --session-id sesk8m4q2p7x --no-callback" in captured.out--def test_agent_run_help_includes_fork_session_guidance(capsys) -> None:parser = cli.build_parser()@@ -485,7 +402,9 @@ def test_agent_run_help_includes_fork_session_guidance(capsys) -> None:assert "--fork-session FORK_SESSION" in captured.outassert "--fork-self" in captured.outassert "--sync" in captured.out- assert "--send-now" in captured.out+ assert "--send-now" not in captured.out+ assert "--create-session" not in captured.out+ assert "--async" not in captured.outassert "--same-scope" in captured.outassert "--scope-id" in captured.outassert "--visible" in captured.out@@ -495,10 +414,10 @@ def test_agent_run_help_includes_fork_session_guidance(capsys) -> None:assert "--fork-self forks this current Session." in captured.outassert "Forks keep the same backend, scope, and cwd as the source Session." in captured.outassert "vibe agent run --fork-self --message" in captured.out- assert "vibe agent run --session-id sesk8m4q2p7x --send-now --message" in captured.out- assert "vibe session queue list sesk8m4q2p7x" in captured.out- assert "vibe session queue remove sesk8m4q2p7x msg_queued123" in captured.out- assert "vibe session send-now sesk8m4q2p7x" in captured.out+ assert "vibe agent run --session-id sesk8m4q2p7x --message" in captured.out+ assert "vibe session queue list --session-id sesk8m4q2p7x" in captured.out+ assert "vibe session queue remove msg_queued123 --session-id sesk8m4q2p7x" in captured.out+ assert "vibe session send-now --session-id sesk8m4q2p7x" in captured.outassert "Agent runs are async by default. From an Avibe Agent shell, they return their final result to this conversation by default." in captured.outassert "vibe agent run --agent release-reviewer --message 'Review the latest deployment result.'" in captured.outassert (@@ -515,20 +434,7 @@ def test_agent_run_help_includes_fork_session_guidance(capsys) -> None:assert "Review the latest CI result and report back." in captured.outassert "--callback-session-id sescaller456 --message 'Review the latest CI result and report back.'" in captured.outassert "--no-callback --message 'Review the latest CI result and report back.'" not in captured.out- assert "Do not combine fork flags with --session-id or --create-session." in captured.out- assert "--create-session-per-run" not in captured.out---def test_agent_run_rejects_async_and_sync_together(capsys) -> None:- parser = cli.build_parser()-- with pytest.raises(SystemExit) as exc:- parser.parse_args(["agent", "run", "--async", "--sync", "--message", "hello"])-- assert exc.value.code == 2- payload = json.loads(capsys.readouterr().err)- assert payload["code"] == "invalid_arguments"- assert "not allowed with argument --async" in payload["error"]+ assert "Do not combine fork flags with --session-id." in captured.outdef test_agent_run_visible_sugar_sets_foreground_visibility() -> None:@@ -537,81 +443,24 @@ def test_agent_run_visible_sugar_sets_foreground_visibility() -> None:assert args.visibility == "foreground"-def test_agent_run_visible_conflicts_with_explicit_visibility(capsys) -> None:- parser = cli.build_parser()-- with pytest.raises(SystemExit) as exc:- parser.parse_args(- [- "agent",- "run",- "--agent",- "worker",- "--visible",- "--visibility",- "background",- "--message",- "hello",- ]- )-- assert exc.value.code == 2- payload = json.loads(capsys.readouterr().err)- assert payload["code"] == "invalid_arguments"- assert "--visibility" in payload["error"]- assert "--visible" in payload["error"]---def test_agent_run_runtime_rejects_async_and_sync_together() -> None:- args = SimpleNamespace(- agent="worker",- session_id=None,- fork_session=None,- fork_self=False,- create_session=False,- create_session_per_run=False,- same_scope=False,- scope_id=None,- deliver_key=None,- model=None,- reasoning_effort=None,- cwd=None,- post_to=None,- callback_session_id=None,- no_callback=True,- async_run=True,- sync_run=True,- wait_timeout=None,- message="hello",- message_file=None,- prompt=None,- prompt_file=None,- )-- result, payload = _capture_stderr_json(cli.cmd_agent_run, args)-- assert result == 1- assert payload["code"] == "conflicting_wait_policy"--def test_task_add_parse_error_is_structured_json(capsys) -> None:parser = cli.build_parser()with pytest.raises(SystemExit) as exc:- parser.parse_args(["task", "add", "--session-key", "slack::channel::C123"])+ parser.parse_args(["task", "add", "--session-id", "sesk8m4q2p7x"])assert exc.value.code == 2payload = json.loads(capsys.readouterr().err)assert payload["code"] == "invalid_arguments"assert payload["help_command"] == "vibe task add --help"- assert "--session-key SESSION_KEY" in payload["usage"]+ assert "--session-id SESSION_ID" in payload["usage"]-def test_task_remove_alias_parse_error_keeps_structured_guidance(capsys) -> None:+def test_task_remove_parse_error_keeps_structured_guidance(capsys) -> None:parser = cli.build_parser()with pytest.raises(SystemExit) as exc:- parser.parse_args(["task", "rm"])+ parser.parse_args(["task", "remove"])assert exc.value.code == 2payload = json.loads(capsys.readouterr().err)@@ -620,111 +469,8 @@ def test_task_remove_alias_parse_error_keeps_structured_guidance(capsys) -> Noneassert "task_id" in payload["error"]-def test_task_add_rejects_invalid_session_key_with_hint() -> None:- args = _parse_task_add(- [- "--session-key",- "slack::thread::123",- "--cron",- "0 * * * *",- "--message",- "hello",- ]- )-- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):- result, payload = _capture_stderr_json(cli.cmd_task_add, args)-- assert result == 1- assert payload["code"] == "invalid_session_key"- assert payload["example"] == "slack::channel::C123"---def test_task_add_rejects_conflicting_delivery_target_flags(capsys) -> None:- parser = cli.build_parser()-- with pytest.raises(SystemExit) as exc:- parser.parse_args(- [- "task",- "add",- "--session-key",- "slack::channel::C123",- "--post-to",- "channel",- "--deliver-key",- "slack::channel::C999",- "--cron",- "0 * * * *",- "--message",- "hello",- ]- )-- assert exc.value.code == 2- payload = json.loads(capsys.readouterr().err)- assert payload["code"] == "invalid_arguments"- assert "not allowed with argument --post-to" in payload["error"]- assert payload["help_command"] == "vibe task add --help"---def test_task_add_rejects_post_to_thread_without_thread_session_key() -> None:- args = _parse_task_add(- [- "--session-key",- "slack::channel::C123",- "--post-to",- "thread",- "--cron",- "0 * * * *",- "--message",- "hello",- ]- )-- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):- result, payload = _capture_stderr_json(cli.cmd_task_add, args)-- assert result == 1- assert payload["code"] == "invalid_delivery_target"---def test_task_add_rejects_cross_platform_deliver_key() -> None:- args = _parse_task_add(- [- "--session-key",- "slack::channel::C123",- "--deliver-key",- "discord::channel::C999",- "--cron",- "0 * * * *",- "--message",- "hello",- ]- )-- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack", "discord"})):- result, payload = _capture_stderr_json(cli.cmd_task_add, args)-- assert result == 1- assert payload["code"] == "invalid_delivery_target"- assert payload["details"] == {- "session_platform": "slack",- "delivery_platform": "discord",- }--def test_task_add_rejects_invalid_cron_with_example() -> None:- args = _parse_task_add(- [- "--session-key",- "slack::channel::C123",- "--cron",- "bad cron",- "--message",- "hello",- ]- )+ args = _parse_task_add(["--cron", "bad cron", "--shell", "true"])with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):result, payload = _capture_stderr_json(cli.cmd_task_add, args)@@ -749,7 +495,7 @@ def test_task_add_rejects_invalid_cron_with_example() -> None:],)def test_task_add_rejects_numeric_weekday_naming_both_readings(cron: str, readings: str | None) -> None:- args = _parse_task_add(["--session-key", "slack::channel::C123", "--cron", cron, "--message", "hello"])+ args = _parse_task_add(["--cron", cron, "--shell", "true"])with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):result, payload = _capture_stderr_json(cli.cmd_task_add, args)@@ -764,7 +510,7 @@ def test_task_add_rejects_numeric_weekday_naming_both_readings(cron: str, readin@pytest.mark.parametrize("cron", ["0 9 * * 5-1", "0 9 * * 0-7", "0 9 * * 7"])def test_task_add_reports_unparseable_numeric_weekday_as_invalid_cron(cron: str) -> None:- args = _parse_task_add(["--session-key", "slack::channel::C123", "--cron", cron, "--message", "hello"])+ args = _parse_task_add(["--cron", cron, "--shell", "true"])with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):result, payload = _capture_stderr_json(cli.cmd_task_add, args)@@ -773,24 +519,9 @@ def test_task_add_reports_unparseable_numeric_weekday_as_invalid_cron(cron: str)assert payload["code"] == "invalid_cron"-def test_task_add_numeric_weekday_rejection_follows_cli_language() -> None:- args = _parse_task_add(["--session-key", "slack::channel::C123", "--cron", "0 7 * * 6", "--message", "hello"])-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._configured_cli_language", return_value="zh"),- ):- result, payload = _capture_stderr_json(cli.cmd_task_add, args)-- assert result == 1- assert payload["code"] == "ambiguous_cron_weekday"- assert "星期" in payload["error"]- assert "Avibe(APScheduler)解析为 sun;标准 crontab(5) 解析为 sat" in payload["hint"]--@pytest.mark.parametrize("cron", ["0 7 * * sat", "0 9 * * mon-fri", "0 9 * * mon-sun/2", "0 9 1-7 * *", "*/5 * * * *"])def test_task_add_accepts_named_or_unrestricted_weekday(cron: str, capsys) -> None:- args = _parse_task_add(["--session-key", "slack::channel::C123", "--cron", cron, "--message", "hello"])+ args = _parse_task_add(["--cron", cron, "--shell", "true"])with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):assert cli.cmd_task_add(args) == 0@@ -821,18 +552,7 @@ def test_task_update_rejects_numeric_weekday_and_keeps_stored_schedule(tmp_path:def test_task_add_rejects_invalid_timezone() -> None:- args = _parse_task_add(- [- "--session-key",- "slack::channel::C123",- "--cron",- "0 * * * *",- "--message",- "hello",- "--timezone",- "Mars/Base",- ]- )+ args = _parse_task_add(["--cron", "0 * * * *", "--shell", "true", "--timezone", "Mars/Base"])with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):result, payload = _capture_stderr_json(cli.cmd_task_add, args)@@ -901,16 +621,7 @@ def test_remote_editor_task_add_persists_authorization_context(_bare_terminal_caller(monkeypatch)store_path = tmp_path / "scheduled_tasks.json"store = cli.ScheduledTaskStore(store_path)- args = _parse_task_add(- [- "--session-key",- "slack::channel::C123",- "--cron",- "0 * * * *",- "--message",- "hello",- ]- )+ args = _parse_task_add(["--cron", "0 * * * *", "--shell", "true"])caller_env = {"AVIBE_SESSION_ID": "sesCaller","AVIBE_RUN_ID": "runCaller",@@ -937,7 +648,7 @@ def test_remote_editor_task_add_persists_authorization_context():result = cli.cmd_task_add(args)- assert result == 0+ assert result == 0, capsys.readouterr().errpayload = json.loads(capsys.readouterr().out)# Persisted for the deferred run, hidden from the projection it prints.assert "resource_user_context" not in payload["definition"]["metadata"]@@ -2428,59 +2139,6 @@ def test_task_update_create_session_preserves_existing_cwd_without_cwd_flag(tmp_assert payload["definition"]["session_id"] != "sesOld"-def test_task_update_session_key_clears_previous_session_id(tmp_path: Path, capsys) -> None:- store_path = tmp_path / "scheduled_tasks.json"- store = cli.ScheduledTaskStore(store_path)- task = store.add_task(- session_key="",- session_id="sesk8m4q2p7x",- prompt="hello",- schedule_type="cron",- cron="0 * * * *",- timezone_name="Asia/Shanghai",- )- parser = cli.build_parser()- args = parser.parse_args(["task", "update", task.id, "--session-key", "slack::channel::C456"])-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._task_store", return_value=store),- ):- result = cli.cmd_task_update(args)-- assert result == 0- payload = json.loads(capsys.readouterr().out)- assert payload["definition"].get("session_id") is None- assert store.get_task(task.id).session_key == "slack::channel::C456"---def test_task_update_replaces_post_to_with_deliver_key(tmp_path: Path, capsys) -> None:- store_path = tmp_path / "scheduled_tasks.json"- store = cli.ScheduledTaskStore(store_path)- task = store.add_task(- session_key="slack::channel::C123::thread::171717.123",- prompt="hello",- schedule_type="cron",- cron="0 * * * *",- timezone_name="Asia/Shanghai",- post_to="channel",- )- parser = cli.build_parser()- args = parser.parse_args(["task", "update", task.id, "--deliver-key", "slack::channel::C999"])-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._task_store", return_value=store),- ):- result = cli.cmd_task_update(args)-- assert result == 0- payload = json.loads(capsys.readouterr().out)- assert payload["definition"]["id"] == task.id- stored = store.get_task(task.id)- assert (stored.post_to, stored.deliver_key) == (None, "slack::channel::C999")--def test_task_update_reset_delivery_preserves_creation_scope_metadata(tmp_path: Path, capsys) -> None:store_path = tmp_path / "scheduled_tasks.json"store = cli.ScheduledTaskStore(store_path)@@ -2517,14 +2175,19 @@ def test_task_update_reset_delivery_preserves_creation_scope_metadata(tmp_path:assert payload["definition"]["metadata"]["session_scope_id"] == "avibe::project::proj-reset-task"-def test_task_add_returns_reachability_warning_for_unbound_lark_dm(tmp_path: Path, capsys) -> None:- parser = cli.build_parser()- args = parser.parse_args(- ["task", "add", "--session-key", "lark::user::ou_123", "--cron", "0 * * * *", "--message", "hello"]+def test_task_add_returns_reachability_warning_for_unbound_lark_dm(+ tmp_path: Path, capsys, monkeypatch, sqlite_schema_db_factory+) -> None:+ _bare_terminal_caller(monkeypatch)+ db_path, agent_store = _caller_session_state(+ tmp_path, sqlite_schema_db_factory, session_id="sesLarkDm", platform="lark", scope_type="user", scope_key="ou_123")+ parser = cli.build_parser()+ args = parser.parse_args(["task", "add", "--session-id", "sesLarkDm", "--cron", "0 * * * *", "--message", "hello"])fake_store = SimpleNamespace(get_user=lambda *args, **kwargs: None)with (+ _cli_state(db_path, agent_store),patch("vibe.cli._ensure_config", return_value=_configured_v2({"lark"})),patch("vibe.cli._task_store", return_value=cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")),patch("core.services.settings.get_settings_store", return_value=fake_store),@@ -2536,180 +2199,6 @@ def test_task_add_returns_reachability_warning_for_unbound_lark_dm(tmp_path: Patassert payload["warnings"][0]["code"] == "lark_user_not_bound"-def test_hook_send_rejects_invalid_session_key_with_hint() -> None:- args = _parse_hook_send(["--session-key", "slack::thread::123", "--message", "hello"])-- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):- result, payload = _capture_stderr_json(cli.cmd_hook_send, args)-- assert result == 1- assert payload["code"] == "invalid_session_key"- assert payload["help_command"] == "vibe hook send --help"---def test_hook_send_deprecation_warning_names_callback_policy(tmp_path: Path, capsys) -> None:- args = _parse_hook_send(["--session-key", "slack::channel::C123", "--message", "hello"])-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._task_request_store", return_value=cli.TaskExecutionStore(tmp_path / "task_requests")),- ):- result = cli.cmd_hook_send(args)-- assert result == 0- payload = json.loads(capsys.readouterr().out)- assert "vibe hook send is deprecated" in payload["deprecation_warning"]- assert "--no-callback" in payload["deprecation_warning"]- assert "--callback-session-id <session-id>" in payload["deprecation_warning"]---def test_hook_send_guards_an_explicit_agent_inside_enqueue(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:- args = _parse_hook_send(- [- "--session-key",- "slack::channel::C123",- "--agent",- "worker",- "--message",- "hello",- ]- )- agent_store = cli.VibeAgentStore(sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite"))- agent = agent_store.create(name="worker", backend="codex")- captured: dict[str, object] = {}-- def enqueue_hook_send(**kwargs):- captured.update(kwargs)- return SimpleNamespace(id="run-hook", request_type="agent_run")-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._agent_store", return_value=agent_store),- patch(- "vibe.cli._task_request_store",- return_value=SimpleNamespace(enqueue_hook_send=enqueue_hook_send),- ),- ):- result = cli.cmd_hook_send(args)-- assert result == 0- assert json.loads(capsys.readouterr().out)["run_id"] == "run-hook"- assert captured["agent_name"] == agent.name- assert captured["expected_enabled_agent_id"] == agent.id---def test_hook_send_guards_the_implicit_default_agent_inside_enqueue(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:- args = _parse_hook_send(- [- "--session-key",- "slack::channel::C123",- "--message",- "hello",- ]- )- db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")- agent_store = cli.VibeAgentStore(db_path)- default_agent = agent_store.ensure_default_agent(backend="codex")- captured: dict[str, object] = {}-- def enqueue_hook_send(**kwargs):- captured.update(kwargs)- return SimpleNamespace(id="run-hook", request_type="agent_run")-- with (- patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),- patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._agent_store", return_value=agent_store),- patch(- "vibe.cli._task_request_store",- return_value=SimpleNamespace(enqueue_hook_send=enqueue_hook_send),- ),- ):- result = cli.cmd_hook_send(args)-- assert result == 0- assert json.loads(capsys.readouterr().out)["run_id"] == "run-hook"- assert captured["agent_name"] == default_agent.name- assert captured["expected_enabled_agent_id"] == default_agent.id---def test_hook_send_rejects_conflicting_delivery_target_flags(capsys) -> None:- parser = cli.build_parser()-- with pytest.raises(SystemExit) as exc:- parser.parse_args(- [- "hook",- "send",- "--session-key",- "slack::channel::C123",- "--post-to",- "channel",- "--deliver-key",- "slack::channel::C999",- "--message",- "hello",- ]- )-- assert exc.value.code == 2- payload = json.loads(capsys.readouterr().err)- assert payload["code"] == "invalid_arguments"- assert "not allowed with argument --post-to" in payload["error"]- assert payload["help_command"] == "vibe hook send --help"---def test_hook_send_rejects_cross_platform_deliver_key() -> None:- args = _parse_hook_send(- [- "--session-key",- "slack::channel::C123",- "--deliver-key",- "discord::channel::C999",- "--message",- "hello",- ]- )-- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack", "discord"})):- result, payload = _capture_stderr_json(cli.cmd_hook_send, args)-- assert result == 1- assert payload["code"] == "invalid_delivery_target"- assert payload["details"] == {- "session_platform": "slack",- "delivery_platform": "discord",- }---def test_hook_send_enqueues_request(tmp_path: Path, capsys) -> None:- args = _parse_hook_send(- [- "--session-key",- "slack::channel::C123::thread::171717.123",- "--post-to",- "channel",- "--message",- "hello",- ]- )- request_root = tmp_path / "task_requests"-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._task_request_store", return_value=cli.TaskExecutionStore(request_root)),- ):- result = cli.cmd_hook_send(args)-- assert result == 0- payload = json.loads(capsys.readouterr().out)- assert payload["ok"] is True- assert payload["session_key"] == "slack::channel::C123::thread::171717.123"- assert payload["post_to"] == "channel"- assert (request_root / "pending" / f"{payload['execution_id']}.json").exists()--def test_runs_cancel_running_agent_run_stops_live_turn_and_marks_canceled(monkeypatch,tmp_path: Path,@@ -2941,134 +2430,60 @@ def test_runs_cancel_running_agent_run_does_not_overwrite_already_finished_turn("ok": True,"session_id": "ses_already_finished","status": "run_settled",- "reason": "run_already_terminal",- },- }-- cancel_dispatch = AsyncMock(side_effect=settle_before_cancel)-- with (- patch("vibe.cli._task_request_store", return_value=request_store),- patch("vibe.internal_client.cancel_dispatch", cancel_dispatch),- ):- result = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))-- assert result == 0- cancel_dispatch.assert_awaited_once_with("ses_already_finished", run_id=request.id)- saved = request_store.get_run(request.id)- assert saved is not None- assert saved["status"] == "succeeded"- assert saved["completed_at"] is not None- assert saved["cancel_requested"] is False- payload = json.loads(capsys.readouterr().out)- assert payload["cancel_code"] == "run_already_settled"- assert payload["cancel_result"]["live_cancel_confirmed"] is False- assert payload["run"]["status"] == "succeeded"---def test_runs_cancel_queued_agent_run_does_not_call_live_controller(- monkeypatch,- tmp_path: Path,- capsys,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- request_store = cli.TaskExecutionStore()- request = request_store.enqueue_agent_run(- session_id="ses_queued_cancel",- message="queued work",- agent_name="worker",- )- cancel_dispatch = AsyncMock()-- with (- patch("vibe.cli._task_request_store", return_value=request_store),- patch("vibe.internal_client.cancel_dispatch", cancel_dispatch),- ):- result = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))-- assert result == 0- cancel_dispatch.assert_not_awaited()- saved = request_store.get_run(request.id)- assert saved is not None- assert saved["status"] == "canceled"- assert saved["cancel_requested"] is True- payload = json.loads(capsys.readouterr().out)- assert payload["cancel_code"] == "queued_canceled"- assert payload["run"]["status"] == "canceled"---def test_hook_send_allows_unresolved_legacy_scope_backend(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:- db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")- agent_store = cli.VibeAgentStore(db_path)- default_agent = agent_store.ensure_default_agent(backend="claude")- agent_store.create(name="codex", backend="opencode")- agent_store.close()- request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- from storage.importer import ensure_sqlite_state- from storage.models import scope_settings- from storage.settings_service import upsert_scope-- ensure_sqlite_state(db_path=db_path, primary_platform="slack")- with cli.create_sqlite_engine(db_path).begin() as conn:- now = "2026-05-22T00:00:00+00:00"- scope_id = upsert_scope(conn, "slack", "channel", "C123", now=now)- conn.execute(- scope_settings.insert().values(- scope_id=scope_id,- enabled=1,- role=None,- workdir=None,- agent_name=None,- agent_backend="codex",- agent_variant=None,- model=None,- reasoning_effort=None,- require_mention=None,- settings_version=1,- settings_json=json.dumps({"routing": {"agent_backend": "codex"}}),- created_at=now,- updated_at=now,- )- )- args = _parse_hook_send(["--session-key", "slack::channel::C123", "--message", "hello"])+ "reason": "run_already_terminal",+ },+ }++ cancel_dispatch = AsyncMock(side_effect=settle_before_cancel)with (- patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),- patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),patch("vibe.cli._task_request_store", return_value=request_store),+ patch("vibe.internal_client.cancel_dispatch", cancel_dispatch),):- result = cli.cmd_hook_send(args)+ result = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))assert result == 0+ cancel_dispatch.assert_awaited_once_with("ses_already_finished", run_id=request.id)+ saved = request_store.get_run(request.id)+ assert saved is not None+ assert saved["status"] == "succeeded"+ assert saved["completed_at"] is not None+ assert saved["cancel_requested"] is Falsepayload = json.loads(capsys.readouterr().out)- queued = json.loads((request_store.pending_dir / f"{payload['run']['id']}.json").read_text())- assert queued["session_key"] == "slack::channel::C123"- assert queued["agent_name"] == default_agent.name+ assert payload["cancel_code"] == "run_already_settled"+ assert payload["cancel_result"]["live_cancel_confirmed"] is False+ assert payload["run"]["status"] == "succeeded"-def test_hook_send_returns_reachability_warning_for_unbound_lark_dm(tmp_path: Path, capsys) -> None:- args = _parse_hook_send(- [- "--session-key",- "lark::user::ou_123",- "--message",- "hello",- ]+def test_runs_cancel_queued_agent_run_does_not_call_live_controller(+ monkeypatch,+ tmp_path: Path,+ capsys,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ request_store = cli.TaskExecutionStore()+ request = request_store.enqueue_agent_run(+ session_id="ses_queued_cancel",+ message="queued work",+ agent_name="worker",)- request_root = tmp_path / "task_requests"- fake_store = SimpleNamespace(get_user=lambda *args, **kwargs: None)+ cancel_dispatch = AsyncMock()with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"lark"})),- patch("vibe.cli._task_request_store", return_value=cli.TaskExecutionStore(request_root)),- patch("core.services.settings.get_settings_store", return_value=fake_store),+ patch("vibe.cli._task_request_store", return_value=request_store),+ patch("vibe.internal_client.cancel_dispatch", cancel_dispatch),):- result = cli.cmd_hook_send(args)+ result = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))assert result == 0+ cancel_dispatch.assert_not_awaited()+ saved = request_store.get_run(request.id)+ assert saved is not None+ assert saved["status"] == "canceled"+ assert saved["cancel_requested"] is Truepayload = json.loads(capsys.readouterr().out)- assert payload["warnings"][0]["code"] == "lark_user_not_bound"+ assert payload["cancel_code"] == "queued_canceled"+ assert payload["run"]["status"] == "canceled"def test_agent_run_standalone_async_reserves_background_session(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:@@ -3076,7 +2491,7 @@ def test_agent_run_standalone_async_reserves_background_session(tmp_path: Path,agent_store = cli.VibeAgentStore(db_path)agent = agent_store.create(name="worker", backend="codex")request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hello"])+ args = _parse_agent_run(["--agent", "worker", "--no-callback", "--message", "hello"])with (patch("vibe.cli._agent_store", return_value=agent_store),@@ -3179,7 +2594,7 @@ def test_agent_run_caller_scope_default_keeps_caller_cwd_and_same_scope_uses_scoimplicit = run([])explicit = run(["--same-scope"])- visible = run(["--visibility", "foreground"])+ visible = run(["--visible"])with engine.connect() as conn:rows = {@@ -3209,80 +2624,7 @@ def test_agent_run_caller_scope_default_keeps_caller_cwd_and_same_scope_uses_scoassert rows[visible["run"]["session_id"]].workdir == str(invocation_cwd)-def test_agent_run_create_session_uses_scope_anchor_for_channel_deliver_key(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:- db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")- agent_store = cli.VibeAgentStore(db_path)- agent_store.create(name="worker", backend="codex")- request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- args = _parse_agent_run(- [- "--agent",- "worker",- "--async",- "--no-callback",- "--create-session",- "--deliver-key",- "slack::channel::C123",- "--message",- "hello",- ]- )-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._agent_store", return_value=agent_store),- patch("vibe.cli._task_request_store", return_value=request_store),- patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),- ):- result = cli.cmd_agent_run(args)-- assert result == 0- payload = json.loads(capsys.readouterr().out)- target = cli.resolve_session_id_target(payload["run"]["session_id"], db_path=db_path)- assert target.session_key.to_key() == "slack::channel::C123"- assert target.session_key.thread_id is None- assert target.session_anchor.startswith("slack_C123:run_")---def test_agent_run_create_session_preserves_legacy_thread_deliver_key(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:- db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")- agent_store = cli.VibeAgentStore(db_path)- agent_store.create(name="worker", backend="codex")- request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- args = _parse_agent_run(- [- "--agent",- "worker",- "--async",- "--no-callback",- "--create-session",- "--deliver-key",- "slack::channel::C123::thread::171717.123",- "--message",- "hello",- ]- )-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._agent_store", return_value=agent_store),- patch("vibe.cli._task_request_store", return_value=request_store),- patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),- ):- result = cli.cmd_agent_run(args)-- assert result == 0- payload = json.loads(capsys.readouterr().out)- target = cli.resolve_session_id_target(payload["run"]["session_id"], db_path=db_path)- assert target.session_key.to_key() == "slack::channel::C123::thread::171717.123"- assert target.session_key.thread_id == "171717.123"- assert target.session_anchor.startswith("slack_171717.123:run_")- queued = request_store.get_run(payload["run"]["id"])- assert queued is not None- assert queued["deliver_key"] == "slack::channel::C123::thread::171717.123"---def test_agent_run_create_session_scope_id_uses_unique_project_anchors(tmp_path: Path, capsys) -> None:+def test_agent_run_scope_id_uses_unique_project_anchors(tmp_path: Path, capsys) -> None:from sqlalchemy import selectfrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state@@ -3330,9 +2672,7 @@ def test_agent_run_create_session_scope_id_uses_unique_project_anchors(tmp_path:["--agent","worker",- "--async","--no-callback",- "--create-session","--scope-id",scope_id,"--message",@@ -3367,7 +2707,7 @@ def test_agent_run_standalone_does_not_create_platform_pseudo_scope(tmp_path: Paagent_store = cli.VibeAgentStore(db_path)agent_store.create(name="worker", backend="codex")request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hello"])+ args = _parse_agent_run(["--agent", "worker", "--no-callback", "--message", "hello"])with (patch("vibe.cli._agent_store", return_value=agent_store),@@ -3391,28 +2731,6 @@ def test_agent_run_standalone_does_not_create_platform_pseudo_scope(tmp_path: Paassert row == (None, "background")-def test_agent_run_rejects_deprecated_prompt_argument(tmp_path: Path, sqlite_schema_db_factory) -> None:- db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")- agent_store = cli.VibeAgentStore(db_path)- agent_store.create(name="worker", backend="codex")- args = _parse_agent_run(["--agent", "worker", "--async", "--prompt", "hello"])-- with patch("vibe.cli._agent_store", return_value=agent_store):- result, payload = _capture_stderr_json(cli.cmd_agent_run, args)-- assert result == 1- assert payload["code"] == "deprecated_prompt_argument"---def test_agent_run_rejects_per_run_for_direct_invocation() -> None:- args = _parse_agent_run(["--agent", "worker", "--create-session-per-run", "--message", "hello"])-- result, payload = _capture_stderr_json(cli.cmd_agent_run, args)-- assert result == 1- assert payload["code"] == "invalid_session_policy"--def test_agent_run_rejects_cross_backend_agent_for_existing_session(tmp_path: Path, sqlite_schema_db_factory) -> None:db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")agent_store = cli.VibeAgentStore(db_path)@@ -3466,7 +2784,6 @@ def test_agent_run_existing_session_allows_matching_agent_hint(tmp_path: Path, c["--agent","codex-worker",- "--async","--no-callback","--session-id",session_id,@@ -3518,103 +2835,6 @@ def test_agent_run_rejects_different_same_backend_agent_for_existing_session(tmpassert payload["code"] == "agent_session_agent_mismatch"-def test_agent_run_rejects_post_to_thread_for_threadless_session_before_enqueue(tmp_path: Path, sqlite_schema_db_factory) -> None:- db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")- # The raw schema template carries no import marker, so the first CLI call to- # ``_ensure_cli_sqlite_state`` would run the JSON importer over this database- # and drop the rows seeded below. Establish the state first, as the rest of- # this module does, then seed what the command is meant to find.- ensure_sqlite_state(db_path=db_path, primary_platform="slack")- agent_store = cli.VibeAgentStore(db_path)- agent_store.create(name="worker", backend="codex")- request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- from storage.sessions_service import SQLiteSessionsService-- service = SQLiteSessionsService(db_path)- try:- session_id = service.reserve_agent_session(- scope_key="slack::C123",- agent_backend="codex",- session_anchor="slack_C123",- agent_name="worker",- )- finally:- service.close()- args = _parse_agent_run(["--async", "--session-id", session_id, "--post-to", "thread", "--message", "hello"])-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._agent_store", return_value=agent_store),- patch("vibe.cli._task_request_store", return_value=request_store),- patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),- ):- result, payload = _capture_stderr_json(cli.cmd_agent_run, args)-- assert result == 1- assert payload["code"] == "invalid_delivery_target"- assert request_store.list_pending() == []---def test_agent_run_rejects_cross_platform_deliver_key_before_enqueue(tmp_path: Path, sqlite_schema_db_factory) -> None:- db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")- # The raw schema template carries no import marker, so the first CLI call to- # ``_ensure_cli_sqlite_state`` would run the JSON importer over this database- # and drop the rows seeded below. Establish the state first, as the rest of- # this module does, then seed what the command is meant to find.- ensure_sqlite_state(db_path=db_path, primary_platform="slack")- agent_store = cli.VibeAgentStore(db_path)- agent_store.create(name="worker", backend="codex")- request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- from storage.sessions_service import SQLiteSessionsService-- service = SQLiteSessionsService(db_path)- try:- session_id = service.reserve_agent_session(- scope_key="slack::C123",- agent_backend="codex",- session_anchor="slack_C123",- agent_name="worker",- )- finally:- service.close()- args = _parse_agent_run(- [- "--async",- "--session-id",- session_id,- "--deliver-key",- "discord::channel::C999",- "--message",- "hello",- ]- )-- with (- patch("vibe.cli._agent_store", return_value=agent_store),- patch("vibe.cli._task_request_store", return_value=request_store),- patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack", "discord"})),- ):- result, payload = _capture_stderr_json(cli.cmd_agent_run, args)-- assert result == 1- assert payload["code"] == "invalid_delivery_target"- assert payload["details"] == {- "session_platform": "slack",- "delivery_platform": "discord",- }- assert request_store.list_pending() == []---def test_agent_run_rejects_delivery_options_without_session_policy() -> None:- args = _parse_agent_run(["--agent", "worker", "--async", "--post-to", "channel", "--message", "hello"])-- result, payload = _capture_stderr_json(cli.cmd_agent_run, args)-- assert result == 1- assert payload["code"] == "delivery_target_without_session_policy"--def test_agent_run_existing_session_uses_session_agent_when_agent_omitted(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")# The raw schema template carries no import marker, so the first CLI call to@@ -3637,7 +2857,7 @@ def test_agent_run_existing_session_uses_session_agent_when_agent_omitted(tmp_pa)finally:service.close()- args = _parse_agent_run(["--async", "--no-callback", "--session-id", session_id, "--message", "hello"])+ args = _parse_agent_run(["--no-callback", "--session-id", session_id, "--message", "hello"])with (patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),@@ -3664,20 +2884,7 @@ def test_agent_run_rejects_default_async_wait_timeout_combo() -> None:assert "--sync" in payload["hint"]-def test_agent_create_accepts_effort_alias(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:- db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")- agent_store = cli.VibeAgentStore(db_path)- args = _parse_agent(["create", "worker", "--backend", "codex", "--effort", "high"])-- with patch("vibe.cli._agent_store", return_value=agent_store):- result = cli.cmd_agent_create(args)-- assert result == 0- payload = json.loads(capsys.readouterr().out)- assert payload["agent"]["reasoning_effort"] == "high"---def test_agent_create_localizes_reserved_name_error(tmp_path: Path, sqlite_schema_db_factory) -> None:+def test_agent_create_reserved_name_error_is_english_under_a_zh_ui(tmp_path: Path, sqlite_schema_db_factory) -> None:agent_store = cli.VibeAgentStore(sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite"))args = _parse_agent(["create", "_hidden", "--backend", "codex"])@@ -3689,8 +2896,8 @@ def test_agent_create_localizes_reserved_name_error(tmp_path: Path, sqlite_schemassert result == 1assert payload["code"] == "agent_name_reserved"- assert payload["error"] == "Agent 名称不能以下划线 `_` 开头;该命名空间由 Avibe 保留。"- assert payload["hint"] == "请选择不以下划线 `_` 开头的 Agent 名称。"+ assert payload["error"] == "Agent names starting with `_` are reserved for Avibe."+ assert payload["hint"] == "Choose an Agent name that does not start with `_`."def test_agent_default_cli_sets_default_agent(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:@@ -4196,7 +3403,7 @@ def test_task_add_create_per_run_ignores_unresolved_legacy_scope_backend(tmp_patargs = _parse_task_add(["--create-session-per-run",- "--deliver-key",+ "--scope-id","slack::channel::C123","--cron","0 * * * *",@@ -4228,37 +3435,6 @@ def test_task_add_create_per_run_ignores_unresolved_legacy_scope_backend(tmp_patassert captured["expected_enabled_agent_id"] == default_agent.id-def test_task_add_rejects_deprecated_prompt_argument() -> None:- args = _parse_task_add(- [- "--session-key",- "slack::channel::C123",- "--cron",- "0 * * * *",- "--prompt",- "hello",- ]- )-- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):- result, payload = _capture_stderr_json(cli.cmd_task_add, args)-- assert result == 1- assert payload["code"] == "deprecated_prompt_argument"- assert "--message" in payload["hint"]---def test_hook_send_rejects_deprecated_prompt_argument() -> None:- args = _parse_hook_send(["--session-key", "slack::channel::C123", "--prompt", "hello"])-- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):- result, payload = _capture_stderr_json(cli.cmd_hook_send, args)-- assert result == 1- assert payload["code"] == "deprecated_prompt_argument"- assert "--message" in payload["hint"]--def test_task_remove_alias_parses_to_remove_command() -> None:parser = cli.build_parser()args = parser.parse_args(["task", "remove", "task-123"])@@ -4268,15 +3444,6 @@ def test_task_remove_alias_parses_to_remove_command() -> None:assert args.task_id == "task-123"-def test_task_hidden_aliases_still_parse() -> None:- parser = cli.build_parser()- list_args = parser.parse_args(["task", "ls"])- remove_args = parser.parse_args(["task", "rm", "task-123"])-- assert list_args.task_command == "ls"- assert remove_args.task_command == "rm"--def _reclaim_bound_definitions_now(session_id: str, *, mode: str, reason: str) -> dict[str, int]:"""Run the shared teardown reclaim against the isolated state database.@@ -4506,23 +3673,9 @@ def _reserved_session_cli_db(tmp_path: Path, sqlite_schema_db_factory):return db_path, agent_store, ordinary- ("language", "expected_hint"),- [- (- "en",- "This session only receives Avibe's workspace failure notifications — it does not accept messages.",- ),- (- "zh",- "该会话只接收 Avibe 的工作区失败通知,不接受发送消息。",- ),- ],-)-def test_reserved_session_cli_hint_uses_the_configured_backend_locale(- language: str,- expected_hint: str,-) -> None:[email protected]("language", ["en", "zh"])+def test_reserved_session_cli_hint_is_english_whatever_the_ui_language(language: str) -> None:+ expected_hint = "This session only receives Avibe's workspace failure notifications — it does not accept messages."exc = cli.UnresolvableSessionTarget("reserved",session_id="ses-workspace-notices",@@ -4675,7 +3828,6 @@ def test_agent_run_refuses_the_reserved_session_with_no_side_effects(request_store = cli.TaskExecutionStore(tmp_path / "task_requests")args = _parse_agent_run([- "--async","--no-callback","--session-id","ses-workspace-notices",@@ -4730,7 +3882,7 @@ def test_agent_run_refuses_the_reserved_session_with_no_side_effects(# --- positive control: the ordinary session still runs ------------------ok_args = _parse_agent_run(- ["--async", "--no-callback", "--session-id", ordinary, "--message", "hello"]+ ["--no-callback", "--session-id", ordinary, "--message", "hello"])with (patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),@@ -4800,7 +3952,15 @@ def _command_task_store(tmp_path: Path):return cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")-def _caller_session_state(tmp_path: Path, sqlite_schema_db_factory, *, session_id: str = "sesCaller"):+def _caller_session_state(+ tmp_path: Path,+ sqlite_schema_db_factory,+ *,+ session_id: str = "sesCaller",+ platform: str = "avibe",+ scope_type: str = "project",+ scope_key: str = "proj-command-task",+):"""A migrated CLI state DB holding one active Session owned by an enabled Agent."""db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")@@ -4813,7 +3973,7 @@ def _caller_session_state(tmp_path: Path, sqlite_schema_db_factory, *, session_iensure_sqlite_state(db_path=db_path, primary_platform="avibe")with cli.create_sqlite_engine(db_path).begin() as conn:now = "2026-06-28T00:00:00+00:00"- scope_id = upsert_scope(conn, "avibe", "project", "proj-command-task", now=now)+ scope_id = upsert_scope(conn, platform, scope_type, scope_key, now=now)conn.execute(agent_sessions.insert().values(id=session_id,@@ -4833,6 +3993,18 @@ def _caller_session_state(tmp_path: Path, sqlite_schema_db_factory, *, session_ireturn db_path, agent_store+def _cli_state(db_path: Path, agent_store):+ """Point the CLI at a test-owned state DB and Agent store."""++ from contextlib import ExitStack++ stack = ExitStack()+ stack.enter_context(patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent))+ stack.enter_context(patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path))+ stack.enter_context(patch("vibe.cli._agent_store", return_value=agent_store))+ return stack++# --- parse forms -----------------------------------------------------------@@ -4959,13 +4131,10 @@ def test_task_add_requires_a_message_or_a_command(monkeypatch) -> None:"flag_argv,flag_name",[(["--session-id", "sesTarget"], "--session-id"),- (["--session-key", "slack::channel::C123"], "--session-key"),(["--create-session"], "--create-session"),(["--create-session-per-run"], "--create-session-per-run"),(["--scope-id", "avibe::project::proj-x"], "--scope-id"),(["--agent", "codex"], "--agent"),- (["--post-to", "channel"], "--post-to"),- (["--deliver-key", "slack::channel::C123"], "--deliver-key"),],)def test_task_add_rejects_session_flags_for_pure_command_task(@@ -5306,17 +4475,17 @@ def test_task_add_command_argv_persists_the_argv_list(def test_task_add_message_task_stores_no_command_fields(- tmp_path: Path, capsys, monkeypatch+ tmp_path: Path, capsys, monkeypatch, sqlite_schema_db_factory) -> None:"""Regression guard: the message lane must be untouched by the command flags."""_bare_terminal_caller(monkeypatch)+ db_path, agent_store = _caller_session_state(tmp_path, sqlite_schema_db_factory)store = _command_task_store(tmp_path)- args = _parse_task_add(- ["--session-key", "slack::channel::C123", "--cron", "0 * * * *", "--message", "morning briefing"]- )+ args = _parse_task_add(["--session-id", "sesCaller", "--cron", "0 * * * *", "--message", "morning briefing"])with (+ _cli_state(db_path, agent_store),patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),patch("vibe.cli._task_store", return_value=store),):@@ -5586,7 +4755,7 @@ def test_task_resume_rejects_orphaned_owner_without_execution_target(with (patch("vibe.cli._task_store", return_value=store),- patch("vibe.cli._configured_cli_language", return_value="zh"),+ patch("vibe.cli.V2Config.load", return_value=SimpleNamespace(language="zh")),):result, payload = _capture_stderr_json(cli.cmd_task_set_enabled,@@ -5596,10 +4765,10 @@ def test_task_resume_rejects_orphaned_owner_without_execution_target(assert result == 1assert payload["code"] == "task_owner_session_unavailable"- assert payload["error"] == "这个 Task 的管理 Session 已不可用。"+ assert payload["error"] == "This Task's managing Session is no longer available."assert payload["hint"] == (- "请从可用的 Agent Session 创建替代 Task,再用 "- f"`vibe task remove {task.id}` 删除这条失去管理者的定义。"+ "Create a replacement Task from an available Agent Session, then remove this orphaned definition with "+ f"`vibe task remove {task.id}`.")assert payload["details"] == {"task_id": task.id,@@ -5635,7 +4804,7 @@ def _run_on_new_session(tmp_path: Path, capsys, db_path: Path, agent_store, requside_effect=lambda session_id: tmp_path / "show" / session_id,),):- result = cli.cmd_agent_run(_parse_agent_run(["--async", "--no-callback", *argv]))+ result = cli.cmd_agent_run(_parse_agent_run(["--no-callback", *argv]))captured = capsys.readouterr()return result, json.loads(captured.out if result == 0 else captured.err)@@ -5681,55 +4850,50 @@ def test_agent_run_starts_a_new_session_on_a_chosen_model_that_its_later_turns_k@pytest.mark.parametrize(- ("defaults", "extra", "catalog", "language", "message"),+ ("defaults", "extra", "catalog", "message"),[- ({}, ["--model", "claude-opus-9"], None, "en", "model 'claude-opus-9' is not in the vibey model catalog"),+ ({}, ["--model", "claude-opus-9"], None, "model 'claude-opus-9' is not in the vibey model catalog"),({},["--model", "claude-opus-5-5", "--reasoning-effort", "medium"],None,- "en","reasoning_effort 'medium' is not valid for model 'claude-opus-5-5'",),# A model the menu lists with no efforts takes none.- ({}, ["--model", "gpt-6-astra", "--reasoning-effort", "high"], None, "en",+ ({}, ["--model", "gpt-6-astra", "--reasoning-effort", "high"], None,"reasoning_effort 'high' is not valid for model 'gpt-6-astra'"),# The pair the Session would run on: an effort override over the Agent's default model...- ({"model": "claude-opus-5-5"}, ["--reasoning-effort", "medium"], None, "en",+ ({"model": "claude-opus-5-5"}, ["--reasoning-effort", "medium"], None,"reasoning_effort 'medium' is not valid for model 'claude-opus-5-5'"),# ...and a model override over the Agent's default effort.- ({"model": "claude-opus-5-5", "reasoning_effort": "xhigh"}, ["--model", "gpt-6-astra"], None, "en",+ ({"model": "claude-opus-5-5", "reasoning_effort": "xhigh"}, ["--model", "gpt-6-astra"], None,"reasoning_effort 'xhigh' is not valid for model 'gpt-6-astra'"),# A menu that cannot be loaded vouches for nothing.- ({}, ["--model", "claude-opus-5-5"], {"ok": False, "error": "config_unavailable"}, "en",+ ({}, ["--model", "claude-opus-5-5"], {"ok": False, "error": "config_unavailable"},"the vibey model catalog could not be loaded, so the model and reasoning effort cannot be checked"),- ({}, ["--model", "claude-opus-9"], None, "zh", "模型 'claude-opus-9' 不在 vibey 的模型目录中"),],ids=["unknown-model", "effort-the-model-does-not-take", "effort-on-a-model-that-takes-none",- "effort-over-the-agents-model", "model-over-the-agents-effort", "menu-unavailable", "zh"],+ "effort-over-the-agents-model", "model-over-the-agents-effort", "menu-unavailable"],)def test_agent_run_refuses_a_vibey_model_its_menu_does_not_offer_and_keeps_no_session(- tmp_path: Path, capsys, sqlite_schema_db_factory, defaults, extra, catalog, language, message+ tmp_path: Path, capsys, sqlite_schema_db_factory, defaults, extra, catalog, message) -> None:"""The effective pair a new Vibey Session would run on (each override over the Agent's default) is checked against- the Model Hub menu, which is authoritative: a pair it does not offer, or a menu that cannot load, is refused in the- caller's language with the catalog hint; the reserved Session is released and no run is queued."""+ the Model Hub menu, which is authoritative: a pair it does not offer, or a menu that cannot load, is refused with the+ catalog hint; the reserved Session is released and no run is queued."""db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")agent_store = cli.VibeAgentStore(db_path)agent_store.create(name="worker", backend="vibey", **defaults)request_store = cli.TaskExecutionStore(tmp_path / "task_requests")- with (- patch("vibe.cli._configured_cli_language", return_value=language),- patch.dict(_CATALOGS, {"vibey": catalog} if catalog is not None else {}),- ):+ with patch.dict(_CATALOGS, {"vibey": catalog} if catalog is not None else {}):result, payload = _run_on_new_session(tmp_path, capsys, db_path, agent_store, request_store, ["--agent", "worker", *extra, "--message", "hi"])assert result == 1assert (payload["code"], payload["error"]) == ("session_model_unavailable", message)- assert payload["hint"] == cli.i18n_t("harness.cli.agentRunModel.catalogHint", language, agent="worker")+ assert payload["hint"] == "Run `vibe agent models worker` to list valid models and reasoning efforts."with sqlite3.connect(db_path) as conn:assert conn.execute("select count(*) from agent_sessions").fetchone() == (0,)assert not list(request_store.pending_dir.glob("*.json"))diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.pyindex 2f445a918..da18cfca5 100644--- a/tests/test_cli_watch_command.py+++ b/tests/test_cli_watch_command.py@@ -106,7 +106,9 @@ def test_watch_add_help_mentions_shell_and_lifetime_timeout(capsys) -> None:assert "--lifetime-timeout" in captured.outassert "vibe watch add --session-id sesk8m4q2p7x --message 'The export finished. Inspect it and continue.'" in captured.outassert "watches follow up in this conversation by default" in captured.out- assert "Prefer --message or --message-file for follow-up instructions" in captured.out+ assert "Use --message or --message-file for follow-up instructions." in captured.out+ assert "--prefix" not in captured.out+ assert "--session-key" not in captured.outassert "Terminal failures also send a follow-up and disable the watch." in captured.outassert "an allowed `--retry-exit-code` keeps waiting" in captured.outassert "A once Watch stops after its first event" in captured.out@@ -198,15 +200,7 @@ def test_watch_list_help_describes_bounded_history(capsys) -> None:def test_watch_add_parser_keeps_top_level_command_name() -> None:- args = _parse_watch_add(- [- "--session-key",- "slack::channel::C123",- "--",- "python3",- "wait.py",- ]- )+ args = _parse_watch_add(["--session-id", "sesk8m4q2p7x", "--", "python3", "wait.py"])assert args.command == "watch"assert args.watch_command == "add"@@ -222,7 +216,7 @@ def test_watch_update_parser_accepts_argv_command_replacement() -> None:def test_watch_add_missing_command_is_structured_json() -> None:- args = _parse_watch_add(["--session-key", "slack::channel::C123"])+ args = _parse_watch_add(["--session-id", "sesk8m4q2p7x"])with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):result, payload = _capture_stderr_json(cli.cmd_watch_add, args)@@ -236,10 +230,11 @@ def test_watch_add_accepts_lifetime_timeout_for_retrying_once_watch(tmp_path: Path,capsys,) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)args = _parse_watch_add([- "--session-key",- "slack::channel::C123",+ "--session-id",+ session_id,"--lifetime-timeout","10","--shell",@@ -268,11 +263,12 @@ def test_watch_add_accepts_lifetime_timeout_for_retrying_once_watch(assert payload["definition"]["lifetime_timeout_seconds"] == 10-def test_watch_add_rejects_missing_cwd() -> None:+def test_watch_add_rejects_missing_cwd(tmp_path: Path) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)args = _parse_watch_add([- "--session-key",- "slack::channel::C123",+ "--session-id",+ session_id,"--cwd","/tmp/definitely-missing-watch-dir","--shell",@@ -322,7 +318,7 @@ def test_watch_add_create_per_run_ignores_unresolved_legacy_scope_backend(tmp_paargs = _parse_watch_add(["--create-session-per-run",- "--deliver-key",+ "--scope-id","slack::channel::C123","--shell","echo done",@@ -415,15 +411,16 @@ def test_watch_add_releases_create_once_session_when_definition_write_fails(def test_watch_add_creates_shell_watch(tmp_path: Path, capsys) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")args = _parse_watch_add([- "--session-key",- "slack::channel::C123",+ "--session-id",+ session_id,"--name","Wait for export",- "--prefix",+ "--message","Export finished.","--shell","python3 scripts/wait.py",@@ -453,14 +450,15 @@ def test_remote_editor_watch_add_starts_and_persists_authorization_context(tmp_path: Path,capsys,) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)store_path = tmp_path / "watches.json"runtime_path = tmp_path / "watch_runtime.json"store = ManagedWatchStore(store_path)runtime_store = WatchRuntimeStateStore(runtime_path)args = _parse_watch_add([- "--session-key",- "slack::channel::C123",+ "--session-id",+ session_id,"--shell","python3 scripts/wait.py",]@@ -736,12 +734,13 @@ def test_watch_add_defaults_target_to_caller_session(tmp_path: Path, capsys) ->def test_watch_add_accepts_message_template(tmp_path: Path, capsys) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")args = _parse_watch_add([- "--session-key",- "slack::channel::C123",+ "--session-id",+ session_id,"--message","Summarize the waiter output.","--shell",@@ -764,12 +763,13 @@ def test_watch_add_accepts_message_template(tmp_path: Path, capsys) -> None:def test_watch_add_creates_exec_watch_with_retry_codes(tmp_path: Path, capsys) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")args = _parse_watch_add([- "--session-key",- "slack::channel::C123",+ "--session-id",+ session_id,"--forever","--timeout","600",@@ -816,12 +816,13 @@ def test_watch_add_timeout_round_trips_through_persisted_read(timeout_args: list[str],expected_timeout: float,) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)store = ManagedWatchStore()runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")args = _parse_watch_add([- "--session-key",- "slack::channel::C123",+ "--session-id",+ session_id,*timeout_args,"--shell","exit 75",@@ -856,14 +857,15 @@ def test_watch_add_timeout_round_trips_through_persisted_read(def test_watch_add_persists_absolute_cwd(tmp_path: Path, capsys, monkeypatch: pytest.MonkeyPatch) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")workdir = tmp_path / "repo"workdir.mkdir()args = _parse_watch_add([- "--session-key",- "slack::channel::C123",+ "--session-id",+ session_id,"--cwd",str(workdir.relative_to(tmp_path)),"--shell",@@ -887,12 +889,13 @@ def test_watch_add_persists_absolute_cwd(tmp_path: Path, capsys, monkeypatch: pydef test_watch_add_returns_structured_error_when_startup_fails(tmp_path: Path) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")args = _parse_watch_add([- "--session-key",- "slack::channel::C123",+ "--session-id",+ session_id,"--shell","python3 scripts/wait.py",]@@ -1367,6 +1370,7 @@ def test_watch_pause_resume_and_remove_update_store(tmp_path: Path, capsys) -> Ndef test_watch_update_renames_and_retargets_watch(tmp_path: Path, capsys) -> None:+ session_id = _create_bare_agent_session(workdir=tmp_path)store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")watch = store.add_watch(@@ -1389,11 +1393,9 @@ def test_watch_update_renames_and_retargets_watch(tmp_path: Path, capsys) -> Nonwatch.id,"--name","Watch deploy",- "--session-key",- "slack::channel::C456",- "--post-to",- "channel",- "--prefix",+ "--session-id",+ session_id,+ "--message","Deploy finished.","--forever","--timeout",@@ -1422,10 +1424,9 @@ def test_watch_update_renames_and_retargets_watch(tmp_path: Path, capsys) -> Nonpayload = json.loads(capsys.readouterr().out)assert payload["definition"]["id"] == watch.idassert payload["definition"]["name"] == "Watch deploy"+ assert payload["definition"]["session_id"] == session_idassert payload["definition"]["message"] == "Deploy finished."assert {"session_key", "post_to", "deliver_key", "prefix"}.isdisjoint(payload["definition"])- stored = store.get_watch(watch.id)- assert (stored.session_key, stored.post_to) == ("slack::channel::C456", "channel")assert payload["definition"]["mode"] == "forever"assert payload["definition"]["timeout_seconds"] == 1200assert payload["definition"]["lifetime_timeout_seconds"] == 7200@@ -1467,40 +1468,6 @@ def test_watch_update_accepts_zero_timeout(tmp_path: Path, capsys) -> None:assert store.get_watch(watch.id).timeout_seconds == 0-def test_watch_update_session_key_clears_previous_session_id(tmp_path: Path, capsys) -> None:- store = ManagedWatchStore(tmp_path / "watches.json")- runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")- watch = store.add_watch(- name="Watch CI",- session_key="",- session_id="sesk8m4q2p7x",- command=["python3", "wait.py"],- shell_command=None,- prefix=None,- cwd=None,- mode="once",- timeout_seconds=600,- lifetime_timeout_seconds=0,- retry_exit_codes=[75],- retry_delay_seconds=30,- post_to=None,- deliver_key=None,- )- args = _parse_watch_update([watch.id, "--session-key", "slack::channel::C456"])-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._watch_store", return_value=store),- patch("vibe.cli._watch_runtime_store", return_value=runtime_store),- ):- result = cli.cmd_watch_update(args)-- assert result == 0- payload = json.loads(capsys.readouterr().out)- assert payload["definition"].get("session_id") is None- assert store.get_watch(watch.id).session_key == "slack::channel::C456"--def test_watch_update_reset_delivery_preserves_creation_scope_metadata(tmp_path: Path, capsys) -> None:store = ManagedWatchStore(tmp_path / "watches.json")runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")@@ -1723,57 +1690,6 @@ def test_watch_update_allows_cwd_for_already_reserved_create_once_watch(tmp_pathassert "session_workdir" not in payload["definition"]["metadata"]-def test_watch_update_rejects_deprecated_prompt_argument(tmp_path: Path) -> None:- store = ManagedWatchStore(tmp_path / "watches.json")- watch = store.add_watch(- name="Watch CI",- session_key="slack::channel::C123",- command=["python3", "wait.py"],- shell_command=None,- prefix=None,- cwd=None,- mode="once",- timeout_seconds=600,- lifetime_timeout_seconds=0,- retry_exit_codes=[75],- retry_delay_seconds=30,- post_to=None,- deliver_key=None,- )- args = _parse_watch_update([watch.id, "--prompt", "hello"])-- with (- patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),- patch("vibe.cli._watch_store", return_value=store),- ):- result, payload = _capture_stderr_json(cli.cmd_watch_update, args)-- assert result == 1- assert payload["code"] == "deprecated_prompt_argument"- assert "--message" in payload["hint"]---def test_watch_add_rejects_deprecated_prompt_argument() -> None:- args = _parse_watch_add(- [- "--session-key",- "slack::channel::C123",- "--prompt",- "hello",- "--",- "python3",- "wait.py",- ]- )-- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):- result, payload = _capture_stderr_json(cli.cmd_watch_add, args)-- assert result == 1- assert payload["code"] == "deprecated_prompt_argument"- assert "--message" in payload["hint"]--def test_watch_update_rejects_agent_together_with_clear_agent(tmp_path: Path) -> None:"""HFR-256 — ``--agent X --clear-agent`` re-pinned today's default Agent.diff --git a/tests/test_computer_cli.py b/tests/test_computer_cli.pyindex 342bf6017..a397976ec 100644--- a/tests/test_computer_cli.py+++ b/tests/test_computer_cli.py@@ -178,15 +178,6 @@ def test_packaged_skill_examples_parse_and_match_the_pinned_driver_schema() -> Nparser.parse_args(["computer", "observe", "apps", "--session-id", "manual"])-def test_computer_help_uses_the_configured_backend_locale(- monkeypatch: pytest.MonkeyPatch,-) -> None:- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")- help_text = cli.build_parser().format_help()- assert "通过当前 Avibe Agent Turn 使用本机桌面" in help_text- assert "Use the local desktop through the active Avibe Agent Turn" not in help_text--def test_argument_contract_rejects_manual_session_and_maps_screenshot_output(tmp_path: Path) -> None:with pytest.raises(ValueError) as exc_info:build_driver_arguments(None, ["session=manual"])@@ -314,13 +305,12 @@ def test_cmd_computer_run_passes_string_arguments_and_prints_json(}-def test_cmd_computer_run_localizes_missing_private_node(+def test_cmd_computer_run_reports_missing_private_node(monkeypatch: pytest.MonkeyPatch,) -> None:from vibe.computer_script_runner import ComputerScriptRunnerErrormonkeypatch.setenv("AVIBE_SESSION_ID", "ses-cli")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")def unavailable(**_kwargs):raise ComputerScriptRunnerError(@@ -335,19 +325,18 @@ def test_cmd_computer_run_localizes_missing_private_node(args = cli.build_parser().parse_args(["computer", "run", "./inspect.mjs"])with pytest.raises(cli.TaskCliError,- match="Avibe 桌面应用随附的 Node runtime",+ match="Node runtime shipped with the Avibe desktop app",) as exc_info:cli.cmd_computer(args)assert exc_info.value.code == "computer_script_unavailable"-def test_cmd_computer_run_localizes_sdk_error_details(+def test_cmd_computer_run_reports_sdk_error_details(monkeypatch: pytest.MonkeyPatch,) -> None:from vibe.computer_script_runner import ComputerScriptRunnerErrormonkeypatch.setenv("AVIBE_SESSION_ID", "ses-cli")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")def invalid_selector(**_kwargs):raise ComputerScriptRunnerError(@@ -372,9 +361,7 @@ def test_cmd_computer_run_localizes_sdk_error_details(with pytest.raises(cli.TaskCliError) as exc_info:cli.cmd_computer(args)- assert str(exc_info.value) == (- "Computer Use 脚本在 computer.app 失败:脚本使用了无效选择器。"- )+ assert str(exc_info.value).startswith("Computer Use script failed at computer.app")assert "Application selector" not in str(exc_info.value)@@ -413,28 +400,15 @@ def test_computer_cli_error_translations_exist_in_all_supported_languages() -> N)- ("language", "expected"),- [- (- "en",- "No screenshot is available for this result. The window may be hidden or "- "minimized, or capture may be unavailable.",- ),- (- "zh",- "此结果没有可用的截图。窗口可能已隐藏或最小化,也可能是截图不可用。",- ),- ],-)-def test_cmd_computer_localizes_missing_screenshot_error(+def test_cmd_computer_reports_missing_screenshot_error(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,- language: str,- expected: str,) -> None:+ expected = (+ "No screenshot is available for this result. The window may be hidden or "+ "minimized, or capture may be unavailable."+ )monkeypatch.setenv("AVIBE_SESSION_ID", "ses-cli")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)with patch("vibe.internal_client.computer_use_sync",@@ -508,7 +482,6 @@ def test_cmd_computer_reports_driver_error_before_writing_screenshot(expected_arguments: dict,) -> None:monkeypatch.setenv("AVIBE_SESSION_ID", "ses-cli")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")output_path = tmp_path / f"{expected_tool}.png"def fake_computer_use_sync(**kwargs):@@ -552,7 +525,7 @@ def test_cmd_computer_reports_driver_error_before_writing_screenshot(assert cli.cmd_computer(args) == 1output = capsys.readouterr().out- assert "请求的 Computer Use 目标正忙" in output+ assert "The requested Computer Use target is busy" in outputassert "desktop is held" not in outputassert not output_path.exists()@@ -653,12 +626,11 @@ def test_json_unavailable_error_keeps_code_and_params(assert payload == body-def test_cmd_computer_localizes_controller_error_in_zh(+def test_cmd_computer_reports_controller_error_in_english(monkeypatch: pytest.MonkeyPatch,capsys,) -> None:monkeypatch.setenv("AVIBE_SESSION_ID", "ses-cli")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")def fake_computer_use_sync(**kwargs):del kwargs@@ -676,8 +648,7 @@ def test_cmd_computer_localizes_controller_error_in_zh(assert cli.cmd_computer(args) == 1output = capsys.readouterr().out- assert "当前 Avibe Session 已归档或正在归档" in output- assert "Computer Use is unavailable because" not in output+ assert "Computer Use is unavailable because this Avibe Session is archived or being archived." in outputdef test_cmd_computer_requires_an_injected_caller_session(diff --git a/tests/test_computer_js_kernel.py b/tests/test_computer_js_kernel.pyindex a5d7d0a8d..38753c794 100644--- a/tests/test_computer_js_kernel.py+++ b/tests/test_computer_js_kernel.py@@ -579,24 +579,15 @@ def test_exceptions_and_unserializable_results_are_reported() -> None:assert "Circular" in cyclic["result_text"]- ("language", "expected"),- [- ("en", "The JavaScript call failed: The JavaScript kernel was reset"),- ("zh", "JavaScript 调用失败:JavaScript 内核已重置"),- ],-)-def test_cli_envelope_and_localized_errors(+def test_cli_envelope_and_errors(monkeypatch: pytest.MonkeyPatch,capsys,tmp_path: Path,- language: str,- expected: str,) -> None:from vibe import cli+ expected = "The JavaScript call failed: The JavaScript kernel was reset"monkeypatch.setenv("AVIBE_SESSION_ID", "ses-cli")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)seen: list[dict] = []code_file = tmp_path / "step.js"code_file.write_text("1 + 1", encoding="utf-8")diff --git a/tests/test_computer_script_sdk.py b/tests/test_computer_script_sdk.pyindex 9dd391529..3087d21e8 100644--- a/tests/test_computer_script_sdk.py+++ b/tests/test_computer_script_sdk.py@@ -1079,7 +1079,6 @@ export default async () => {{assert runner_error.structured_error == expectedmonkeypatch.setenv("AVIBE_SESSION_ID", "ses-script")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")def fail_script(**_kwargs):raise runner_errordiff --git a/tests/test_desktop_runtime_stop.py b/tests/test_desktop_runtime_stop.pyindex ce44167d5..21bdadc4b 100644--- a/tests/test_desktop_runtime_stop.py+++ b/tests/test_desktop_runtime_stop.py@@ -33,7 +33,6 @@ from config import pathsfrom config.v2_config import V2Configfrom tests.ui_server_test_helpers import csrf_headersfrom vibe import cli, desktop_backends, desktop_runtime, remote_access, restart_supervisor, runtime, ui_server-from vibe.i18n import t as i18n_t# Random, so no process another test file started with a fixed id is ever in scope.RUNTIME_ID = secrets.token_hex(32)@@ -48,6 +47,12 @@ OPENCODE_STAMPED = {"opencode", "opencode-native", "opencode-configured", "opencpytestmark = pytest.mark.skipif(os.name == "nt", reason="POSIX signal delivery")+# The CLI's refusal lines, in English whatever the UI language.+_STOP_REFUSED = "Nothing was stopped: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Stop it from the Avibe that started it."+_RESTART_REFUSED = "Nothing was restarted: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Restart it from the Avibe that started it."+_CLAIM_REFUSED = "Another Avibe Runtime is running here and does not belong to this desktop app; nothing was stopped ({part}: {reason})."++@pytest.fixturedef bundle(tmp_path) -> Path:@@ -337,7 +342,8 @@ def test_the_stop_and_its_ancestors_are_never_signalled(spawn, bundle, tmp_path)("service", "service", None, "ERROR: Avibe service did not stop; preserving pidfile and aborting."),("installer", "installer", None, "ERROR: Desktop backend installer processes did not stop."),("opencode", "opencode", None, "ERROR: The OpenCode server this Runtime started did not stop."),- ("opencode", "opencode", "zh", "错误:此 Runtime 启动的 OpenCode 服务未能停止。"),+ # The CLI speaks English whatever the configured UI language.+ ("opencode", "opencode", "zh", "ERROR: The OpenCode server this Runtime started did not stop."),],)def test_a_role_process_carrying_the_id_at_the_rescan_fails_the_stop(@@ -726,9 +732,7 @@ def test_a_plain_stop_from_another_desktop_runtime_stops_nothing(running_runtimeassert cli.cmd_stop() == 3- assert _stderr_lines(capsys)[-1] == i18n_t(- "desktopRuntime.stopRefused", "en", part="service", reason="runtime_id_mismatch"- )+ assert _stderr_lines(capsys)[-1] == _STOP_REFUSED.format(part="service", reason="runtime_id_mismatch")assert stop_env["signals"] == []assert stop_env["stop_pid"] == []assert stop_env["remote_access"] == []@@ -745,9 +749,7 @@ def test_a_plain_stop_refuses_while_nothing_names_the_service_lock_holder(spawn,with _service_lock_held_for(None):assert cli.cmd_stop() == 3- assert _stderr_lines(capsys)[-1] == i18n_t(- "desktopRuntime.stopRefused", "en", part="service", reason="identity_unavailable"- )+ assert _stderr_lines(capsys)[-1] == _STOP_REFUSED.format(part="service", reason="identity_unavailable")assert stop_env["signals"] == []assert stop_env["stop_pid"] == []assert stop_env["remote_access"] == []@@ -805,9 +807,7 @@ def test_a_plain_restart_from_another_desktop_runtime_schedules_nothing(assert cli.cmd_restart() == 3- assert _stderr_lines(capsys)[-1] == i18n_t(- "desktopRuntime.restartRefused", "en", part="service", reason="runtime_id_mismatch"- )+ assert _stderr_lines(capsys)[-1] == _RESTART_REFUSED.format(part="service", reason="runtime_id_mismatch")assert stop_env["signals"] == []assert all(_alive(child) for child in running_runtime)@@ -978,7 +978,7 @@ def test_a_refused_desktop_start_leaves_everything_as_it_found_it(recorded = status_path.read_bytes()assert cli.cmd_start(open_browser=False) == 3- assert _stderr_lines(capsys)[-1] == i18n_t("desktopRuntime.claimRefused", "en", part=part, reason=reason)+ assert _stderr_lines(capsys)[-1] == _CLAIM_REFUSED.format(part=part, reason=reason)assert stop_env["status"] == []assert status_path.read_bytes() == recordedassert stop_env["signals"] == []@@ -1028,9 +1028,7 @@ def test_a_desktop_start_whose_service_lost_the_lock_to_another_runtime_rolls_bawith held:assert cli.cmd_start(open_browser=False) == 3- assert _stderr_lines(capsys)[-1] == i18n_t(- "desktopRuntime.claimRefused", "en", part="service", reason="runtime_id_mismatch"- )+ assert _stderr_lines(capsys)[-1] == _CLAIM_REFUSED.format(part="service", reason="runtime_id_mismatch")assert stop_env["stop_pid"] == [own_ui.pid, own_service.pid]assert not _signalled(stop_env, foreign[0])assert _alive(foreign[0])@@ -1084,9 +1082,7 @@ def test_a_stop_asks_again_of_every_process_it_is_about_to_signal(with _service_lock_held_for(service):assert cli.cmd_stop() == 3- assert _stderr_lines(capsys)[-1] == i18n_t(- "desktopRuntime.stopRefused", "en", part=taken_over, reason="runtime_id_mismatch"- )+ assert _stderr_lines(capsys)[-1] == _STOP_REFUSED.format(part=taken_over, reason="runtime_id_mismatch")foreign = service if taken_over == "service" else uiassert not _signalled(stop_env, foreign)assert _alive(foreign)diff --git a/tests/test_doctor_i18n.py b/tests/test_doctor_i18n.pyindex 8a7a58b1d..57282819f 100644--- a/tests/test_doctor_i18n.py+++ b/tests/test_doctor_i18n.py@@ -245,7 +245,6 @@ def test_package_integrity_doctor_items_are_localized(site_packages = tmp_path / "site-packages"(site_packages / "avibe_os-1.0.dist-info").mkdir(parents=True)active_vibe = (Path.home() / ".local" / "bin" / "vibe").resolve()- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)monkeypatch.setattr(cli, "_path_entries_for_executable", lambda _name: [active_vibe])monkeypatch.setattr(cli, "_uv_tool_site_packages_for_vibe", lambda _path: [site_packages])monkeypatch.setattr(cli, "_is_uv_tool_editable", lambda _path: False)@@ -254,7 +253,7 @@ def test_package_integrity_doctor_items_are_localized(item = next(item- for item in cli._local_cli_installation_items()+ for item in cli._local_cli_installation_items(language=language)if item.get("code") == "installation.package_integrity")@@ -291,12 +290,11 @@ def test_restart_failure_summary_localizes_labels_and_preserves_raw_payload(original = dict(payload)status_path = tmp_path / "restart.json"status_path.write_text("{}", encoding="utf-8")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)monkeypatch.setattr(cli.runtime, "get_restart_status_path", lambda: status_path)monkeypatch.setattr(cli.runtime, "read_json", lambda _path: payload)monkeypatch.setattr(cli.runtime, "verified_service_running", lambda: False)- item = cli._restart_state_items()[0]+ item = cli._restart_state_items(language=language)[0]assert item["code"] == "runtime.restart_failed"assert state_marker in item["message"]@@ -313,13 +311,12 @@ def test_service_pid_sentinel_is_localized_only_at_rendering_boundary(language: str,missing_marker: str,) -> None:- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)monkeypatch.setattr(cli.paths, "get_runtime_pid_path", lambda: tmp_path / "absent.pid")monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda **_kwargs: 4242)monkeypatch.setattr(cli.runtime, "service_lock_holder_pid", lambda: 4242)monkeypatch.setattr(cli.runtime, "read_status", lambda: {"service_pid": None})- items = cli._service_lifecycle_items(detect_extra_processes=False)+ items = cli._service_lifecycle_items(language=language, detect_extra_processes=False)mismatch_codes = {"runtime.service_pidfile_mismatch",@@ -384,9 +381,8 @@ def test_doctor_dependency_status_stays_machine_data_and_out_of_sentence(},)monkeypatch.setattr(cli.api, "askill_auto_install_supported", lambda: True)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")- items = cli._managed_dependencies_doctor_items(deep=False)+ items = cli._managed_dependencies_doctor_items(language="zh", deep=False)expected = {"dependencies.askill.not_ready": "missing",@@ -413,9 +409,7 @@ def test_doctor_ready_and_unsupported_dependencies_keep_stable_codes(]},)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "en")-- items = cli._managed_dependencies_doctor_items(deep=False)+ items = cli._managed_dependencies_doctor_items(language="en", deep=False)ready = next(item for item in items if item.get("code") == "dependencies.askill.ready")unsupported = next(item for item in items if item.get("code") == "dependencies.avault.platform_unsupported")@@ -458,9 +452,8 @@ def test_show_runtime_download_labels_are_localized(archive_cache_status=lambda: None,)monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **kwargs: manager)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")- items = cli._show_runtime_doctor_items(deep=True)+ items = cli._show_runtime_doctor_items(language="zh", deep=True)message = "\n".join(item["message"] for item in items)assert label_marker in messageassert english_label not in message@@ -470,8 +463,7 @@ def test_doctor_uses_real_chinese_path_and_stable_code(monkeypatch: pytest.Monkemonkeypatch.setenv(cli.paths.AVIBE_HOME_ENV, "/tmp/avibe-doctor-home")rendered: dict[str, list[dict]] = {}for language in ("en", "zh"):- monkeypatch.setattr(cli, "_configured_cli_language", lambda language=language: language)- rendered[language] = cli._home_migration_items()+ rendered[language] = cli._home_migration_items(language=language)items = rendered["zh"]@@ -481,11 +473,9 @@ def test_doctor_uses_real_chinese_path_and_stable_code(monkeypatch: pytest.Monkeassert [item["code"] for item in rendered["en"]] == [item["code"] for item in rendered["zh"]]-def test_doctor_localizes_nested_repair_details_and_missing_payload_values(+def test_doctor_projects_nested_repair_details_and_missing_payload_values(monkeypatch: pytest.MonkeyPatch,) -> None:- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")-repaired = cli._repair_managed_dependency("avault",lambda force: {@@ -497,7 +487,7 @@ def test_doctor_localizes_nested_repair_details_and_missing_payload_values()assert "English installer completed" not in repaired["message"]assert "0.1.6" in repaired["message"]- assert "修复完成" in repaired["message"]+ assert "avault repair completed" in repaired["message"]failures = [(@@ -508,7 +498,7 @@ def test_doctor_localizes_nested_repair_details_and_missing_payload_values("platform": "Windows ARM64","message": "no askill build for Windows ARM64",},- "没有为当前平台发布",+ "No askill build is published for this platform.",),("avault",@@ -519,7 +509,7 @@ def test_doctor_localizes_nested_repair_details_and_missing_payload_values("actual_sha256": "actual","message": "checksum verification failed",},- "校验和验证失败",+ "checksum verification failed (expected expected, got actual)",),]for target, result, marker in failures:@@ -536,7 +526,7 @@ def test_doctor_localizes_nested_repair_details_and_missing_payload_values("message": "raw download copy",},)- assert "DNS 查询失败" in download["message"]+ assert "DNS lookup failed after 3 attempts" in download["message"]assert "dns" not in download["message"]unknown_download = cli._repair_managed_dependency("tmux",@@ -555,6 +545,7 @@ def test_doctor_localizes_nested_repair_details_and_missing_payload_values(label="avault",code_prefix="dependencies.avault.download",repair_target=None,+ language="zh",)assert "the selected dependency URL" not in items[0]["message"]assert "所选依赖 URL" in items[0]["message"]@@ -574,7 +565,7 @@ def test_doctor_localizes_nested_repair_details_and_missing_payload_values(archive_cache_status=lambda: None,)monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **kwargs: manager)- runtime_items = cli._show_runtime_doctor_items()+ runtime_items = cli._show_runtime_doctor_items(language="zh")messages = "\n".join(item["message"] for item in runtime_items)assert "this platform" not in messagesassert "当前平台" in messages@@ -603,15 +594,15 @@ def test_doctor_tunnel_quality_projects_every_finite_value(monkeypatch.setattr(cli.paths, "get_config_path", lambda: config_path)monkeypatch.setattr(cli.paths, "get_runtime_doctor_path", lambda: tmp_path / "doctor.json")monkeypatch.setattr(cli.V2Config, "load", lambda *_args, **_kwargs: config)- monkeypatch.setattr(cli, "_home_migration_items", lambda: [])+ monkeypatch.setattr(cli, "_home_migration_items", lambda **_kwargs: [])monkeypatch.setattr(cli, "_service_lifecycle_items", lambda **_kwargs: [])monkeypatch.setattr(cli, "_service_install_family_items", lambda **_kwargs: [])- monkeypatch.setattr(cli, "_restart_state_items", lambda: [])- monkeypatch.setattr(cli, "_runtime_architecture_items", lambda: [])- monkeypatch.setattr(cli, "_show_git_checkpoint_items", lambda: [])+ monkeypatch.setattr(cli, "_restart_state_items", lambda **_kwargs: [])+ monkeypatch.setattr(cli, "_runtime_architecture_items", lambda **_kwargs: [])+ monkeypatch.setattr(cli, "_show_git_checkpoint_items", lambda **_kwargs: [])monkeypatch.setattr(cli, "_managed_dependencies_doctor_items", lambda **_kwargs: [])monkeypatch.setattr(cli, "_show_runtime_doctor_items", lambda **_kwargs: [])- monkeypatch.setattr(cli, "_local_cli_installation_items", lambda: [])+ monkeypatch.setattr(cli, "_local_cli_installation_items", lambda **_kwargs: [])monkeypatch.setattr(cli.api, "detect_cli", lambda *_args, **_kwargs: {})monkeypatch.setattr(cli.paths,@@ -659,9 +650,7 @@ def test_doctor_tunnel_quality_projects_every_finite_value("vibe.remote_access.tunnel_quality.request_path_has_usable_latency",lambda request_path: bool(request_path and request_path.get("latency_ms")),)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")-- result = cli._doctor()+ result = cli._doctor(language="zh")remote_group = next(group for group in result["groups"] if group["name"] == t("doctor.group.remoteAccess", "zh"))shape_marker = {"tunnelQualityRequestsUnavailable": "远程请求不可用",diff --git a/tests/test_harness_health_projection.py b/tests/test_harness_health_projection.pyindex f19225480..49ac6110d 100644--- a/tests/test_harness_health_projection.py+++ b/tests/test_harness_health_projection.py@@ -116,6 +116,30 @@ class _FailureSeedingTaskStore(cli.ScheduledTaskStore):return task+def _bare_session() -> str:+ """A Session row for a Watch to follow up in, with no Agent for the CLI to resolve."""+ from config import paths+ from storage.agent_session_rows import create_agent_session_row+ from storage.db import create_sqlite_engine++ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ return create_agent_session_row(+ conn,+ scope_id=None,+ session_anchor="slack_C123",+ agent_backend="codex",+ agent_variant="codex",+ model="gpt-5.5-codex",+ native_session_id="codex-native",+ workdir=str(Path.cwd()),+ require_workdir=False,+ )+ finally:+ engine.dispose()++def test_the_cli_is_a_projection_consumer_not_a_second_health_read_model(monkeypatch, capsys) -> None:@@ -156,12 +180,10 @@ def test_the_cli_is_a_projection_consumer_not_a_second_health_read_model(["task","add",- "--session-key",- "slack::channel::C123","--cron","0 * * * *",- "--message",- "hello",+ "--shell",+ "true",])with (@@ -218,12 +240,10 @@ def test_task_and_watch_mutations_return_the_enriched_projection(capsys) -> None["task","add",- "--session-key",- "slack::channel::C123","--cron","0 * * * *",- "--message",- "hello",+ "--shell",+ "true",])with (@@ -258,8 +278,8 @@ def test_task_and_watch_mutations_return_the_enriched_projection(capsys) -> None["watch","add",- "--session-key",- "slack::channel::C123",+ "--session-id",+ _bare_session(),"--name","Wait for export","--shell",diff --git a/tests/test_harness_live_status.py b/tests/test_harness_live_status.pyindex 00c10d8ca..1a0a0c3a8 100644--- a/tests/test_harness_live_status.py+++ b/tests/test_harness_live_status.py@@ -505,18 +505,6 @@ def test_harness_status_prioritizes_running_run_before_bounded_probe(store.close()-def test_harness_cli_help_uses_configured_language(monkeypatch, capsys) -> None:- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")-- with pytest.raises(SystemExit) as exc_info:- cli.build_parser().parse_args(["harness", "--help"])-- assert exc_info.value.code == 0- output = capsys.readouterr().out- assert "检查活跃 Run、已启用 Watch、即将触发的 Task 和实时异常" in output- assert "显示有界的实时状态与异常快照" in output--def test_enabled_tasks_are_bounded_after_next_fire_ordering(tmp_path) -> None:store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")try:diff --git a/tests/test_harness_skill_guidance.py b/tests/test_harness_skill_guidance.pyindex 60d843441..6dcb79e86 100644--- a/tests/test_harness_skill_guidance.py+++ b/tests/test_harness_skill_guidance.py@@ -112,21 +112,27 @@ def test_harness_guidance_examples_parse_against_the_real_cli() -> None:def test_avibe_skills_do_not_reintroduce_legacy_harness_guidance() -> None:+ # Spellings the CLI no longer accepts; a Skill that still teaches one teaches a failing call.disallowed = ("--deliver-key",- "`--prefix`",- "vibe hook send",+ "--post-to",+ "--session-key",+ "--send-now",+ "--visibility foreground",+ "--visibility background",+ "--prefix",+ "vibe hook","--prompt`","one-shot async run",- "vibe agent run --async",+ "--async","Delivery controls","Legacy compatibility",- "`vibe agent run` takes `--async`","current Agent Session ID",)for path in ("skills/use-avibe/SKILL.md",+ "skills/use-avibe-harness/SKILL.md","skills/background-watch-hook/SKILL.md",*(path.relative_to(ROOT).as_posix() for path in _use_avibe_references()),):diff --git a/tests/test_install_script.py b/tests/test_install_script.pyindex c10257377..23d85511a 100644--- a/tests/test_install_script.py+++ b/tests/test_install_script.py@@ -83,7 +83,6 @@ def _write_fake_uv(path: Path, uv_log: Path) -> None:return upgrade.ActivationOutcome(outcome.activated_launcher, (failure,))cli.activate_installer_candidate = _activate_with_peer_failure- cli._configured_cli_language = lambda: "zh"if os.environ.get("VIBE_TEST_CP1252_DIAGNOSTIC") == "1":sys.stdout = io.TextIOWrapper(os.fdopen(os.dup(1), "wb"),diff --git a/tests/test_managed_skills.py b/tests/test_managed_skills.pyindex 046b5cd5c..145ca9ad3 100644--- a/tests/test_managed_skills.py+++ b/tests/test_managed_skills.py@@ -10,6 +10,8 @@ import pytestfrom core import managed_skillsfrom core.managed_skills import (+ _skill_list_rows,+ catalog_page,BUILTIN_SKILLS_ROOT_ENV,BUILTIN_SKILLS_SNAPSHOT_ENV,CATALOG_DESCRIPTION_MAX_CHARS,@@ -29,7 +31,6 @@ from core.managed_skills import (publish_builtin_skills,render_skill_catalog_prompt,render_skill_content,- render_skill_list,resolve_skills,)from core.system_prompt_injection import build_system_prompt_injection@@ -590,14 +591,14 @@ def test_catalog_paginates_stably_without_exposing_directories(tmp_path: Path) -assert "ordinary tasks do not require scanning every page" in promptassert ("Consider whether any available Skills would help in the current situation. "- "Load those you choose with `vibe skill load -- <name>`; "+ "Load those you choose with `vibe skill load -- <name> [<name> ...]`; ""reuse any already loaded in this conversation.") in promptassert "If the user requests a Skill by exact name, use that Skill." in promptassert "Before acting on a task covered" not in promptassert "remains in context" not in promptassert "For non-explicit requests, only load Skill names listed here" in prompt- assert render_skill_list(skills, page=2) == "- skill-25: Description 25"+ assert [skill.name for skill in catalog_page(skills, 2)[0]] == ["skill-25"]assert str(tmp_path) not in promptassert render_skill_catalog_prompt([]) == ""@@ -639,7 +640,7 @@ def test_manual_only_skill_is_loadable_but_not_advertised(tmp_path: Path) -> Nonassert manual is not Noneassert manual.disable_model_invocation is True- assert render_skill_list([manual]) == ""+ assert list(catalog_page([manual], 1)[0]) == []manual_prompt = render_skill_catalog_prompt([manual])assert "`vibe skill load -- <name>`" in manual_promptassert (@@ -673,15 +674,13 @@ def test_catalog_bounds_descriptions_and_row_bytes(tmp_path: Path) -> None:assert skill.description.endswith("...")skills.append(skill)- rows, notice = render_skill_list(skills).rsplit("\n", 1)+ first_page, next_page = catalog_page(skills, 1)+ rows = "\n".join(_skill_list_rows(first_page))assert len(rows.encode("utf-8")) <= CATALOG_PAGE_MAX_BYTES- assert notice == "More skills are available. Run `vibe skill list --page 2` to view more."+ assert next_page == 2- first_page_names = [line.split(":", 1)[0][2:] for line in rows.splitlines()]- second_page = render_skill_list(skills, page=2)- assert second_page.splitlines()[0].startswith(- f"- skill-{len(first_page_names):02d}:"- )+ second_page, _ = catalog_page(skills, 2)+ assert second_page[0].name == f"skill-{len(first_page):02d}"def test_catalog_neutralizes_yaml_decoded_terminal_controls(tmp_path: Path) -> None:@@ -696,8 +695,8 @@ def test_catalog_neutralizes_yaml_decoded_terminal_controls(tmp_path: Path) -> Nassert skill is not Noneassert skill.description == "[31mred 0m"- assert "\x1b" not in render_skill_list([skill])- assert "\x9b" not in render_skill_list([skill])+ assert "\x1b" not in "\n".join(_skill_list_rows([skill]))+ assert "\x9b" not in "\n".join(_skill_list_rows([skill]))def test_system_prompt_catalog_reflects_add_edit_and_delete_each_render(tmp_path: Path, monkeypatch) -> None:diff --git a/tests/test_pairing_recovery.py b/tests/test_pairing_recovery.pyindex eb781e139..1fe3acb96 100644--- a/tests/test_pairing_recovery.py+++ b/tests/test_pairing_recovery.py@@ -361,7 +361,6 @@ def test_keyless_config_read_failure_preserves_redeemed_recovery(assert response.status_code == 400assert response.get_json()["error"] == "pairing_recovery_unavailable"else:- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "en")monkeypatch.setattr(cli.getpass, "getpass",lambda prompt: pytest.fail("keyless recovery must not ask for another key"),@@ -613,6 +612,14 @@ def test_ambiguous_redeem_failures_retain_prepared_claim()["phase"] == "prepared"+def _configure_ui_language(monkeypatch, language: str) -> None:+ """A configured UI language the CLI's pairing guidance must not follow."""++ config = V2Config.load()+ config.language = language+ config.save()++@pytest.mark.parametrize("language", ["en", "zh"])def test_definitive_failure_retirement_can_be_retried_through_cli(pairing_host,@@ -622,7 +629,7 @@ def test_definitive_failure_retirement_can_be_retried_through_cli():root, calls = pairing_hostjournal = root / "state/pending-pairing.json"- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)+ _configure_ui_language(monkeypatch, language)def redeem(url, payload, **kwargs):calls.append(payload["pairing_key"])@@ -649,16 +656,16 @@ def test_definitive_failure_retirement_can_be_retried_through_cli(pairing_key="key_bad", backend_url="https://backend.test",)) == 1first_output = capsys.readouterr().err- assert ("was not applied" if language == "en" else "尚未应用") in first_output+ assert "was not applied" in first_outputassert "vibe remote pair" in first_outputassert cli.cmd_remote_pair(args) == 1assert journal.exists()- assert ("was not applied" if language == "en" else "尚未应用") in capsys.readouterr().err+ assert "was not applied" in capsys.readouterr().errmonkeypatch.setattr(Path, "unlink", original_unlink)assert cli.cmd_remote_pair(args) == 1output = capsys.readouterr().err- assert ("was cleared" if language == "en" else "已清理") in output+ assert "was cleared" in outputassert "vibe remote pair" in outputassert not journal.exists()assert calls == ["key_bad"]@@ -695,7 +702,6 @@ def test_definitive_failure_marker_write_failure_does_not_promise_recovery(journal = root / "state/pending-pairing.json"assert json.loads(journal.read_text(encoding="utf-8"))["phase"] == "prepared"assert remote_access.pair("", "")["error"] == "pairing_recovery_not_ready"- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "en")cli._print_remote_pair_failure(result)output = capsys.readouterr().errassert "was not applied" in output@@ -736,7 +742,7 @@ def test_cli_uncertain_failure_instructions_reach_explicit_replacement(return redeem(url, payload, **kwargs)monkeypatch.setattr(remote_access, "_json_request", fail_then_redeem)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)+ _configure_ui_language(monkeypatch, language)monkeypatch.setattr(cli.getpass, "getpass", lambda *args: pytest.fail("pending operation must not prompt"))args = SimpleNamespace(pairing_key="uncertain-key", backend_url="https://backend.test", device_name="fixture", json=False,@@ -745,7 +751,7 @@ def test_cli_uncertain_failure_instructions_reach_explicit_replacement(first = capsys.readouterr().errcommand = "vibe remote pair NEW_PAIRING_KEY --backend-url BACKEND_URL"assert command in first- assert ("uncertain" if language == "en" else "不确定") in first+ assert "uncertain" in firstargs.pairing_key = Noneassert cli.cmd_remote_pair(args) == 1assert command in capsys.readouterr().err@@ -1654,24 +1660,14 @@ def test_ordinary_save_during_redeem_does_not_revoke_across_processes(pairing_ho@pytest.mark.parametrize(- ("language", "error", "needle"),+ ("error", "needle"),[- ("en", "pairing_save_failed_after_redeem", "cloud-side"),- ("zh", "pairing_save_failed_after_redeem", "云端"),- ("en", "pairing_recovery_unavailable", "could not start"),- ("zh", "pairing_recovery_unavailable", "无法启动"),- ("en", "pairing_retirement_failed", "retired"),- ("zh", "pairing_retirement_failed", "清理"),+ ("pairing_save_failed_after_redeem", "cloud-side"),+ ("pairing_recovery_unavailable", "could not start"),+ ("pairing_retirement_failed", "retired"),],)-def test_pairing_recovery_cli_messages_use_supported_locales(- monkeypatch,- capsys,- language,- error,- needle,-):- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)+def test_pairing_recovery_cli_messages_name_the_outcome(capsys, error, needle):cli._print_remote_pair_failure({"error": error,"orphaned_binding": {"instance_id": "inst_A", "device_name": "fixture"},diff --git a/tests/test_prompt_render_export.py b/tests/test_prompt_render_export.pyindex 881bfdd68..0af222b7d 100644--- a/tests/test_prompt_render_export.py+++ b/tests/test_prompt_render_export.py@@ -48,8 +48,8 @@ _PREVIOUS_FORK_OVERRIDE_GUIDANCE = ("forked-Session overrides, and only when the requested Agent backend matches the source Session backend.")_NEW_SESSION_MODEL_GUIDANCE = (- "- `--model` and `--reasoning-effort` set the model of the new Session a run creates (a blank new Session, "- "`--create-session`, or a fork), and that Session keeps it; they are not valid with `--session-id`. With "+ "- `--model` and `--reasoning-effort` set the model of the new Session a run creates (a blank new Session "+ "or a fork), and that Session keeps it; they are not valid with `--session-id`. With ""`--fork-self` or `--fork-session`, `--agent`, `--model`, and `--reasoning-effort` override the forked Session ""only when the requested Agent backend matches the source Session backend.")@@ -146,7 +146,7 @@ def test_export_reconstructs_production_text_with_source_for_every_block(monkeypassert production.count(prompt_text("skills-prompt")) == 1assert ("Consider whether any available Skills would help in the current situation. "- "Load those you choose with `vibe skill load -- <name>`; "+ "Load those you choose with `vibe skill load -- <name> [<name> ...]`; ""reuse any already loaded in this conversation.") in productionassert "If the user requests a Skill by exact name, use that Skill." in production@@ -425,7 +425,20 @@ def test_debug_cli_rejects_invalid_context_without_partial_json(tmp_path, capsysassert captured.err[email protected]("language", ["en", "zh"])+_EXPORT_ERRORS = {+ "invalidField": "Invalid field type or missing required field: {field}",+ "unknownField": "Unknown field: {field}",+ "invalidJson": "The context file must contain valid UTF-8 JSON.",+ "unreadableContext": "Cannot read the context file. Check its path and permissions.",+ "invalidContext": "The context must be a JSON object containing only backend, agent_instructions and options.",+ "invalidBackend": "backend must be claude, codex or opencode.",+}+++def _export_error(kind: str, field: str = "") -> str:+ return "Prompt export failed: " + _EXPORT_ERRORS[kind].format(field=field) + "\n"++@pytest.mark.parametrize("options,field,kind", [({"context": {"user_id": "u", "channel_id": "c", "platform_specific": [1]}}, "options.context.platform_specific", "invalidField"),({"context": {"user_id": "u", "channel_id": "c", "platform_specific": "text"}}, "options.context.platform_specific", "invalidField"),@@ -436,11 +449,10 @@ def test_debug_cli_rejects_invalid_context_without_partial_json(tmp_path, capsys({"enabled_agents": 123}, "options.enabled_agents", "invalidField"),({"unknown": True}, "options.unknown", "unknownField"),])-def test_cli_localizes_validation_before_rendering(monkeypatch, tmp_path, capsys, language, options, field, kind):+def test_cli_reports_validation_before_rendering(monkeypatch, tmp_path, capsys, options, field, kind):def unexpected_render(*_args, **_kwargs):pytest.fail("Invalid input reached production rendering")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)monkeypatch.setattr(managed_skills, "resolve_skills", unexpected_render)context_file = tmp_path / "context.json"context_file.write_text(json.dumps({@@ -450,11 +462,9 @@ def test_cli_localizes_validation_before_rendering(monkeypatch, tmp_path, capsysassert cli.cmd_debug_prompt(args) == 1output = capsys.readouterr()assert output.out == ""- error = cli.i18n_t(f"debug.cli.error.{kind}", language, field=field)- assert output.err == cli.i18n_t("debug.cli.error.promptExport", language, error=error) + "\n"+ assert output.err == _export_error(kind, field)[email protected]("language", ["en", "zh"])@pytest.mark.parametrize("agents,location", [("codex", ""), ("", ""), ({"name": "codex"}, ""), ({}, ""),(True, ""), (123, ""), (1.5, ""),@@ -463,11 +473,10 @@ def test_cli_localizes_validation_before_rendering(monkeypatch, tmp_path, capsys([{"name": " "}], ".0"), ([{"name": "!!!"}], ".0"),([{"name": "codex"}, {}], ".1"),])-def test_cli_rejects_invalid_json_agent_inputs(monkeypatch, tmp_path, capsys, language, agents, location):+def test_cli_rejects_invalid_json_agent_inputs(monkeypatch, tmp_path, capsys, agents, location):def unexpected_discovery(*_args, **_kwargs):pytest.fail("Invalid Agent input reached production rendering")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)monkeypatch.setattr(managed_skills, "resolve_skills", unexpected_discovery)request = _inputs()request["options"]["enabled_agents"] = agents@@ -477,8 +486,7 @@ def test_cli_rejects_invalid_json_agent_inputs(monkeypatch, tmp_path, capsys, laassert cli.cmd_debug_prompt(args) == 1output = capsys.readouterr()assert output.out == ""- error = cli.i18n_t("debug.cli.error.invalidField", language, field=f"options.enabled_agents{location}")- assert output.err == cli.i18n_t("debug.cli.error.promptExport", language, error=error) + "\n"+ assert output.err == _export_error("invalidField", f"options.enabled_agents{location}")@pytest.mark.parametrize("agents,expected_rows", [@@ -511,14 +519,12 @@ def test_cli_renders_valid_json_agent_arrays(monkeypatch, tmp_path, capsys, agenassert render_prompt_context(omitted) == rendered[email protected]("language", ["en", "zh"])@pytest.mark.parametrize("content,kind", [(b"{", "invalidJson"), (b"\xff", "invalidJson"), (None, "unreadableContext"),(b"null", "invalidContext"), (b'{}', "invalidBackend"),(b'{"backend":"codex","extra":1}', "invalidContext"),])-def test_cli_localizes_invalid_context_files(monkeypatch, tmp_path, capsys, language, content, kind):- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)+def test_cli_reports_invalid_context_files(monkeypatch, tmp_path, capsys, content, kind):context_file = tmp_path / "context.json"if content is not None:context_file.write_bytes(content)@@ -526,8 +532,7 @@ def test_cli_localizes_invalid_context_files(monkeypatch, tmp_path, capsys, langassert cli.cmd_debug_prompt(args) == 1output = capsys.readouterr()assert output.out == ""- error = cli.i18n_t(f"debug.cli.error.{kind}", language)- assert output.err == cli.i18n_t("debug.cli.error.promptExport", language, error=error) + "\n"+ assert output.err == _export_error(kind)def test_approved_guidance_changes_preserve_all_other_injection_bytes(monkeypatch):diff --git a/tests/test_session_cli.py b/tests/test_session_cli.pyindex 875604792..907b23df2 100644--- a/tests/test_session_cli.py+++ b/tests/test_session_cli.py@@ -60,7 +60,7 @@ def test_list_excludes_archived_and_orders_by_activity(monkeypatch, tmp_path, caassert payload["kind"] == "agent_sessions"ids = [s["id"] for s in payload["sessions"]]assert ids == ["sesbbb", "sesaaa"] # newest activity first; archived excluded- assert "data query" in payload["message"]+ assert "message" not in payloaddef test_list_row_has_only_lean_fields(monkeypatch, tmp_path, capsys):@@ -142,7 +142,7 @@ def test_list_invalid_type_errors(monkeypatch, tmp_path, capsys):def test_get_returns_detail_without_status_agentid_anchor(monkeypatch, tmp_path, capsys):engine = _setup(monkeypatch, tmp_path)_seed(engine, "sesaaa", platform="avibe", native="proj_a")- code, payload = _run(cli.cmd_session_get, ["session", "get", "sesaaa"], capsys)+ code, payload = _run(cli.cmd_session_get, ["session", "get", "--session-id", "sesaaa"], capsys)assert code == 0s = payload["session"]assert s["id"] == "sesaaa"@@ -150,7 +150,7 @@ def test_get_returns_detail_without_status_agentid_anchor(monkeypatch, tmp_path,assert s["agent_backend"] == "claude" # backend kept in detailfor omitted in ("status", "agent_id", "session_anchor"):assert omitted not in s- assert "vibe runs list --session-id sesaaa" in payload["message"]+ assert "message" not in payloaddef test_get_defaults_to_caller_session(monkeypatch, tmp_path, capsys):@@ -162,36 +162,42 @@ def test_get_defaults_to_caller_session(monkeypatch, tmp_path, capsys):assert code == 0assert payload["session"]["id"] == "sesaaa"- assert payload["session_default_notice"] == {- "code": "session_defaulted_to_caller",- "message": "Session defaulted to this Agent Session.",- "session_id": "sesaaa",- }+ assert "session_default_notice" not in payload-def test_get_requires_session_without_caller(monkeypatch, tmp_path, capsys):+ ("cmd_name", "argv", "help_command"),+ [+ ("cmd_session_get", ["session", "get"], "vibe session get --help"),+ ("cmd_session_update", ["session", "update", "--title", "x"], "vibe session update --help"),+ ("cmd_session_send_now", ["session", "send-now"], "vibe session send-now --help"),+ ("cmd_session_queue_list", ["session", "queue", "list"], "vibe session queue list --help"),+ ("cmd_session_queue_remove", ["session", "queue", "remove", "msg_any"], "vibe session queue remove --help"),+ ],+)+def test_single_session_commands_need_a_caller_or_session_id(monkeypatch, tmp_path, capsys, cmd_name, argv, help_command):_setup(monkeypatch, tmp_path)monkeypatch.delenv("AVIBE_SESSION_ID", raising=False)- code, payload = _run(cli.cmd_session_get, ["session", "get"], capsys)+ code, payload = _run(getattr(cli, cmd_name), argv, capsys)assert code == 1- assert payload["code"] == "missing_session_target"- assert payload["help_command"] == "vibe session get --help"- assert payload["hint"] == "Run this command from an Avibe Agent shell, or pass the target Session ID positionally."+ assert payload["code"] == "missing_caller_session"+ assert payload["help_command"] == help_command+def test_get_archived_is_not_found(monkeypatch, tmp_path, capsys):engine = _setup(monkeypatch, tmp_path)_seed(engine, "sesarch", status="archived")- code, payload = _run(cli.cmd_session_get, ["session", "get", "sesarch"], capsys)+ code, payload = _run(cli.cmd_session_get, ["session", "get", "--session-id", "sesarch"], capsys)assert code == 1assert payload["code"] == "session_not_found"def test_get_missing_is_not_found(monkeypatch, tmp_path, capsys):_setup(monkeypatch, tmp_path)- code, payload = _run(cli.cmd_session_get, ["session", "get", "nope"], capsys)+ code, payload = _run(cli.cmd_session_get, ["session", "get", "--session-id", "nope"], capsys)assert code == 1assert payload["code"] == "session_not_found"@@ -225,7 +231,7 @@ def test_send_now_dispatches_an_existing_queue_without_adding_a_message(code, payload = _run(cli.cmd_session_send_now,- ["session", "send-now", "sesaaa"],+ ["session", "send-now", "--session-id", "sesaaa"],capsys,)@@ -266,7 +272,7 @@ def test_send_now_surfaces_a_typed_steer_refusal(monkeypatch, tmp_path, capsys):code, payload = _run(cli.cmd_session_send_now,- ["session", "send-now", "sesaaa"],+ ["session", "send-now", "--session-id", "sesaaa"],capsys,)@@ -297,7 +303,7 @@ def test_send_now_surfaces_an_idle_flush_failure(monkeypatch, tmp_path, capsys):code, payload = _run(cli.cmd_session_send_now,- ["session", "send-now", "sesaaa"],+ ["session", "send-now", "--session-id", "sesaaa"],capsys,)@@ -324,7 +330,7 @@ def test_send_now_rejects_an_archived_session_before_controller_call(code, payload = _run(cli.cmd_session_send_now,- ["session", "send-now", "sesarch"],+ ["session", "send-now", "--session-id", "sesarch"],capsys,)@@ -332,18 +338,6 @@ def test_send_now_rejects_an_archived_session_before_controller_call(assert payload["code"] == "session_not_found"-def test_send_now_requires_an_explicit_target(capsys):- parser = cli.build_parser()-- with pytest.raises(SystemExit) as exc:- parser.parse_args(["session", "send-now"])-- assert exc.value.code == 2- payload = json.loads(capsys.readouterr().err)- assert payload["code"] == "invalid_arguments"- assert payload["help_command"] == "vibe session send-now --help"--def test_send_now_accepts_im_while_queue_management_remains_workbench_only(monkeypatch,tmp_path,@@ -368,17 +362,17 @@ def test_send_now_accepts_im_while_queue_management_remains_workbench_only(send_code, send_payload = _run(cli.cmd_session_send_now,- ["session", "send-now", "sesim"],+ ["session", "send-now", "--session-id", "sesim"],capsys,)list_code, list_payload = _run(cli.cmd_session_queue_list,- ["session", "queue", "list", "sesim"],+ ["session", "queue", "list", "--session-id", "sesim"],capsys,)remove_code, remove_payload = _run(cli.cmd_session_queue_remove,- ["session", "queue", "remove", "sesim", "msg_any"],+ ["session", "queue", "remove", "msg_any", "--session-id", "sesim"],capsys,)@@ -434,7 +428,7 @@ def test_queue_list_is_paginated_in_fifo_order_and_exposes_run_identity(code, page1 = _run(cli.cmd_session_queue_list,- ["session", "queue", "list", "sesaaa", "--limit", "2"],+ ["session", "queue", "list", "--session-id", "sesaaa", "--limit", "2"],capsys,)@@ -444,12 +438,12 @@ def test_queue_list_is_paginated_in_fifo_order_and_exposes_run_identity(assert page1["queued"][0]["run_id"] is Noneassert page1["queued"][1]["run_id"] == "run_second"assert page1["pagination"]["next_command"] == (- "vibe session queue list sesaaa --page 2 --limit 2"+ "vibe session queue list --session-id sesaaa --page 2 --limit 2")code, page2 = _run(cli.cmd_session_queue_list,- ["session", "queue", "list", "sesaaa", "--page", "2", "--limit", "2"],+ ["session", "queue", "list", "--session-id", "sesaaa", "--page", "2", "--limit", "2"],capsys,)@@ -472,7 +466,7 @@ def test_queue_list_reports_server_owned_explicit_retry_hold(monkeypatch, tmp_paconn, scope_id=scope_id, session_id="sesaaa", text="保留附件",metadata={"requires_explicit_retry": True, "retry_reason": "caller spoof"},)- _, before = _run(cli.cmd_session_queue_list, ["session", "queue", "list", "sesaaa"], capsys)+ _, before = _run(cli.cmd_session_queue_list, ["session", "queue", "list", "--session-id", "sesaaa"], capsys)assert before["queued"][0]["requires_explicit_retry"] is Falseassert before["queued"][0]["retry_reason"] is Nonefor _ in range(3):@@ -484,7 +478,7 @@ def test_queue_list_reports_server_owned_explicit_retry_hold(monkeypatch, tmp_padeliveries=[delivery], dispatch_text="保留附件",)manager._settle_durable_prewrite_failure(turn_id, outcome="no_terminal_result")- code, result = _run(cli.cmd_session_queue_list, ["session", "queue", "list", "sesaaa"], capsys)+ code, result = _run(cli.cmd_session_queue_list, ["session", "queue", "list", "--session-id", "sesaaa"], capsys)assert code == 0assert result["queued"][0]["id"] == payload["id"]assert result["queued"][0]["requires_explicit_retry"] is True@@ -517,7 +511,7 @@ def test_queue_remove_deletes_only_the_named_session_row_and_notifies_web(code, wrong_session = _run(cli.cmd_session_queue_remove,- ["session", "queue", "remove", "sesbbb", queued["id"]],+ ["session", "queue", "remove", queued["id"], "--session-id", "sesbbb"],capsys,)@@ -528,7 +522,7 @@ def test_queue_remove_deletes_only_the_named_session_row_and_notifies_web(code, removed = _run(cli.cmd_session_queue_remove,- ["session", "queue", "remove", "sesaaa", queued["id"]],+ ["session", "queue", "remove", queued["id"], "--session-id", "sesaaa"],capsys,)@@ -585,7 +579,7 @@ def test_queue_remove_cancels_the_agent_run_owned_by_that_row(code, removed = _run(cli.cmd_session_queue_remove,- ["session", "queue", "remove", "sesrun", queued["id"]],+ ["session", "queue", "remove", queued["id"], "--session-id", "sesrun"],capsys,)@@ -605,12 +599,12 @@ def test_queue_commands_reject_an_archived_session(monkeypatch, tmp_path, capsyslist_code, list_payload = _run(cli.cmd_session_queue_list,- ["session", "queue", "list", "sesarch"],+ ["session", "queue", "list", "--session-id", "sesarch"],capsys,)remove_code, remove_payload = _run(cli.cmd_session_queue_remove,- ["session", "queue", "remove", "sesarch", "msg_any"],+ ["session", "queue", "remove", "msg_any", "--session-id", "sesarch"],capsys,)@@ -626,7 +620,7 @@ def test_queue_commands_reject_an_archived_session(monkeypatch, tmp_path, capsysdef test_update_sets_title(monkeypatch, tmp_path, capsys):engine = _setup(monkeypatch, tmp_path)_seed(engine, "sesaaa", title="Old")- code, payload = _run(cli.cmd_session_update, ["session", "update", "sesaaa", "--title", "New name"], capsys)+ code, payload = _run(cli.cmd_session_update, ["session", "update", "--session-id", "sesaaa", "--title", "New name"], capsys)assert code == 0assert payload["updated"] is Trueassert payload["session"]["title"] == "New name"@@ -646,29 +640,13 @@ def test_update_defaults_to_caller_session(monkeypatch, tmp_path, capsys):assert payload["updated"] is Trueassert payload["session"]["id"] == "sesaaa"assert payload["session"]["title"] == "New name"- assert payload["session_default_notice"] == {- "code": "session_defaulted_to_caller",- "message": "Session defaulted to this Agent Session.",- "session_id": "sesaaa",- }---def test_update_requires_session_without_caller(monkeypatch, tmp_path, capsys):- _setup(monkeypatch, tmp_path)- monkeypatch.delenv("AVIBE_SESSION_ID", raising=False)-- code, payload = _run(cli.cmd_session_update, ["session", "update", "--title", "New name"], capsys)-- assert code == 1- assert payload["code"] == "missing_session_target"- assert payload["help_command"] == "vibe session update --help"- assert payload["hint"] == "Run this command from an Avibe Agent shell, or pass the target Session ID positionally."+ assert "session_default_notice" not in payloaddef test_update_empty_title_clears(monkeypatch, tmp_path, capsys):engine = _setup(monkeypatch, tmp_path)_seed(engine, "sesaaa", title="Old")- _, payload = _run(cli.cmd_session_update, ["session", "update", "sesaaa", "--title", ""], capsys)+ _, payload = _run(cli.cmd_session_update, ["session", "update", "--session-id", "sesaaa", "--title", ""], capsys)assert payload["session"]["title"] is None@@ -682,7 +660,7 @@ def test_update_help_teaches_visibility_sugar(capsys):help_text = capsys.readouterr().outassert "--visible" in help_textassert "--hidden" in help_text- assert "--visibility {foreground,background}" in help_text+ assert "--visibility" not in help_text@pytest.mark.parametrize(@@ -690,7 +668,7 @@ def test_update_help_teaches_visibility_sugar(capsys):[("--visible", "foreground"), ("--hidden", "background")],)def test_update_visibility_sugar_parses(flag, expected):- args = cli.build_parser().parse_args(["session", "update", "sesaaa", flag])+ args = cli.build_parser().parse_args(["session", "update", "--session-id", "sesaaa", flag])assert args.visibility == expected@@ -699,15 +677,13 @@ def test_update_visibility_sugar_parses(flag, expected):"visibility_args",[["--visible", "--hidden"],- ["--visible", "--visibility", "background"],- ["--hidden", "--visibility", "foreground"],],)def test_update_visibility_sugar_rejects_conflicts(visibility_args, capsys):parser = cli.build_parser()with pytest.raises(SystemExit) as exc:- parser.parse_args(["session", "update", "sesaaa", *visibility_args])+ parser.parse_args(["session", "update", "--session-id", "sesaaa", *visibility_args])assert exc.value.code == 2payload = json.loads(capsys.readouterr().err)@@ -739,9 +715,9 @@ def test_update_visibility_and_make_standalone_keeps_workdir(monkeypatch, tmp_pa["session","update",+ "--session-id","sesaaa",- "--visibility",- "background",+ "--hidden","--scope-id","none",],@@ -768,7 +744,7 @@ def test_update_visibility_and_make_standalone_keeps_workdir(monkeypatch, tmp_padef test_update_archived_is_not_found(monkeypatch, tmp_path, capsys):engine = _setup(monkeypatch, tmp_path)_seed(engine, "sesarch", status="archived", title="Old")- code, payload = _run(cli.cmd_session_update, ["session", "update", "sesarch", "--title", "x"], capsys)+ code, payload = _run(cli.cmd_session_update, ["session", "update", "--session-id", "sesarch", "--title", "x"], capsys)assert code == 1assert payload["code"] == "session_not_found"# title must not have been written to the soft-deleted rowdiff --git a/tests/test_show_pages.py b/tests/test_show_pages.pyindex f320f125d..53a84e530 100644--- a/tests/test_show_pages.py+++ b/tests/test_show_pages.py@@ -2655,7 +2655,7 @@ def test_show_path_cli_json_creates_page(monkeypatch, tmp_path, capsys):assert captured["timeout"] == 3-def test_show_path_cli_prints_annotation_capabilities(monkeypatch, tmp_path, capsys):+def test_show_path_cli_prints_the_json_envelope_without_json_flag(monkeypatch, tmp_path, capsys):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()_save_config()@@ -2664,9 +2664,10 @@ def test_show_path_cli_prints_annotation_capabilities(monkeypatch, tmp_path, capargs = cli.build_parser().parse_args(["show", "path", "--session-id", "ses123"])assert cli.cmd_show_path(args) == 0- output = capsys.readouterr().out- assert "Use it:" in output- assert "- Annotations: users can mark up this page; see vibe show marks / reply / annotate." in output+ payload = json.loads(capsys.readouterr().out)+ assert (payload["schema_version"], payload["ok"], payload["kind"]) == (1, True, "show_page")+ assert payload["session_id"] == "ses123"+ assert "Annotations: users can mark up this page; see vibe show marks / reply / annotate." in payload["next_actions"]def test_show_path_cli_keeps_page_when_prewarm_fails(monkeypatch, tmp_path, capsys):@@ -2700,11 +2701,7 @@ def test_show_path_defaults_to_caller_session(monkeypatch, tmp_path, capsys):payload = json.loads(capsys.readouterr().out)assert payload["session_id"] == "sesCaller"- assert payload["session_default_notice"] == {- "code": "session_defaulted_to_caller",- "message": "Show Page session defaulted to this Agent Session.",- "session_id": "sesCaller",- }+ assert "session_default_notice" not in payloadassert (tmp_path / "show" / "sesCaller" / "index.html").exists()@@ -2718,7 +2715,7 @@ def test_show_path_requires_session_without_caller(monkeypatch, tmp_path, capsysassert cli.cmd_show_path(args) == 1payload = json.loads(capsys.readouterr().err)- assert payload["code"] == "missing_session_target"+ assert payload["code"] == "missing_caller_session"assert payload["help_command"] == "vibe show path --help"@@ -2854,14 +2851,9 @@ def test_show_list_cli_json_reports_pagination(monkeypatch, tmp_path, capsys):assert payload["count"] == 20assert payload["pagination"]["has_more"] is Trueassert payload["pagination"]["next_page"] == 2- assert "vibe show list --global --json --page 2 --limit 20" == payload["pagination"]["next_command"]+ assert "vibe show list --global --page 2 --limit 20" == payload["pagination"]["next_command"]assert "message" not in payload- # Text output still tells a person how to continue, from the same next_command.- args = cli.build_parser().parse_args(["show", "list", "--global"])- assert cli.cmd_show_list(args) == 0- assert "Continue with: vibe show list --global --page 2 --limit 20" in capsys.readouterr().out-def test_show_list_cli_next_command_uses_absolute_time_filters(monkeypatch, tmp_path, capsys):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))@@ -2883,7 +2875,7 @@ def test_show_list_cli_next_command_uses_absolute_time_filters(monkeypatch, tmp_payload = json.loads(capsys.readouterr().out)assert "--updated-after 2026-05-25T00:00:00+00:00" in payload["pagination"]["next_command"]assert "--updated-after 2026-05-25T08:00:00+08:00" not in payload["pagination"]["next_command"]- assert payload["pagination"]["next_command"].endswith("--json --page 2 --limit 10")+ assert payload["pagination"]["next_command"].endswith("--page 2 --limit 10")def test_show_list_cli_filters_visibility(monkeypatch, tmp_path, capsys):@@ -2909,23 +2901,18 @@ def test_show_list_cli_filters_visibility(monkeypatch, tmp_path, capsys):args = cli.build_parser().parse_args(["show", "list", "--global", "--visibility", "private"])assert cli.cmd_show_list(args) == 0- output = capsys.readouterr().out- assert "Sessions: all" in output- assert "Count: 1" in output- assert "Filter: visibility=private" in output- assert "- ses-private" in output- assert "- ses-limited" not in output- assert "- ses-public" not in output+ payload = json.loads(capsys.readouterr().out)+ assert payload["kind"] == "show_pages"+ assert payload["global"] is True+ assert (payload["count"], payload["visibility"]) == (1, "private")+ assert [page["session_id"] for page in payload["pages"]] == ["ses-private"]args = cli.build_parser().parse_args(["show", "list", "--global", "--visibility", "limited"])assert cli.cmd_show_list(args) == 0- output = capsys.readouterr().out- assert "Count: 1" in output- assert "Filter: visibility=limited" in output- assert "- ses-private" not in output- assert "- ses-limited" in output- assert "- ses-public" not in output+ payload = json.loads(capsys.readouterr().out)+ assert (payload["count"], payload["visibility"]) == (1, "limited")+ assert [page["session_id"] for page in payload["pages"]] == ["ses-limited"]def test_show_page_payload_requires_enabled_avibe_cloud(monkeypatch, tmp_path):@@ -3040,13 +3027,13 @@ def test_show_status_and_update_default_to_caller_session(monkeypatch, tmp_path,assert cli.cmd_show_status(parser.parse_args(["show", "status", "--json"])) == 0status_payload = json.loads(capsys.readouterr().out)assert status_payload["session_id"] == "sesCaller"- assert status_payload["session_default_notice"]["session_id"] == "sesCaller"+ assert "session_default_notice" not in status_payloadassert cli.cmd_show_update(parser.parse_args(["show", "update", "--visibility", "public", "--json"])) == 0update_payload = json.loads(capsys.readouterr().out)assert update_payload["session_id"] == "sesCaller"assert update_payload["visibility"] == "public"- assert update_payload["session_default_notice"]["session_id"] == "sesCaller"+ assert "session_default_notice" not in update_payloaddef test_show_update_rotate_share_fails_while_private(monkeypatch, tmp_path, capsys):@@ -3163,9 +3150,8 @@ def test_show_mark_cli_records_event_and_message(monkeypatch, tmp_path, capsys):"mark","--session-id","ses123",- "--target","mark-default-summary",- "--body",+ "--message","Review this summary.","--json",]@@ -3244,7 +3230,7 @@ def test_show_mark_keeps_anchor_text_without_a_selector(monkeypatch, tmp_path, c)args = cli.build_parser().parse_args(- ["show", "mark", "--session-id", "ses123", "--target", "cta", "--body", "Aligned it.", "--json", *flags]+ ["show", "mark", "--session-id", "ses123", "cta", "--message", "Aligned it.", "--json", *flags])assert cli.cmd_show(args) == 0@@ -3304,9 +3290,8 @@ def test_show_mark_defaults_to_caller_session(monkeypatch, tmp_path, capsys):["show","mark",- "--target","mark-default-summary",- "--body",+ "--message","Review this summary.","--json",]@@ -3315,7 +3300,7 @@ def test_show_mark_defaults_to_caller_session(monkeypatch, tmp_path, capsys):payload = json.loads(capsys.readouterr().out)assert payload["session_id"] == "sesCaller"- assert payload["session_default_notice"]["session_id"] == "sesCaller"+ assert "session_default_notice" not in payloadwith engine.connect() as conn:assert conn.execute(select(show_session_events.c.session_id)).scalar_one() == "sesCaller"@@ -3372,9 +3357,8 @@ def test_show_mark_cli_posts_to_live_ui_when_running(monkeypatch, tmp_path, caps"mark","--session-id","ses123",- "--target","mark-default-summary",- "--body",+ "--message","Review this summary.","--json",]@@ -3491,7 +3475,7 @@ def test_show_mark_positional_target_replaces_same_target(monkeypatch, tmp_path,assert cli.cmd_show(first_args) == 0first = json.loads(capsys.readouterr().out)second_args = cli.build_parser().parse_args(- ["show", "mark", "--target", "#revenue-card", "--session-id", "ses123", "--body", "New note.", "--json"]+ ["show", "mark", "#revenue-card", "--session-id", "ses123", "--message", "New note.", "--json"])assert cli.cmd_show(second_args) == 0second = json.loads(capsys.readouterr().out)@@ -3604,7 +3588,7 @@ def test_show_marks_uses_shared_pagination(monkeypatch, tmp_path, capsys):payload = json.loads(capsys.readouterr().out)assert len(payload["marks"]) == 20assert payload["pagination"]["next_command"] == (- "vibe show marks --session-id ses123 --json --page 2 --limit 20"+ "vibe show marks --session-id ses123 --page 2 --limit 20")@@ -3797,7 +3781,7 @@ def test_show_annotate_cli_defaults_session_and_records_offline_control(monkeyparesult = json.loads(capsys.readouterr().out)assert result["session_id"] == "sesCaller"- assert result["session_default_notice"]["session_id"] == "sesCaller"+ assert "session_default_notice" not in resultassert result["event"]["payload"] == {"action": "set-mode", "mode": "smart"}assert result["event"]["transcript_text"] == ""assert result["event"]["message_id"] is None@@ -3929,7 +3913,7 @@ def test_show_event_defaults_to_caller_session(monkeypatch, tmp_path, capsys):payload = json.loads(capsys.readouterr().out)assert payload["session_id"] == "sesCaller"- assert payload["session_default_notice"]["session_id"] == "sesCaller"+ assert "session_default_notice" not in payloadwith engine.connect() as conn:assert conn.execute(select(show_session_events.c.session_id)).scalar_one() == "sesCaller"diff --git a/tests/test_show_runtime_archive_cleanup.py b/tests/test_show_runtime_archive_cleanup.pyindex 2f277034f..b91c41c17 100644--- a/tests/test_show_runtime_archive_cleanup.py+++ b/tests/test_show_runtime_archive_cleanup.py@@ -392,7 +392,7 @@ def test_cleanup_reports_inspection_failure_distinct_from_lock_contention(tmp_paassert result["skipped_reason"] == "archive_inspection_failed"-def test_archive_cleanup_outcomes_are_fully_rendered_everywhere() -> None:+def test_archive_cleanup_outcomes_are_fully_rendered_everywhere(monkeypatch, capsys) -> None:"""Enumeration pin: every report outcome/reason must render distinctly.A new outcome or skip reason that the CLI/Doctor forgot to wire fails this@@ -401,27 +401,40 @@ def test_archive_cleanup_outcomes_are_fully_rendered_everywhere() -> None:from core import show_runtime as modulefrom vibe import cli as vibe_cli+ def render(archives: dict) -> tuple[str, str]:+ class FakeRuntimeManager:+ def clean(self, *, keep_previous=1, dry_run=False):+ return {"ok": True, "removed": [], "archives": archives}++ monkeypatch.setattr(vibe_cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())+ monkeypatch.setattr(+ vibe_cli, "_clean_git_runtime", lambda *, keep_previous, dry_run=False: {"ok": True, "removed": []}+ )+ vibe_cli.cmd_runtime(vibe_cli.build_parser().parse_args(["runtime", "clean"]))+ captured = capsys.readouterr()+ return captured.out, captured.err+reasons = {module._SKIPPED_ARCHIVE_REASON_INSTALL_RUNNING,module._SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED,module._SKIPPED_ARCHIVE_REASON_REMOVAL_FAILED,}- # Every skip reason produces a non-empty localized skip line.- language = "en"+ # Every skip reason produces a distinct, non-empty skip line.rendered = set()for reason in reasons:- message = vibe_cli.i18n_t("runtime.clean.skipped", language, reason=reason)- assert message and message != "runtime.clean.skipped"- assert reason in message- rendered.add(message)+ _out, err = render({"skipped_reason": reason, "failed_count": 2})+ assert err.strip()+ if reason != module._SKIPPED_ARCHIVE_REASON_REMOVAL_FAILED:+ assert reason in err+ rendered.add(err)assert len(rendered) == len(reasons)# Inspection failures carry different remediation from lock contention.- wait_action = vibe_cli.i18n_t("runtime.doctor.archiveCacheSkippedAction", language)- inspect_action = vibe_cli.i18n_t("runtime.doctor.archiveCacheSkippedInspectionAction", language)+ wait_action = vibe_cli.i18n_t("runtime.doctor.archiveCacheSkippedAction", "en")+ inspect_action = vibe_cli.i18n_t("runtime.doctor.archiveCacheSkippedInspectionAction", "en")assert wait_action and inspect_action and wait_action != inspect_action# Partial removals report the failed count.- partial = vibe_cli.i18n_t("runtime.clean.partiallyRemoved", language, failed=3)- assert "3" in partial and partial != "runtime.clean.partiallyRemoved"+ out, err = render({"outcome": "partial", "removed_count": 1, "removed_bytes": 10, "failed_count": 3})+ assert "3 archive(s) could not be removed" in err# The outcome vocabulary stays closed.assert module._ARCHIVE_CLEANUP_OUTCOMES == frozenset({"cleaned", "partial", "skipped"})diff --git a/tests/test_skill_cli.py b/tests/test_skill_cli.pyindex 22d54b5fd..6b19b2ae2 100644--- a/tests/test_skill_cli.py+++ b/tests/test_skill_cli.py@@ -1,5 +1,5 @@+import jsonfrom pathlib import Path-from types import SimpleNamespacefrom core import managed_skillsfrom vibe.cli import build_parser, cmd_skill@@ -29,49 +29,73 @@ def _isolate_catalog(monkeypatch, tmp_path: Path) -> Path:return cwd-def test_skill_list_and_load_follow_the_text_protocol(monkeypatch, tmp_path, capsys):+def _skill_content(skill_file: Path, body: str) -> str:+ return f'<skill_content name="{skill_file.parent.name}" directory="{skill_file.parent.resolve()}">\n{body}</skill_content>\n'+++def test_skill_list_prints_the_json_envelope(monkeypatch, tmp_path, capsys):cwd = _isolate_catalog(monkeypatch, tmp_path)- skill_file = _write_skill(- cwd / ".agents" / "skills",- "docs",- "Read project docs.",- "Use references/guide.md\n",- )+ _write_skill(cwd / ".agents" / "skills", "docs", "Read project docs.", "Use references/guide.md\n")- assert cmd_skill(SimpleNamespace(skill_command="list", page=1)) == 0- assert capsys.readouterr().out == "- docs: Read project docs.\n"+ assert cmd_skill(build_parser().parse_args(["skill", "list"])) == 0- assert cmd_skill(SimpleNamespace(skill_command="load", name="docs")) == 0- output = capsys.readouterr().out- assert output == (- f'<skill_content name="docs" directory="{skill_file.parent.resolve()}">\n'- "Use references/guide.md\n"- "</skill_content>\n"- )+ payload = json.loads(capsys.readouterr().out)+ assert payload["schema_version"] == 1+ assert payload["ok"] is True+ assert payload["kind"] == "skills"+ assert payload["skills"] == [{"name": "docs", "description": "Read project docs."}]+ assert payload["pagination"] == {"page": 1, "returned": 1, "has_more": False, "next_page": None}-def test_skill_load_failure_has_empty_stdout(monkeypatch, tmp_path, capsys):- _isolate_catalog(monkeypatch, tmp_path)+def test_skill_load_prints_each_named_skill_in_order_and_fails_on_unknown_names(monkeypatch, tmp_path, capsys):+ cwd = _isolate_catalog(monkeypatch, tmp_path)+ docs = _write_skill(cwd / ".agents" / "skills", "docs", "Read project docs.", "Use references/guide.md\n")+ release = _write_skill(cwd / ".agents" / "skills", "release", "Cut a release.", "Tag it.\n")+ args = build_parser().parse_args(["skill", "load", "--", "release", "missing", "docs"])++ assert cmd_skill(args) == 1- assert cmd_skill(SimpleNamespace(skill_command="load", name="missing")) == 1captured = capsys.readouterr()- assert captured.out == ""- assert captured.err == "Skill not found: missing\n"+ assert captured.out == _skill_content(release, "Tag it.\n") + _skill_content(docs, "Use references/guide.md\n")+ error = json.loads(captured.err)+ assert error["kind"] == "error"+ assert error["code"] == "skill_not_found"+ assert error["details"] == {"missing": ["missing"], "loaded": ["release", "docs"]}-def test_skill_load_parser_accepts_the_canonical_separator_form():- args = build_parser().parse_args(["skill", "load", "--", "pdf-processing"])+def test_skill_load_of_known_names_succeeds_with_skill_text_only(monkeypatch, tmp_path, capsys):+ cwd = _isolate_catalog(monkeypatch, tmp_path)+ docs = _write_skill(cwd / ".agents" / "skills", "docs", "Read project docs.", "Use references/guide.md\n")- assert args.skill_command == "load"- assert args.name == "pdf-processing"+ assert cmd_skill(build_parser().parse_args(["skill", "load", "--", "docs"])) == 0+ captured = capsys.readouterr()+ assert captured.out == _skill_content(docs, "Use references/guide.md\n")+ assert captured.err == ""-def test_skill_cli_localizes_errors(monkeypatch, tmp_path, capsys):- _isolate_catalog(monkeypatch, tmp_path)- monkeypatch.setattr("vibe.cli._configured_cli_language", lambda: "zh")- assert cmd_skill(SimpleNamespace(skill_command="load", name="missing")) == 1+def test_cli_json_keeps_non_ascii_text_as_itself(monkeypatch, tmp_path, capsys):+ cwd = _isolate_catalog(monkeypatch, tmp_path)+ _write_skill(cwd / ".agents" / "skills", "docs", "阅读项目文档", "Body\n")- captured = capsys.readouterr()- assert captured.out == ""- assert captured.err == "未找到 Skill:missing\n"+ assert cmd_skill(build_parser().parse_args(["skill", "list"])) == 0++ output = capsys.readouterr().out+ assert '"description": "阅读项目文档"' in output+ assert "\\u" not in output+++def test_cli_json_escapes_text_a_legacy_code_page_cannot_carry(monkeypatch, tmp_path):+ import io+ import sys++ cwd = _isolate_catalog(monkeypatch, tmp_path)+ _write_skill(cwd / ".agents" / "skills", "docs", "阅读项目文档", "Body\n")+ raw = io.BytesIO()+ monkeypatch.setattr(sys, "stdout", io.TextIOWrapper(raw, encoding="cp1252"))++ assert cmd_skill(build_parser().parse_args(["skill", "list"])) == 0++ sys.stdout.flush()+ payload = json.loads(raw.getvalue().decode("cp1252"))+ assert payload["skills"] == [{"name": "docs", "description": "阅读项目文档"}]diff --git a/tests/test_skill_observability.py b/tests/test_skill_observability.pyindex 8c742bf82..1d9716c92 100644--- a/tests/test_skill_observability.py+++ b/tests/test_skill_observability.py@@ -386,8 +386,8 @@ def test_cli_transport_failure_preserves_output_and_exit(monkeypatch, capsys):monkeypatch.setattr(managed_skills, "load_skill", lambda *args, **kwargs: skill())monkeypatch.setattr("vibe.internal_client.record_skill_observation_sync", Mock(side_effect=TimeoutError))assert cli.cmd_skill(SimpleNamespace(skill_command="list", page=1)) == 0- assert capsys.readouterr().out == "- docs: Project documentation\n"- assert cli.cmd_skill(SimpleNamespace(skill_command="load", name="docs")) == 0+ assert json.loads(capsys.readouterr().out)["skills"] == [{"name": "docs", "description": "Project documentation"}]+ assert cli.cmd_skill(SimpleNamespace(skill_command="load", names=["docs"])) == 0output = capsys.readouterr()assert "Read the docs." in output.out and output.err == ""@@ -401,11 +401,26 @@ def test_cli_observes_actual_loaded_snapshot(monkeypatch):monkeypatch.setattr("core.managed_skills.load_skill", lambda *args, **kwargs: loaded)submitted = Mock(return_value={"status": "queued"})monkeypatch.setattr("vibe.internal_client.record_skill_observation_sync", submitted)- assert cli.cmd_skill(SimpleNamespace(skill_command="load", name="docs")) == 0+ assert cli.cmd_skill(SimpleNamespace(skill_command="load", names=["docs"])) == 0event = submitted.call_args.args[0]assert event["content"]["skill_revision"] == runtime.load_result("docs", loaded, duration_ms=0)["skill_revision"]+def test_cli_observes_each_name_of_a_multi_skill_load(monkeypatch, capsys):+ from vibe import cli++ monkeypatch.setattr("core.managed_skills.resolve_skills", lambda: [skill()])+ monkeypatch.setattr("core.managed_skills.load_skill", lambda *args, **kwargs: skill())+ submitted = Mock(return_value={"status": "queued"})+ monkeypatch.setattr("vibe.internal_client.record_skill_observation_sync", submitted)++ assert cli.cmd_skill(SimpleNamespace(skill_command="load", names=["docs", "missing"])) == 1++ capsys.readouterr()+ loads = [call.args[0]["content"] for call in submitted.call_args_list]+ assert [(event["skill_name"], event["error_code"]) for event in loads] == [("docs", None), ("missing", "not_found")]++def test_runtime_candidate_requires_acceptance(monkeypatch):from core.system_prompt_injection import build_system_prompt_injection@@ -583,20 +598,17 @@ def test_clear_command_requires_explicit_confirmation(engine, capsys):assert counts(engine) == (0, None)[email protected]("language", ["en", "zh"])@pytest.mark.parametrize(- "owner,clear,yes,code,key",+ "owner,clear,yes,code,error",[- (False, False, False, "forbidden", "ownerRequired"),- (True, True, False, "confirmation_required", "confirmationRequired"),- (True, False, True, "invalid_arguments", "clearRequired"),+ (False, False, False, "forbidden", "Instance Member or Owner access is required."),+ (True, True, False, "confirmation_required", "Clearing Skill statistics requires --yes."),+ (True, False, True, "invalid_arguments", "--yes requires --clear."),],)-def test_skill_usage_errors_follow_cli_language(monkeypatch, capsys, language, owner, clear, yes, code, key):+def test_skill_usage_errors_name_the_refusal(monkeypatch, capsys, owner, clear, yes, code, error):from vibe import cli- from vibe.i18n import t- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)monkeypatch.setattr("storage.resource_access_service.resolve_resource_access_context",lambda _caller: SimpleNamespace(can_manage_instance=owner),@@ -606,23 +618,20 @@ def test_skill_usage_errors_follow_cli_language(monkeypatch, capsys, language, oassert captured.out == ""payload = json.loads(captured.err)assert payload["code"] == code- assert payload["error"] == t(f"data.skillUsage.{key}", language)+ assert payload["error"] == error[email protected]("language", ["en", "zh"])-def test_skill_usage_help_follows_cli_language(monkeypatch, capsys, language):+def test_skill_usage_help_names_its_manager_floor(capsys):from vibe import cli- from vibe.i18n import t- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)with pytest.raises(SystemExit) as exit_info:cli.build_parser().parse_args(["data", "skill-usage", "--help"])assert exit_info.value.code == 0output = capsys.readouterr().out- for key in ("helpCommand", "helpClear", "helpYes"):- assert t(f"data.skillUsage.{key}", language) in output- assert ("Member or Owner" if language == "en" else "管理者或所有者") in output- assert ("Owner only" if language == "en" else "仅限实例所有者") not in output+ assert "Inspect or clear local Skill statistics (Instance Member or Owner)" in output+ assert "Clear Skill events and daily statistics." in output+ assert "Confirm clearing Skill statistics." in output+ assert "Owner only" not in output@pytest.mark.parametrize("role", ["owner", "member"])diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex e355bcc19..3dfe150e5 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -1465,7 +1465,10 @@ def test_sessions_fork_on_archived_source_survives_ui_error_parse(monkeypatch, tassert isinstance(body.get("message"), str) and body["message"]-def test_doctor_post_runs_fast_diagnostics_by_default(monkeypatch):+def test_doctor_post_runs_fast_diagnostics_by_default_in_the_ui_language(monkeypatch):+ from types import SimpleNamespace++ from core.services import settings as settings_servicefrom vibe import clicalls = []@@ -1473,16 +1476,18 @@ def test_doctor_post_runs_fast_diagnostics_by_default(monkeypatch):monkeypatch.setattr(cli,"_doctor",- lambda *, deep=True: calls.append(deep)+ lambda *, deep=True, language="en": calls.append((deep, language))or {"mode": "fast", "groups": [], "summary": {"pass": 0, "warn": 0, "fail": 0}, "ok": True},)+ # The CLI renders Doctor in English; the Web panel keeps the configured UI language.+ monkeypatch.setattr(settings_service, "load_config_or_default", lambda: SimpleNamespace(language="zh"))client = app.test_client()response = client.post("/api/doctor", json={}, headers=csrf_headers(client))assert response.status_code == 200assert response.get_json()["mode"] == "fast"- assert calls == [False]+ assert calls == [(False, "zh")]def test_doctor_post_can_run_deep_diagnostics(monkeypatch):@@ -1493,7 +1498,7 @@ def test_doctor_post_can_run_deep_diagnostics(monkeypatch):monkeypatch.setattr(cli,"_doctor",- lambda *, deep=True: calls.append(deep)+ lambda *, deep=True, language="en": calls.append(deep)or {"mode": "deep", "groups": [], "summary": {"pass": 0, "warn": 0, "fail": 0}, "ok": True},)diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex e39da65c7..291512e36 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -2394,22 +2394,14 @@ def test_public_show_page_implicit_markdown_preserves_admission_errors(def test_show_cli_guidance_distinguishes_public_and_private_markdown_contracts():- translations = {- language: json.loads(- (Path(ui_server.__file__).parent / "i18n" / f"{language}.json").read_text(- encoding="utf-8"- )- )["show"]["markdown"]["help"]- for language in ("en", "zh")- }+ from vibe import cli++ guidance = cli._show_examples_text()- assert "Public Show Page" in translations["en"]- assert "automatically" in translations["en"]- assert "authorized private" in translations["en"]- assert "公共 Show Page" in translations["zh"]- assert "自动" in translations["zh"]- assert "已授权的私有页面" in translations["zh"]- assert all("Accept: text/markdown" in value for value in translations.values())+ assert "Public Show Page" in guidance+ assert "automatically" in guidance+ assert "authorized private" in guidance+ assert "Accept: text/markdown" in guidance@pytest.mark.parametrize(diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.pyindex 9f4c47072..71ec5d325 100644--- a/tests/test_upgrade_flow.py+++ b/tests/test_upgrade_flow.py@@ -1163,11 +1163,8 @@ def test_do_upgrade_keeps_active_launcher_when_staged_install_fails(monkeypatch,assert launcher.resolve() == old.resolve()- ("language", "expected"),- [("en", "Upgrade activated the new version"), ("zh", "升级已激活新版本")],-)-def test_cmd_upgrade_reports_peer_activation_failures(monkeypatch, tmp_path, capsys, language, expected):+def test_cmd_upgrade_reports_peer_activation_failures(monkeypatch, tmp_path, capsys):+ expected = "Upgrade activated the new version"launcher = tmp_path / "activated home 空格" / "vibe"peer = tmp_path / "peer home 空格" / "稳定-vibe"outcome = vibe_upgrade.ActivationOutcome(@@ -1188,7 +1185,6 @@ def test_cmd_upgrade_reports_peer_activation_failures(monkeypatch, tmp_path, capmonkeypatch.setattr(cli, "cache_running_vibe_path", lambda: str(launcher))monkeypatch.setattr(cli, "build_upgrade_plan", lambda **_kwargs: plan)monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: False)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: outcome)monkeypatch.setattr(cli,@@ -1791,13 +1787,13 @@ def test_cmd_check_update_reports_desktop_managed_runtime(monkeypatch, capsys):assert "Updates are delivered with the Avibe desktop app." in capsys.readouterr().out-def test_desktop_managed_runtime_messages_follow_configured_language(monkeypatch, capsys):+def test_desktop_managed_runtime_messages_are_english_in_the_cli_and_localized_on_the_web(monkeypatch, capsys):monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")monkeypatch.setattr(cli.V2Config, "load", lambda: SimpleNamespace(language="zh"))monkeypatch.setattr(api.V2Config, "load", lambda: SimpleNamespace(language="zh"))assert cli.cmd_check_update() == 0- assert "更新由 Avibe 桌面应用统一提供。" in capsys.readouterr().out+ assert "Updates are delivered with the Avibe desktop app." in capsys.readouterr().outassert api.do_upgrade()["message"] == "此 Runtime 由 Avibe 桌面应用管理。"diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex 6638b0bc8..ab6e531fd 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -76,6 +76,75 @@ def _write_alembic_revision(db_path: Path, revision: str) -> None:conn.execute("insert into alembic_version values (?)", (revision,))+def test_cli_text_is_english_whatever_the_ui_language(monkeypatch, tmp_path, capsys):+ """Agents read CLI help and errors; they stay English when the Web UI is set to Chinese."""++ import argparse++ config_path = tmp_path / "config.json"+ config_path.write_text(json.dumps({"language": "zh"}), encoding="utf-8")+ monkeypatch.setattr(cli.paths, "get_config_path", lambda: config_path)+ monkeypatch.setattr(cli.V2Config, "load", lambda *_args, **_kwargs: SimpleNamespace(language="zh"))+ han = re.compile(r"[\u4e00-\u9fff]")++ def leaves(parser, path=()):+ yield path, parser+ for action in parser._actions:+ if isinstance(action, argparse._SubParsersAction):+ for name, child in action.choices.items():+ yield from leaves(child, (*path, name))++ for path, parser in leaves(cli.build_parser()):+ help_text = parser.format_help()+ assert not han.search(help_text), f"vibe {' '.join(path)} --help is not English"++ with pytest.raises(SystemExit):+ cli.build_parser().parse_args(["skill", "load"])+ assert not han.search(capsys.readouterr().err)+++def test_top_level_help_lists_only_public_commands(capsys):+ parser = cli.build_parser()++ with pytest.raises(SystemExit):+ parser.parse_args(["--help"])++ help_text = capsys.readouterr().out+ assert "==SUPPRESS==" not in help_text+ assert not re.search(r"[{,]desktop[,}]|^\s+desktop\s", help_text, re.MULTILINE)+ # The desktop shell's own entry point still runs.+ assert parser.parse_args(["desktop", "endpoint", "--json"]).desktop_command == "endpoint"+++ "argv",+ [+ ["hook", "send", "--session-id", "ses1", "--message", "hi"],+ ["task", "ls"],+ ["watch", "rm", "watch1"],+ ["agent", "run", "--agent", "a", "--async", "--message", "hi"],+ ["agent", "run", "--session-id", "ses1", "--send-now", "--message", "hi"],+ ["agent", "run", "--agent", "a", "--create-session", "--message", "hi"],+ ["agent", "run", "--agent", "a", "--visibility", "foreground", "--message", "hi"],+ ["agent", "run", "--agent", "a", "--prompt", "hi"],+ ["agent", "create", "a", "--backend", "codex", "--effort", "high"],+ ["task", "add", "--session-key", "slack::channel::C1", "--cron", "0 * * * *", "--message", "hi"],+ ["watch", "add", "--session-id", "ses1", "--prefix", "hi", "--shell", "true"],+ ["session", "get", "ses1"],+ ["session", "update", "--session-id", "ses1", "--visibility", "background"],+ ["show", "mark", "--target", "t", "--body", "hi"],+ ],+)+def test_removed_spellings_are_unknown(argv, capsys):+ """One spelling per concept: a removed alias, flag, or command is an argument error."""++ with pytest.raises(SystemExit) as exc_info:+ cli.build_parser().parse_args(argv)++ assert exc_info.value.code == 2+ assert json.loads(capsys.readouterr().err)["code"] == "invalid_arguments"++def test_retention_help_reads_raw_config_without_loading_or_migrating(monkeypatch, tmp_path):config_path = tmp_path / "config.json"config_path.write_text(@@ -88,7 +157,7 @@ def test_retention_help_reads_raw_config_without_loading_or_migrating(monkeypatcraise AssertionError("help construction must not load or migrate V2Config")monkeypatch.setattr(cli.V2Config, "load", _load_should_not_run)- assert cli._configured_trace_retention_days("en") == 90+ assert cli._configured_trace_retention_days() == 90cli.build_parser()@@ -100,7 +169,7 @@ def test_retention_help_ignores_oversized_configured_window(monkeypatch, tmp_pat)monkeypatch.setattr(cli.paths, "get_config_path", lambda: config_path)- assert cli._configured_trace_retention_days("en") == 30+ assert cli._configured_trace_retention_days() == 30@pytest.mark.parametrize(@@ -113,12 +182,12 @@ def test_retention_help_ignores_oversized_configured_window(monkeypatch, tmp_pat),("zh",- "不提供密钥时,命令会继续本机可恢复的配对",- "要替换结果不确定的待处理配对",+ "Without a key, the CLI resumes a recoverable local pairing",+ "To replace an uncertain pending attempt",),],)-def test_remote_pair_help_localizes_recovery_guidance(+def test_remote_pair_help_is_english_whatever_the_ui_language(monkeypatch, tmp_path, capsys, language, resume_hint, replacement_hint,):monkeypatch.setenv("COLUMNS", "240")@@ -135,8 +204,6 @@ def test_remote_pair_help_localizes_recovery_guidance(assert resume_hint in outputassert replacement_hint in outputassert "vibe remote pair --backend-url https://avibe.bot" in output- if language == "zh":- assert "Without a key, the CLI resumes" not in outputdef test_local_cli_installation_items_pass_for_normal_uv_tool(monkeypatch, tmp_path):@@ -359,9 +426,8 @@ def test_tied_installs_are_never_ranked_by_discovery_order(split_launchers, monk_reinstall_same_version(split)for generation in (split.old, split.new):os.utime(generation / "uv" / "tools" / "avibe-os" / "uv-receipt.toml", (1_500_000, 1_500_000))- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")- item, = cli._stable_launcher_items()+ item, = cli._stable_launcher_items(language="zh")assert item["status"] == "fail"for launcher, generation in ((split.path_launcher, split.old), (split.installer_launcher, split.new)):@@ -374,7 +440,7 @@ def test_tied_installs_are_never_ranked_by_discovery_order(split_launchers, monkassert result["status"] == "failed"assert result["reason"] == "stable_launchers_tied"- assert "没有改动任何启动器" in result["message"]+ assert "No launcher was changed" in result["message"]assert split.path_launcher.resolve() == (split.old / "bin" / "vibe").resolve()assert split.installer_launcher.resolve() == (split.new / "bin" / "vibe").resolve()@@ -390,15 +456,14 @@ def test_tied_installs_are_never_ranked_by_discovery_order(split_launchers, monk@pytest.mark.parametrize("failure", ["unwritable-launcher", "missing-export", "lock-busy"])-def test_stable_launcher_repair_failures_are_localized(split_launchers, monkeypatch, failure):- """No exception text reaches the localized repair message."""+def test_stable_launcher_repair_failures_name_the_cause_without_exception_text(split_launchers, monkeypatch, failure):+ """No exception text reaches the repair message."""split = split_launchers- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")reason, fragment = {- "unwritable-launcher": ("stable_launcher_move_failed", "请确认你有权限写入它"),- "missing-export": ("stable_launcher_move_failed", "请确认你有权限写入它"),- "lock-busy": ("upgrade_lock_busy", "另一个 Avibe 安装、升级或修复正在进行"),+ "unwritable-launcher": ("stable_launcher_move_failed", "Make sure you can write to it"),+ "missing-export": ("stable_launcher_move_failed", "Make sure you can write to it"),+ "lock-busy": ("upgrade_lock_busy", "Another Avibe install, upgrade or repair is running"),}[failure]if failure == "unwritable-launcher":if os.name != "posix" or os.geteuid() == 0:@@ -434,7 +499,6 @@ def test_windows_repair_leaves_the_launcher_it_runs_from_and_names_the_target(sppeer.parent.mkdir()peer.symlink_to(split.old / "bin" / "vibe")monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(split.installer_launcher.parent), str(peer.parent)))- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")# Stand-in for Windows holding the stale PATH launcher's image open.monkeypatch.setattr(cli, "launcher_is_current_process", lambda launcher: Path(launcher) == split.path_launcher)@@ -443,7 +507,7 @@ def test_windows_repair_leaves_the_launcher_it_runs_from_and_names_the_target(spassert result["status"] == "failed"assert result["reason"] == "stable_launcher_running"assert result["launchers"] == [str(peer)]- assert str(split.path_launcher) in result["message"] and "Windows 无法" in result["message"]+ assert str(split.path_launcher) in result["message"] and "Windows cannot replace" in result["message"]commands = [shlex.split(command) for command in re.findall(r"`([^`]+)`", result["message"])]assert [str(split.installer_launcher), "doctor", "repair", "stable-launchers"] in commandsassert peer.resolve() == (split.new / "bin" / "vibe").resolve()@@ -818,7 +882,6 @@ def test_doctor_reports_degraded_show_checkpoints_without_git(monkeypatch):def test_doctor_lists_stored_cron_tasks_with_numeric_weekdays(monkeypatch):"""Tasks written before numeric weekdays were refused still fire a day off intent."""- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "en")assert cli._scheduled_task_weekday_items() == []store = cli.ScheduledTaskStore()@@ -851,21 +914,22 @@ def test_doctor_surfaces_configuration_recovery_warnings(monkeypatch, tmp_path):monkeypatch.setattr(paths, "get_config_path", lambda: config_path)monkeypatch.setattr(paths, "get_runtime_doctor_path", lambda: doctor_path)monkeypatch.setattr(cli.V2Config, "load", lambda _path: config)- monkeypatch.setattr(cli, "_home_migration_items", lambda: [])+ monkeypatch.setattr(cli, "_home_migration_items", lambda **_kwargs: [])monkeypatch.setattr(cli, "_service_lifecycle_items", lambda **_kwargs: [])monkeypatch.setattr(cli, "_service_install_family_items", lambda **_kwargs: [])- monkeypatch.setattr(cli, "_restart_state_items", lambda: [])- monkeypatch.setattr(cli, "_runtime_architecture_items", lambda: [])- monkeypatch.setattr(cli, "_show_git_checkpoint_items", lambda: [])+ monkeypatch.setattr(cli, "_restart_state_items", lambda **_kwargs: [])+ monkeypatch.setattr(cli, "_runtime_architecture_items", lambda **_kwargs: [])+ monkeypatch.setattr(cli, "_show_git_checkpoint_items", lambda **_kwargs: [])monkeypatch.setattr(cli, "_managed_dependencies_doctor_items", lambda **_kwargs: [])monkeypatch.setattr(cli, "_show_runtime_doctor_items", lambda **_kwargs: [])- monkeypatch.setattr(cli, "_local_cli_installation_items", lambda: [])+ monkeypatch.setattr(cli, "_local_cli_installation_items", lambda **_kwargs: [])monkeypatch.setattr(cli.api, "detect_cli", lambda _path, _backend: {"found": False, "path": None, "status": "missing"})- result = cli._doctor()+ result = cli._doctor(language="zh")- config_group = next(group for group in result["groups"] if group["name"] == "Configuration")- recovery_item = next(item for item in config_group["items"] if item.get("code") == "config.recovery")+ recovery_item = next(+ item for group in result["groups"] for item in group["items"] if item.get("code") == "config.recovery"+ )assert recovery_item["status"] == "warn"assert recovery_item["code"] == "config.recovery"assert recovery_item["message"] != warning@@ -3034,9 +3098,8 @@ def test_show_runtime_doctor_retires_legacy_source_with_actionable_replacement(archive_cache_status=lambda: {"candidate_count": 0, "candidate_bytes": 0, "skipped_reason": None},)monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)- items = cli._show_runtime_doctor_items(deep=False)+ items = cli._show_runtime_doctor_items(language=language, deep=False)failure = next(item for item in items if item.get("code") == "show_runtime.provider_unsupported")assert failure["status"] == "fail"@@ -3173,7 +3236,6 @@ def test_managed_dependencies_doctor_localizes_model_hub_engine_label(installed,code,):- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)monkeypatch.setattr(cli.api,"dependencies_status",@@ -3195,7 +3257,7 @@ def test_managed_dependencies_doctor_localizes_model_hub_engine_label(},)- items = cli._managed_dependencies_doctor_items()+ items = cli._managed_dependencies_doctor_items(language=language)item = next(item@@ -3696,12 +3758,7 @@ def test_repair_show_runtime_returns_structured_download_failure(monkeypatch):assert archive_url in result["message"][email protected](("language", "message_fragment"), [("en", "Fix or remove"), ("zh", "\u4fee\u590d\u6216\u79fb\u9664")])-def test_repair_show_runtime_renders_explicit_command_failure(- monkeypatch,- language,- message_fragment,-):+def test_repair_show_runtime_renders_explicit_command_failure(monkeypatch):manager = SimpleNamespace(repair=lambda: {"ok": False,@@ -3712,13 +3769,12 @@ def test_repair_show_runtime_renders_explicit_command_failure(})monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda: manager)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)result = cli._repair_show_runtime()assert result["status"] == "failed"assert result["explicit_command"] == "/custom/runtime"- assert message_fragment in result["message"]+ assert "Fix or remove" in result["message"]def test_runtime_prepare_strict_does_not_report_policy_skip_as_ready(monkeypatch, capsys):@@ -3811,21 +3867,21 @@ def test_runtime_prepare_reports_cpa_failure_without_blocking_avibe_upgrade(@pytest.mark.parametrize(("cpa_result", "expected", "stream"),(- ({"ok": True, "changed": True}, "Model Hub 引擎已安装。", "out"),- ({"ok": True, "changed": False}, "Model Hub 引擎已就绪。", "out"),+ ({"ok": True, "changed": True}, "Model Hub engine installed.", "out"),+ ({"ok": True, "changed": False}, "Model Hub engine ready.", "out"),({"ok": False, "skipped": True, "reason": "offline"},- "Model Hub 引擎:已跳过(offline)。",+ "Model Hub engine: skipped (offline).","out",),({"ok": False, "reason": "download_failed"},- "Model Hub 引擎尚未就绪:download_failed",+ "Model Hub engine not ready: download_failed","err",),),)-def test_runtime_prepare_localizes_cpa_output(+def test_runtime_prepare_reports_cpa_output(monkeypatch,capsys,cpa_result,@@ -3842,7 +3898,6 @@ def test_runtime_prepare_localizes_cpa_output(})monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda _args: manager)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda **_kwargs: {"ok": True})monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})@@ -3869,17 +3924,16 @@ def test_runtime_prepare_localizes_cpa_output(captured = capsys.readouterr()assert expected in getattr(captured, stream)- assert "Model Hub engine" not in captured.out + captured.err@pytest.mark.parametrize(("ripgrep_result", "expected", "stream"),(- ({"ok": True, "changed": True}, "ripgrep 已安装。", "out"),- ({"ok": True, "changed": False}, "ripgrep 已就绪。", "out"),+ ({"ok": True, "changed": True}, "ripgrep installed.", "out"),+ ({"ok": True, "changed": False}, "ripgrep ready.", "out"),({"ok": False, "reason": "ripgrep_platform_unsupported"},- "ripgrep 尚未就绪:ripgrep_platform_unsupported",+ "ripgrep not ready: ripgrep_platform_unsupported","err",),),@@ -3901,7 +3955,6 @@ def test_strict_runtime_prepare_reports_ripgrep_without_requiring_it(})monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda _args: manager)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda **_kwargs: {"ok": True})monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})@@ -4089,23 +4142,8 @@ def test_runtime_clean_json_keeps_nested_failure_payload_and_exits_nonzero(monke@pytest.mark.parametrize("help_args", [("runtime", "--help"), ("runtime", "clean", "--help")])- ("language", "consumer_scope", "failure_contract"),- [- ("en", "Show, Git, Model Hub, tmux, ripgrep, and cloudflared", "exit nonzero if any cleanup fails"),- ("zh", "Show、Git、Model Hub、tmux、ripgrep 和 cloudflared", "任一清理失败时以非零状态退出"),- ],-)-def test_runtime_clean_help_names_consumers_and_failure_exit(- monkeypatch,- capsys,- help_args,- language,- consumer_scope,- failure_contract,-):+def test_runtime_clean_help_names_consumers_and_failure_exit(monkeypatch, capsys, help_args):monkeypatch.setenv("COLUMNS", "240")- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)parser = cli.build_parser()with pytest.raises(SystemExit) as exc_info:@@ -4113,10 +4151,9 @@ def test_runtime_clean_help_names_consumers_and_failure_exit(assert exc_info.value.code == 0output = capsys.readouterr().out- assert cli.i18n_t("runtime.clean.commandHelp", language) in output- assert consumer_scope in output+ assert "Show, Git, Model Hub, tmux, ripgrep, and cloudflared" in outputassert "Memory" not in output- assert failure_contract in output+ assert "exit nonzero if any cleanup fails" in output@pytest.mark.parametrize("legacy_source", ["github", "github-source", "GitHub-Source"])diff --git a/tests/test_watch_job_target.py b/tests/test_watch_job_target.pyindex 272e3ed52..6f5ca6f6a 100644--- a/tests/test_watch_job_target.py+++ b/tests/test_watch_job_target.py@@ -287,8 +287,6 @@ def _resume_in_the_web_ui(watch_id: str, capsys) -> tuple[str, str]:def test_a_job_watch_that_no_longer_owns_its_job_is_never_resumed(tmp_path: Path, capsys, monkeypatch, state: str, resume) -> None:- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")-async def run() -> tuple[LocalJobHost, str, str, tuple[str, str]]:store = ManagedWatchStore()host = _host(tmp_path, store)@@ -317,8 +315,7 @@ def test_a_job_watch_that_no_longer_owns_its_job_is_never_resumed(host, job_id, watch_id, (code, message) = asyncio.run(run())assert code == "job_watch_not_resumable"- language = "zh" if resume is _resume_in_the_cli else "en"- assert message == i18n_t("error.jobWatchResumeRefused.message", language)+ assert message == i18n_t("error.jobWatchResumeRefused.message", "en")assert not ManagedWatchStore().get_watch(watch_id).enabledif state == "released":assert len(_follow_ups(watch_id)) == 1@@ -328,7 +325,7 @@ def test_a_job_watch_that_no_longer_owns_its_job_is_never_resumed(assert host.stop_reason(job_id) == "watch_disabled"-def test_changing_a_job_watch_waiter_is_refused_in_the_user_language(tmp_path: Path, capsys, monkeypatch) -> None:+def test_changing_a_job_watch_waiter_is_refused(tmp_path: Path, capsys, monkeypatch) -> None:async def hand_over() -> tuple[LocalJobHost, str, str]:store = ManagedWatchStore()host = _host(tmp_path, store)@@ -336,7 +333,6 @@ def test_changing_a_job_watch_waiter_is_refused_in_the_user_language(tmp_path: Preturn host, job_id, await host.hand_over(job_id)host, job_id, watch_id = asyncio.run(hand_over())- monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")monkeypatch.setattr(sys, "argv", ["vibe", "watch", "update", watch_id, "--shell", "pytest -q"])with pytest.raises(SystemExit) as exit_info:cli.main()@@ -344,7 +340,9 @@ def test_changing_a_job_watch_waiter_is_refused_in_the_user_language(tmp_path: Passert exit_info.value.code == 1error = json.loads(capsys.readouterr().err)assert error["code"] == "job_watch_update_refused"- assert error["error"] == i18n_t("error.jobWatchUpdateRefused.message", "zh")+ assert error["error"] == (+ "This Watch waits on a command that is already running, so only its name, message, and lifetime can be changed."+ )assert ManagedWatchStore().get_watch(watch_id).job_target["command"] == "sleep 60"# What it does take goes through the same doorway.diff --git a/vibe/cli.py b/vibe/cli.pyindex 7fedb23cb..aacc1c3cb 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -68,7 +68,7 @@ from core.watches import (WatchRuntimeStateStore,)from vibe import __version__, api, runtime-from vibe.i18n import normalize_language, t as i18n_t+from vibe.i18n import t as i18n_tfrom vibe.restart_supervisor import schedule_restartfrom vibe.screenshot import ScreenshotError, capture_screenshotfrom vibe.upgrade import (@@ -290,7 +290,6 @@ class VibeArgumentParser(argparse.ArgumentParser):def __init__(self, *args, **kwargs):self.error_help_command = kwargs.pop("error_help_command", None)self.error_hint = kwargs.pop("error_hint", None)- self.error_i18n_key = kwargs.pop("error_i18n_key", None)super().__init__(*args, **kwargs)def parse_args(self, args=None, namespace=None):@@ -318,12 +317,6 @@ class VibeArgumentParser(argparse.ArgumentParser):return parseddef error(self, message):- if self.error_i18n_key:- message = i18n_t(- self.error_i18n_key,- _configured_cli_language(),- detail=message,- )payload = {"schema_version": 1,"ok": False,@@ -336,7 +329,7 @@ class VibeArgumentParser(argparse.ArgumentParser):payload["hint"] = self.error_hintif self.error_help_command:payload["help_command"] = self.error_help_command- self.exit(2, json.dumps(payload, indent=2) + "\n")+ self.exit(2, _json_text(payload, stream=sys.stderr) + "\n")class TaskCliError(ValueError):@@ -399,14 +392,10 @@ RESERVED_SESSION_CLI_CODE = "reserved_session"def _reserved_session_cli_error(exc: "UnresolvableSessionTarget") -> TaskCliError:"""Re-type the resolver refusal and localize its user-facing guidance."""- try:- lang = V2Config.load().language- except Exception:- lang = "en"return TaskCliError(str(exc),code=RESERVED_SESSION_CLI_CODE,- hint=i18n_t("harness.notice.workspaceSessionReadOnly", lang),+ hint=i18n_t("harness.notice.workspaceSessionReadOnly"),details={"session_id": exc.session_id, "reason": exc.reason},)@@ -480,14 +469,10 @@ def _print_task_error(exc: Exception, *, help_command: str | None = None) -> Nonisinstance(exc, ResourceAccessError)and exc.code == HARNESS_ACCESS_FORBIDDEN_CODE):- try:- lang = V2Config.load().language- except Exception:- lang = "en"exc = TaskCliError(str(exc),code=exc.code,- hint=i18n_t("harness.notice.remoteExecutionDisabled", lang),+ hint="Harness work needs the Editor role on this Avibe instance.",help_command=help_command,)if isinstance(exc, TaskCliError):@@ -516,7 +501,7 @@ def _print_task_error(exc: Exception, *, help_command: str | None = None) -> Non}if help_command:payload["help_command"] = help_command- print(json.dumps(payload, indent=2), file=sys.stderr)+ print(_json_text(payload, stream=sys.stderr), file=sys.stderr)def _definition_conflict_cli_error(@@ -550,11 +535,28 @@ def _cli_payload(kind: str, **fields) -> dict:return {"schema_version": 1, "ok": True, "kind": kind, **fields}+def _json_text(payload: Mapping[str, Any], *, stream: Any) -> str:+ """Indented JSON for the CLI: non-ASCII text as itself, escaped only where ``stream`` cannot carry it.++ Agents read this output, and a ``\\uXXXX`` escape costs six characters per+ character. A stream whose encoding cannot hold the text (a Windows pipe on a+ legacy code page) still gets valid JSON rather than an encoding error.+ """++ text = json.dumps(payload, ensure_ascii=False, indent=2)+ encoding = getattr(stream, "encoding", None) or "utf-8"+ try:+ text.encode(encoding)+ except (UnicodeEncodeError, LookupError):+ return json.dumps(payload, indent=2)+ return text++def _print_cli_payload(kind: str, **fields) -> None:- print(json.dumps(_cli_payload(kind, **fields), indent=2))+ print(_json_text(_cli_payload(kind, **fields), stream=sys.stdout))-def _configured_trace_retention_days(language: str) -> int:+def _configured_trace_retention_days() -> int:"""Read the persisted window for help text without loading/migrating config."""from storage import agent_events_retention as _retention@@ -571,22 +573,9 @@ def _configured_trace_retention_days(language: str) -> int:passexcept Exception:pass- del languagereturn _retention.DEFAULT_RETENTION_DAYS-def _configured_cli_language() -> str:- """Read an optional configured language without creating or migrating state."""-- try:- config_path = paths.get_config_path()- payload = json.loads(config_path.read_text(encoding="utf-8"))- language = payload.get("language") if isinstance(payload, dict) else None- return normalize_language(language if isinstance(language, str) else None)- except Exception:- return "en"--def _redirect_broken_diagnostic_stream(stream: Any) -> None:"""Keep interpreter shutdown from flushing a broken advisory stream."""@@ -638,7 +627,7 @@ def _emit_activation_notice(outcome: Any) -> None:"""Format and emit a peer activation notice without affecting the result."""try:- notice = format_activation_failures(outcome, _configured_cli_language())+ notice = format_activation_failures(outcome)except Exception as exc: # noqa: BLE001notice = f"Stable launcher activation notice unavailable: {exc}"_emit_upgrade_advisory(notice)@@ -648,7 +637,7 @@ def _emit_deferred_activation_notice(log_path: Path | None) -> None:"""Format and emit the deferred helper log location best-effort."""try:- notice = format_deferred_activation_log(log_path, _configured_cli_language())+ notice = format_deferred_activation_log(log_path)except Exception as exc: # noqa: BLE001notice = f"Deferred activation diagnostics unavailable: {exc}"_emit_upgrade_advisory(notice)@@ -658,36 +647,40 @@ def cmd_skill(args) -> int:"""List or load Skills through Avibe's live resolver."""from core.managed_skills import (+ catalog_page,load_skill,render_skill_content,- render_skill_list,resolve_skills,)from core.skill_observability import finish_cli_catalog, finish_cli_load- language = _configured_cli_language()-if args.skill_command == "list":resolved = []observation_error = "internal_error"try:resolved = resolve_skills()- output = render_skill_list(- resolved,- page=args.page,- more_notice=i18n_t(- "skill.cli.more",- language,- page=args.page + 1,- ),+ entries, next_page = catalog_page(resolved, args.page)+ pagination = {+ "page": args.page,+ "returned": len(entries),+ "has_more": next_page is not None,+ "next_page": next_page,+ }+ if next_page is not None:+ pagination["next_command"] = f"vibe skill list --page {next_page}"+ _print_cli_payload(+ "skills",+ skills=[{"name": skill.name, "description": skill.description} for skill in entries],+ pagination=pagination,)- if output:- print(output, flush=True)observation_error = Nonereturn 0except ValueError:observation_error = "invalid_page"- print(i18n_t("skill.cli.error.invalidPage", language), file=sys.stderr)+ _print_task_error(+ TaskCliError("--page must be a positive integer", code="invalid_pagination"),+ help_command="vibe skill list --help",+ )return 1except BrokenPipeError:observation_error = "output_interrupted"@@ -696,30 +689,52 @@ def cmd_skill(args) -> int:finish_cli_catalog(resolved, args.page, observation_error)if args.skill_command == "load":+ # Each name is loaded, printed, and observed on its own, in the order given:+ # an unknown name fails the command without hiding the Skills that did load.+ names = list(dict.fromkeys(args.names))started_at = time.monotonic()- skill = None- observation_error = "internal_error"try:allowed = resolve_skills()- skill = next((entry for entry in allowed if entry.name == args.name), None)- if skill is None:- observation_error = "not_found"- print(i18n_t("skill.cli.error.notFound", language, name=args.name), file=sys.stderr)- return 1- loaded = load_skill(args.name, resolved_skills=allowed)- if loaded is None:- observation_error = "unreadable_or_invalid"- print(i18n_t("skill.cli.error.notFound", language, name=args.name), file=sys.stderr)- return 1- skill = loaded- print(render_skill_content(skill), flush=True)- observation_error = None- return 0- except BrokenPipeError:- observation_error = "output_interrupted"+ except BaseException:+ for name in names:+ finish_cli_load(name, None, started_at, "internal_error")raise- finally:- finish_cli_load(args.name, skill, started_at, observation_error)+ missing: list[str] = []+ for name in names:+ started_at = time.monotonic()+ skill = None+ observation_error = "internal_error"+ try:+ skill = next((entry for entry in allowed if entry.name == name), None)+ if skill is None:+ observation_error = "not_found"+ missing.append(name)+ continue+ loaded = load_skill(name, resolved_skills=allowed)+ if loaded is None:+ observation_error = "unreadable_or_invalid"+ missing.append(name)+ continue+ skill = loaded+ print(render_skill_content(skill), flush=True)+ observation_error = None+ except BrokenPipeError:+ observation_error = "output_interrupted"+ raise+ finally:+ finish_cli_load(name, skill, started_at, observation_error)+ if missing:+ _print_task_error(+ TaskCliError(+ f"Skill not found: {', '.join(missing)}",+ code="skill_not_found",+ hint="Load only names listed in the prompt or returned by `vibe skill list`.",+ details={"missing": missing, "loaded": [name for name in names if name not in missing]},+ ),+ help_command="vibe skill list",+ )+ return 1+ return 0return 1@@ -821,10 +836,8 @@ def cmd_computer(args) -> int:computer_use_sync,)- language = _configured_cli_language()-- def translate(key: str, **kwargs: Any) -> str:- return i18n_t(key, language, **kwargs)+ # Computer Use reports keyed errors; the CLI renders each key's English entry.+ translate = i18n_tcaller_context = caller_context_from_env()caller_session_id = _default_session_id_from_caller(caller_context)@@ -885,7 +898,7 @@ def cmd_computer(args) -> int:)except ComputerCliError as exc:raise TaskCliError(- i18n_t(exc.key, language, **exc.params),+ i18n_t(exc.key, **exc.params),code="invalid_computer_use_arguments",hint=translate("computer.cli.hint.invalidArguments"),help_command="vibe computer --help",@@ -939,7 +952,7 @@ def cmd_computer(args) -> int:screenshot_path = write_screenshot(tool, result, args.output)except ComputerCliError as exc:raise TaskCliError(- i18n_t(exc.key, language, **exc.params),+ i18n_t(exc.key, **exc.params),code="computer_use_screenshot_missing",help_command="vibe computer --help",) from exc@@ -959,6 +972,16 @@ def cmd_computer(args) -> int:return 1 if result.get("isError") is True else 0+_PROMPT_RENDER_INPUT_ERRORS = {+ "invalidContext": "The context must be a JSON object containing only backend, agent_instructions and options.",+ "invalidBackend": "backend must be claude, codex or opencode.",+ "invalidField": "Invalid field type or missing required field: {field}",+ "unknownField": "Unknown field: {field}",+ "unreadableContext": "Cannot read the context file. Check its path and permissions.",+ "invalidJson": "The context file must contain valid UTF-8 JSON.",+}++def cmd_debug_prompt(args) -> int:"""Export all authored sources, optionally with the production rendering."""@@ -984,15 +1007,13 @@ def cmd_debug_prompt(args) -> int:raise PromptRenderInputError("invalidContext")payload = export_prompt_studio_catalog(render_context=context)except PromptRenderInputError as exc:- language = _configured_cli_language()- error = i18n_t(f"debug.cli.error.{exc.key}", language, field=exc.field)- print(i18n_t("debug.cli.error.promptExport", language, error=error), file=sys.stderr)+ error = _PROMPT_RENDER_INPUT_ERRORS.get(exc.key, "Invalid prompt rendering input.").format(field=exc.field)+ print(f"Prompt export failed: {error}", file=sys.stderr)return 1except (OSError, ValueError, TypeError):logger.debug("Prompt export failed", exc_info=True)- language = _configured_cli_language()- error = i18n_t("debug.cli.error.renderFailed", language)- print(i18n_t("debug.cli.error.promptExport", language, error=error), file=sys.stderr)+ error = "Cannot render the prompt sources. Check the sources and rendering inputs."+ print(f"Prompt export failed: {error}", file=sys.stderr)return 1print(json.dumps(payload, ensure_ascii=False, indent=2))return 0@@ -1003,7 +1024,7 @@ def _add_pagination_args(parser, *, help_command: str) -> None:parser.add_argument("--limit",type=int,- help=f"Rows per page. Defaults to {DEFAULT_PAGE_LIMIT}; maximum {MAX_PAGE_LIMIT}.",+ help=f"Rows per page. Defaults to {DEFAULT_PAGE_LIMIT}; values above {MAX_PAGE_LIMIT} read {MAX_PAGE_LIMIT}.",)parser.error_help_command = help_command@@ -1012,7 +1033,7 @@ def _add_brief_arg(parser, *, list_command: str) -> None:parser.add_argument("--brief",action="store_true",- help=i18n_t("harness.cli.help.brief", _configured_cli_language(), list_command=list_command),+ help=f"Print only the compact row that '{list_command}' prints for this record",)@@ -1034,11 +1055,18 @@ def _add_vault_approval_wait_args(parser, *, default_seconds: int = DEFAULT_VAULdef _page_request_from_args(args, *, help_command: str) -> PageRequest:+ """One page of a CLI list. A ``--limit`` above the maximum reads the maximum.++ Asking for more rows than one page holds is not a different decision, so it is+ served rather than refused; the response's ``pagination.limit`` reports the+ limit actually used, and ``next_command`` continues from there.+ """++ limit = getattr(args, "limit", None)+ if limit is not None:+ limit = min(limit, MAX_PAGE_LIMIT)try:- return make_page_request(- page=getattr(args, "page", None),- limit=getattr(args, "limit", None),- )+ return make_page_request(page=getattr(args, "page", None), limit=limit)except ValueError as exc:raise TaskCliError(str(exc), code="invalid_pagination", help_command=help_command) from exc@@ -1064,21 +1092,10 @@ def _paginated_fields(page_result, *, command: list[str], include_next_command:# ``next_command`` is the continuation whenever the command can be replayed;# only a page it cannot name (SQL piped on stdin) needs telling how to go on.if page_payload["has_more"] and "next_command" not in page_payload:- fields["message"] = i18n_t("common.moreRecordsAddPage", _configured_cli_language())+ fields["message"] = "More records are available. Add --page to continue."return fields-def _text_page_continuation(payload: Mapping[str, object]) -> Optional[str]:- """How a text printer tells a person to continue; JSON carries ``pagination.next_command``."""-- pagination = payload.get("pagination")- next_command = pagination.get("next_command") if isinstance(pagination, Mapping) else None- if next_command:- return i18n_t("common.moreRecordsContinueWith", _configured_cli_language(), command=next_command)- message = payload.get("message")- return str(message) if message else None--def _print_definition_list_payload(page_result,*,@@ -1215,32 +1232,6 @@ def _task_update_examples_text() -> str:)-def _hook_send_examples_text() -> str:- return dedent(- """\- Deprecated:- `vibe hook send` is a compatibility entrypoint.- New automation should use `vibe agent run`.-- Session target:- Use --session-id with the target Agent Session ID, for example sesk8m4q2p7x.-- Guidance:- If this is your first time creating an async one-shot run, use `vibe agent run --help`.- `vibe hook send` queues one deprecated asynchronous compatibility turn without persisting a scheduled task.- `--session-id` chooses which Agent Session Avibe will continue using for that one async turn.- Keep the current session id when the hook should continue in the same session.- If no session id is available, trigger this from an active Avibe conversation instead of guessing.- For new async one-shot work, prefer `vibe agent run`.- `--message` and `--message-file` provide the one-shot async user message that will be queued immediately.-- Examples:- vibe agent run --session-id sesk8m4q2p7x --no-callback --message 'The export finished. Share the summary.'- vibe agent run --session-id sesk8m4q2p7x --no-callback --message 'Run the benchmark; I will inspect the run later.'- """- )--def _watch_examples_text() -> str:return dedent("""\@@ -1298,9 +1289,8 @@ def _architecture_token(text: str | None) -> str | None:return None-def _runtime_architecture_items() -> list[dict[str, str]]:+def _runtime_architecture_items(*, language: str = "en") -> list[dict[str, str]]:items: list[dict[str, str]] = []- language = _configured_cli_language()unknown_value = i18n_t("doctor.value.unknown", language)is_apple_silicon = _is_apple_silicon_host()host_arch = "Apple Silicon" if is_apple_silicon else platform.machine() or unknown_value@@ -1359,9 +1349,8 @@ def _path_points_to(path: Path, target: Path) -> bool:return resolved_path is not None and resolved_target is not None and resolved_path == resolved_target-def _home_migration_items() -> list[dict]:+def _home_migration_items(*, language: str = "en") -> list[dict]:items: list[dict] = []- language = _configured_cli_language()explicit_home = os.environ.get(paths.AVIBE_HOME_ENV)if explicit_home:_add_doctor_item(@@ -1501,7 +1490,7 @@ def _launcher_command(launcher: Path | str, *args: str) -> str:return shlex.join([str(launcher), *args])-def _service_generation_items() -> list[dict]:+def _service_generation_items(*, language: str = "en") -> list[dict]:"""Warn when the running service is older than the last activated install."""items: list[dict] = []@@ -1509,7 +1498,6 @@ def _service_generation_items() -> list[dict]:downgrade = generation_downgrade(process_generation(owner_pid)) if owner_pid else Noneif downgrade is None:return items- language = _configured_cli_language()_add_doctor_item(items,"warn",@@ -1532,9 +1520,8 @@ def _service_generation_items() -> list[dict]:return items-def _service_install_family_items(*, detect_extra_processes: bool = True) -> list[dict]:+def _service_install_family_items(*, language: str = "en", detect_extra_processes: bool = True) -> list[dict]:items: list[dict] = []- language = _configured_cli_language()current_family = _current_cli_install_family()owner_pid = runtime.resolve_service_owner_pid(include_starting=False)service_pids = [pid for pid in [owner_pid] if pid]@@ -1622,9 +1609,8 @@ def _restart_failure_summary(payload: dict, language: str) -> str:return " ".join(i18n_t(key, language, value=value) for key, value in pairs if value)-def _restart_state_items() -> list[dict]:+def _restart_state_items(*, language: str = "en") -> list[dict]:items: list[dict] = []- language = _configured_cli_language()restart_path = runtime.get_restart_status_path()payload = runtime.read_json(restart_path) or {}if not payload:@@ -1739,9 +1725,8 @@ def _restart_state_items() -> list[dict]:return items-def _service_lifecycle_items(*, detect_extra_processes: bool = True) -> list[dict]:+def _service_lifecycle_items(*, language: str = "en", detect_extra_processes: bool = True) -> list[dict]:items: list[dict] = []- language = _configured_cli_language()missing_value = i18n_t("doctor.value.missing", language)pid_path = paths.get_runtime_pid_path()recorded_pid: int | None = None@@ -1861,7 +1846,7 @@ def _service_lifecycle_items(*, detect_extra_processes: bool = True) -> list[dicreturn items-def _show_git_checkpoint_items() -> list[dict]:+def _show_git_checkpoint_items(*, language: str = "en") -> list[dict]:try:if runtime.resolve_service_owner_pid(include_starting=False):from core.show_git import show_git_checkpointing_active@@ -1878,13 +1863,13 @@ def _show_git_checkpoint_items() -> list[dict]:return [{"status": "warn",- "message": i18n_t("doctor.item.showGitUnavailable", _configured_cli_language()),+ "message": i18n_t("doctor.item.showGitUnavailable", language),"code": "runtime.show_git_unavailable",}]-def _scheduled_task_weekday_items() -> list[dict]:+def _scheduled_task_weekday_items(*, language: str = "en") -> list[dict]:"""Warn about stored cron tasks whose numeric weekday may fire a day off intent."""if not paths.get_sqlite_state_path().exists():@@ -1905,7 +1890,6 @@ def _scheduled_task_weekday_items() -> list[dict]:]if not affected:return []- language = _configured_cli_language()return [{"status": "warn",@@ -1936,11 +1920,11 @@ def _remote_examples_text() -> str:def _remote_pair_examples_text() -> str:- return i18n_t("remote_access.cli.pairHelpEpilog", _configured_cli_language())+ return "Guidance:\n This is the direct pairing command for users who already have a pairing key.\n For the guided setup flow, run `vibe remote`.\n Without a key, the CLI resumes a recoverable local pairing, or prompts if none is pending.\n To replace an uncertain pending attempt, explicitly supply a fresh key and the same backend URL.\n Pairing saves the remote-access config and then starts the managed tunnel automatically.\n The pairing key is one-time use; create a fresh key from the Avibe Cloud console if it fails.\n\nExamples:\n vibe remote\n vibe remote pair vrp_abc123\n vibe remote pair --device-name \"Mac Studio\"\n vibe remote pair --backend-url https://avibe.bot"def _show_examples_text() -> str:- markdown_help = i18n_t("show.markdown.help", _configured_cli_language())+ markdown_help = "Public Show Page links automatically return agent-readable Markdown to Agents and command-line clients. For an authorized private read, request the URL with Accept: text/markdown."return dedent("""\A Show Page is one session-scoped visual page that Avibe serves through the Web UI / Avibe Cloud tunnel.@@ -1970,14 +1954,14 @@ def _show_examples_text() -> str:vibe show listvibe show list --global --visibility publicvibe show path --session-id sesk8m4q2p7x- vibe show status --session-id sesk8m4q2p7x --json+ vibe show status --session-id sesk8m4q2p7xvibe show update --session-id sesk8m4q2p7x --visibility publicvibe show update --session-id sesk8m4q2p7x --visibility offlinevibe show mark mark-default-summary --session-id sesk8m4q2p7x --message "Review this summary."vibe show reply show_evt_1a2b3c4d --message "The source changed in W30."- vibe show marks --json+ vibe show marksvibe show unmark mark_1 mark-default-summary- vibe show event --session-id sesk8m4q2p7x --event-json @./show-event.json --json+ vibe show event --session-id sesk8m4q2p7x --event-json @./show-event.jsonvibe show annotate --session-id sesk8m4q2p7x --on --mode screenshotMore:@@ -2020,8 +2004,6 @@ def _show_status_examples_text() -> str:path, visibility, active_url, private_url, public_url, share_id, offline, created_at, updated_at.JSON includes history.mode (managed or self-managed), history.checkpointing_active,and history.git_dir (Avibe's history directory, not the user's repository).-- Use --json when another program or agent will consume the result.""")@@ -2060,8 +2042,7 @@ def _show_mark_examples_text() -> str:Examples:vibe show mark mark-default-summary --session-id sesk8m4q2p7x --message "Review this summary."- vibe show mark summary --session-id sesk8m4q2p7x --scope default --message-file ./comment.txt --json- vibe show mark --target summary --body "Legacy option aliases still work."+ vibe show mark summary --session-id sesk8m4q2p7x --scope default --message-file ./comment.txt""")@@ -2073,7 +2054,7 @@ def _show_event_examples_text() -> str:Examples:vibe show event --session-id sesk8m4q2p7x --type assistant.page.updated --event-json '{"summary":"Updated the plan."}'- vibe show event --session-id sesk8m4q2p7x --event-json @./show-event.json --json+ vibe show event --session-id sesk8m4q2p7x --event-json @./show-event.json""")@@ -2088,13 +2069,13 @@ def _show_annotate_examples_text() -> str:vibe show annotate --session-id sesk8m4q2p7x --onvibe show annotate --session-id sesk8m4q2p7x --on --mode screenshotvibe show annotate --session-id sesk8m4q2p7x --mode smart- vibe show annotate --session-id sesk8m4q2p7x --off --json+ vibe show annotate --session-id sesk8m4q2p7x --off""")def _print_json(payload: dict) -> None:- print(json.dumps(payload, indent=2))+ print(_json_text(payload, stream=sys.stdout))def _watch_add_examples_text() -> str:@@ -2110,7 +2091,7 @@ def _watch_add_examples_text() -> str:`--session-id` chooses which Agent Session Avibe will continue using for follow-up messages from the watch.Use --create-session with --scope-id <scopes.id> to create a reusable Session in a specific existing scope.Use --create-session with --same-scope only from an Avibe Agent shell, where the caller Session scope is available.- Prefer --message or --message-file for follow-up instructions; --prefix is legacy-compatible.+ Use --message or --message-file for follow-up instructions.Terminal failures also send a follow-up and disable the watch.In either mode, an allowed `--retry-exit-code` keeps waiting. A once Watch stops after its first event.A forever Watch waits for each event's Agent Run to finish before re-arming, then applies a five-second safety delay.@@ -2139,10 +2120,9 @@ def _agent_run_examples_text() -> str:Use --session-id to continue an existing Agent Session.The default is P1: steer an active native Turn, start when idle, or fall back to the durable P3 queue.Add --queue to persist this Run as P3 behind the active Turn.- --send-now explicitly selects the same P1 content delivery for an existing Session.- To promote the exact existing P3 queue head without a new message, use: vibe session send-now <session-id>- Inspect queued work with: vibe session queue list <session-id>- Remove one exact queued row with: vibe session queue remove <session-id> <message-id>+ To promote the exact existing P3 queue head without a new message, use: vibe session send-now --session-id <session-id>+ Inspect queued work with: vibe session queue list --session-id <session-id>+ Remove one exact queued row with: vibe session queue remove <message-id> --session-id <session-id>Omit --session-id/--fork-self/--fork-session to create a background Session for --agent.Inside an Agent shell it inherits the caller scope and invocation cwd; outside one it is standalone with its own Show workspace.Use --same-scope to explicitly place a new Session in the caller/source Session's scope.@@ -2162,15 +2142,15 @@ def _agent_run_examples_text() -> str:--fork-session <session-id> creates a new Avibe Agent Session and asks the native backend to fork the source native session on the first turn.Forks keep the same backend, scope, and cwd as the source Session. Passing --agent is allowed only when that Agent uses the same backend.--agent, --model, and --reasoning-effort may override the forked Session's Agent/model/effort.- Do not combine fork flags with --session-id or --create-session.+ Do not combine fork flags with --session-id.Avibe Agent shell examples:vibe agent run --agent release-reviewer --message 'Review the latest deployment result.'vibe agent run --agent release-reviewer --visible --message 'Review this project in a visible sibling Session.'- vibe agent run --session-id sesk8m4q2p7x --send-now --message 'Apply this correction in the current turn.'- vibe session queue list sesk8m4q2p7x- vibe session queue remove sesk8m4q2p7x msg_queued123- vibe session send-now sesk8m4q2p7x+ vibe agent run --session-id sesk8m4q2p7x --message 'Apply this correction in the current turn.'+ vibe session queue list --session-id sesk8m4q2p7x+ vibe session queue remove msg_queued123 --session-id sesk8m4q2p7x+ vibe session send-now --session-id sesk8m4q2p7xNormal terminal examples:vibe agent run --sync --agent release-reviewer --message 'Review the latest CI result and print it here.'@@ -2184,19 +2164,17 @@ def _agent_run_examples_text() -> str:)-def _add_hidden_task_alias(task_subparsers, alias: str, parser) -> None:- alias_parser = task_subparsers.add_parser(- alias,- help=argparse.SUPPRESS,- parents=[parser],- add_help=False,- formatter_class=argparse.RawDescriptionHelpFormatter,- )- alias_parser.error_help_command = getattr(parser, "error_help_command", None)- alias_parser.error_hint = getattr(parser, "error_hint", None)- task_subparsers._choices_actions = [ # type: ignore[attr-defined]- action for action in task_subparsers._choices_actions if action.dest != alias # type: ignore[attr-defined]+def _hide_subcommands(subparsers, *names: str) -> None:+ """Keep internal subcommands runnable while leaving them out of help and usage.++ ``help=argparse.SUPPRESS`` on a subcommand is not honored by the help listing,+ which prints a literal ``==SUPPRESS==`` row and still names it in the choices.+ """++ subparsers._choices_actions = [ # type: ignore[attr-defined]+ action for action in subparsers._choices_actions if action.dest not in names # type: ignore[attr-defined]]+ subparsers.metavar = "{" + ",".join(action.dest for action in subparsers._choices_actions) + "}" # type: ignore[attr-defined]def _write_json(path, payload):@@ -2303,27 +2281,7 @@ def _default_timezone_name() -> str:return "UTC"-def _resolve_prompt_input(args, *, help_command: str, example_command: str) -> str:- if getattr(args, "prompt", None) is not None or getattr(args, "prompt_file", None) is not None:- raise TaskCliError(- "--prompt is deprecated; use --message instead",- code="deprecated_prompt_argument",- hint="Use --message for the user message sent to the Agent, or --message-file for file input.",- example=f"{example_command} --message 'Share the hourly summary.'",- help_command=help_command,- )- return _resolve_message_input(args, help_command=help_command, example_command=example_command)--def _resolve_message_input(args, *, help_command: str, example_command: str) -> str:- if getattr(args, "prompt", None) is not None or getattr(args, "prompt_file", None) is not None:- raise TaskCliError(- "--prompt is deprecated; use --message instead",- code="deprecated_prompt_argument",- hint="Use --message for the user message sent to the Agent, or --message-file for file input.",- example=f"{example_command} --message 'Share the hourly summary.'",- help_command=help_command,- )message = (getattr(args, "message", None) or "").strip()message_file = getattr(args, "message_file", None)if message and message_file:@@ -2377,77 +2335,11 @@ def _resolve_optional_message_input(*,help_command: str,example_command: str,- legacy_prefix: Optional[str] = None,) -> Optional[str]:- if getattr(args, "prompt", None) is not None or getattr(args, "prompt_file", None) is not None:- raise TaskCliError(- "--prompt is deprecated; use --message instead",- code="deprecated_prompt_argument",- hint="Use --message for the user message sent to the Agent, or --message-file for file input.",- example=f"{example_command} --message 'Review the waiter output.'",- help_command=help_command,- )has_message = getattr(args, "message", None) is not None or getattr(args, "message_file", None) is not None- has_prefix = legacy_prefix is not None- if has_message and has_prefix:- raise TaskCliError(- "use either --message/--message-file or --prefix, not both",- code="conflicting_message_inputs",- hint="Use --message for new watches. --prefix is only a compatibility alias.",- help_command=help_command,- )if has_message:return _resolve_message_input(args, help_command=help_command, example_command=example_command)- return legacy_prefix---def _resolve_legacy_prompt_input(args, *, help_command: str, example_command: str) -> str:- prompt = (getattr(args, "prompt", None) or "").strip()- prompt_file = getattr(args, "prompt_file", None)- if prompt and prompt_file:- raise TaskCliError(- "use either --prompt or --prompt-file",- code="conflicting_prompt_inputs",- hint="Pass inline text with --prompt or load it from disk with --prompt-file, but not both.",- help_command=help_command,- )- if prompt:- return prompt- if getattr(args, "prompt", None) is not None:- raise TaskCliError(- "prompt text cannot be empty",- code="empty_prompt",- hint="Provide non-empty text after --prompt, or use --prompt-file with a readable text file.",- help_command=help_command,- )- if prompt_file:- try:- content = Path(prompt_file).read_text(encoding="utf-8").strip()- except OSError as exc:- raise TaskCliError(- f"failed to read prompt file: {exc}",- code="prompt_file_read_failed",- hint="Use --prompt-file with a readable UTF-8 text file.",- example=f"{example_command} --prompt-file briefing.md",- help_command=help_command,- details={"prompt_file": prompt_file},- ) from exc- if not content:- raise TaskCliError(- "prompt file is empty",- code="empty_prompt",- hint="Put the prompt text in the file, or pass it directly with --prompt.",- example=f"{example_command} --prompt 'Share the hourly summary.'",- help_command=help_command,- details={"prompt_file": prompt_file},- )- return content- raise TaskCliError(- "one of --prompt or --prompt-file is required",- code="missing_prompt",- hint="Pass inline text with --prompt or load it from disk with --prompt-file.",- help_command=help_command,- )+ return Nonedef _normalize_run_at(value: str, timezone_name: str) -> str:@@ -2926,7 +2818,7 @@ def _parse_validated_session_key(# reply can't attach to a workbench session (persist_agent_message can't# resolve a project scope) — target workbench sessions by --session-id.raise TaskCliError(- "avibe workbench sessions must be targeted with --session-id, not --session-key",+ "avibe workbench sessions must be targeted by Agent Session ID",code="avibe_requires_session_id",hint="A workbench session key has no agent session id, so the reply wouldn't attach to the Chat. Pass the session id via --session-id.",example="--session-id ses3chKBjP5hy",@@ -2976,25 +2868,17 @@ def _resolve_session_target_args(*,required: bool,help_command: str,-) -> tuple[Optional[str], str]:+) -> Optional[str]:session_id = (getattr(args, "session_id", None) or "").strip()- session_key = (getattr(args, "session_key", None) or "").strip()- if session_id and session_key:- raise TaskCliError(- "use either --session-id or --session-key, not both",- code="conflicting_session_target",- hint="Use --session-id for new commands.",- help_command=help_command,- )- if required and not session_id and not session_key:+ if required and not session_id:raise TaskCliError(- "one of --session-id or --session-key is required",+ "--session-id is required",code="missing_session_target",hint="Run from an Avibe Agent shell to continue this conversation by default, or pass --session-id for the target Session.",example="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'",help_command=help_command,)- return session_id or None, session_key+ return session_id or Noneclass _CommandTarget(NamedTuple):@@ -3196,52 +3080,36 @@ def _default_session_id_from_caller(caller_context) -> Optional[str]:return session_id-def _apply_caller_session_default(args, caller_context, *, purpose: str) -> Optional[dict[str, str]]:+def _apply_caller_session_default(args, caller_context) -> None:+ """Target the caller Session when the command names no Session of its own.++ No notice reports it: every payload already carries the resolved ``session_id``.+ """+if (getattr(args, "session_id", None) or "").strip():- return None- if (getattr(args, "session_key", None) or "").strip():- return None+ returnif bool(getattr(args, "create_session", False)) or bool(getattr(args, "create_session_per_run", False)):- return None+ returnif (getattr(args, "fork_session", None) or "").strip():- return None+ returndefault_session_id = _default_session_id_from_caller(caller_context)- if not default_session_id:- return None- setattr(args, "session_id", default_session_id)- return {- "code": "session_defaulted_to_caller",- "message": f"{purpose} defaulted to this Agent Session.",- "session_id": default_session_id,- }-+ if default_session_id:+ setattr(args, "session_id", default_session_id)-def _resolve_show_session_id(args, *, help_command: str) -> tuple[str, Optional[dict[str, str]]]:- caller_context = caller_context_from_env()- notice = _apply_caller_session_default(args, caller_context, purpose="Show Page session")- session_id = (getattr(args, "session_id", None) or "").strip()- if not session_id:- raise TaskCliError(- "Show Page session id is required outside an Avibe Agent environment.",- code="missing_session_target",- hint="Run this command from an Avibe Agent shell, or pass --session-id for the target Show Page.",- help_command=help_command,- )- return session_id, notice+def _resolve_caller_session_id(args, *, help_command: str) -> str:+ """The one Session a single-Session command acts on: ``--session-id``, else the caller."""-def _resolve_caller_session_id(args, *, purpose: str, help_command: str) -> tuple[str, Optional[dict[str, str]]]:- caller_context = caller_context_from_env()- notice = _apply_caller_session_default(args, caller_context, purpose=purpose)+ _apply_caller_session_default(args, caller_context_from_env())session_id = (getattr(args, "session_id", None) or "").strip()if not session_id:raise TaskCliError(- f"{purpose} id is required outside an Avibe Agent environment.",- code="missing_session_target",- hint="Run this command from an Avibe Agent shell, or pass the target Session ID positionally.",+ "This command defaults to the caller Session, and no Avibe Agent caller Session is set.",+ code="missing_caller_session",+ hint="Run it from an Avibe Agent shell, or pass --session-id <id>.",help_command=help_command,)- return session_id, notice+ return session_iddef _require_caller_session_id(caller_context, *, purpose: str, help_command: str) -> str:@@ -3414,7 +3282,6 @@ def _resolve_agent_run_scope_key(args, *, caller_context, source_session_id: Optdef _resolve_definition_scope_key(args, *, caller_context, help_command: str) -> Optional[str]:raw_scope_id = (getattr(args, "scope_id", None) or "").strip()same_scope = bool(getattr(args, "same_scope", False))- legacy_deliver_key = (getattr(args, "deliver_key", None) or "").strip()if raw_scope_id and same_scope:raise TaskCliError("use either --same-scope or --scope-id, not both",@@ -3422,13 +3289,6 @@ def _resolve_definition_scope_key(args, *, caller_context, help_command: str) ->hint="Use --same-scope to reuse the caller scope, or --scope-id to place the new Session explicitly.",help_command=help_command,)- if legacy_deliver_key and (raw_scope_id or same_scope):- raise TaskCliError(- "use either the legacy delivery target or the new scope placement flags, not both",- code="conflicting_scope_target",- hint="Use --scope-id or --same-scope for new Agent-facing commands.",- help_command=help_command,- )if raw_scope_id:return _validate_existing_scope_id(raw_scope_id, help_command=help_command).session_scopeif same_scope:@@ -3438,8 +3298,6 @@ def _resolve_definition_scope_key(args, *, caller_context, help_command: str) ->help_command=help_command,)return _require_scope_id_from_session_id(caller_session_id, help_command=help_command)- if legacy_deliver_key:- return _parse_validated_session_key(legacy_deliver_key, help_command=help_command).session_scopereturn None@@ -3506,6 +3364,15 @@ class SessionListScope:return {"session_id": self.session_id, "global": self.session_id is None}+def _add_session_target_arg(parser) -> None:+ """Name the one Session a single-Session command acts on; the caller Session by default."""++ parser.add_argument(+ "--session-id",+ help="Agent Session ID. Defaults to the caller Session in an Avibe Agent shell.",+ )++def _add_session_scope_args(parser, *, items: str) -> None:"""One grammar for every list of Session-owned records.@@ -4061,11 +3928,10 @@ def cmd_harness_status(args) -> int:try:scope = _resolve_session_list_scope(args, help_command="vibe harness status --help")- language = _configured_cli_language()request_store = _task_request_store()sqlite_store = request_store.sqlite_backendif sqlite_store is None:- raise RuntimeError(i18n_t("harness.cli.error.sqliteRequired", language))+ raise RuntimeError("Harness status requires the SQLite task store.")fetch_limit = MAX_PAGE_LIMIT + 1raw_runs = sqlite_store.list_active_runs(limit=fetch_limit, session_id=scope.session_id)raw_watches = sqlite_store.list_enabled_definitions(@@ -4093,20 +3959,16 @@ def cmd_harness_status(args) -> int:runtime_snapshot.get("ok"))if not runtime_snapshot["available"]:- runtime_snapshot["error"] = i18n_t(- "harness.cli.error.controllerStatus",- language,- status=status_code,- )+ runtime_snapshot["error"] = f"The controller returned status {status_code}."except internal_client.InternalServerTimeout:runtime_snapshot = {"available": False,- "error": i18n_t("harness.cli.error.controllerTimeout", language),+ "error": "The controller request timed out.",}except internal_client.InternalServerUnavailable:runtime_snapshot = {"available": False,- "error": i18n_t("harness.cli.error.controllerUnavailable", language),+ "error": "The controller is unreachable.",}# Ownership is a point-in-time controller fact. Keep only Runs that were@@ -4265,21 +4127,16 @@ def _wait_for_watch_startup(#: Attribute name -> the flag as the user typed it, for the refusal message._TASK_SESSION_FLAG_ARGS: tuple[tuple[str, str], ...] = (("session_id", "--session-id"),- ("session_key", "--session-key"),("create_session", "--create-session"),("create_session_per_run", "--create-session-per-run"),("same_scope", "--same-scope"),("scope_id", "--scope-id"),("agent", "--agent"),- ("post_to", "--post-to"),- ("deliver_key", "--deliver-key"),)_TASK_MESSAGE_FLAG_ARGS: tuple[tuple[str, str], ...] = (("message", "--message"),("message_file", "--message-file"),- ("prompt", "--prompt"),- ("prompt_file", "--prompt-file"),)@@ -4442,11 +4299,7 @@ def cmd_task_add(args):session_workdir = Noneelse:# The defaulted target is the definition's ``session_id``; no notice repeats it.- _apply_caller_session_default(- args,- caller_context,- purpose="Task target Session",- )+ _apply_caller_session_default(args, caller_context)session_policy = _validate_definition_session_policy(args,schedule_type=schedule_type,@@ -4457,7 +4310,7 @@ def cmd_task_add(args):# Optional only for an escalating command task, where the Agent turn is a# failure notice and the stored message is extra triage guidance.message = (- _resolve_prompt_input(+ _resolve_message_input(args,help_command="vibe task add --help",example_command="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *'",@@ -4465,11 +4318,12 @@ def cmd_task_add(args):if not has_command or _explicit_flag_names(args, _TASK_MESSAGE_FLAG_ARGS)else "")- session_id, session_key = _resolve_session_target_args(+ session_id = _resolve_session_target_args(args,required=session_policy == "existing",help_command="vibe task add --help",)+ session_key = ""# Before the reservation and before the definition row: a stored# schedule fires under the authority written with it, so the Session# it will speak in is admitted while the caller is still here to be@@ -4536,8 +4390,8 @@ def cmd_task_add(args):session_policy=session_policy,session_id=session_id,session_key=session_key,- post_to=getattr(args, "post_to", None),- deliver_key=getattr(args, "deliver_key", None),+ post_to=None,+ deliver_key=None,scope_key=scope_key,help_command="vibe task add --help",)@@ -4573,8 +4427,6 @@ def cmd_task_add(args):name=_normalize_task_name(getattr(args, "name", None)),session_key=session_key,session_id=session_id,- post_to=args.post_to,- deliver_key=args.deliver_key,prompt=message,schedule_type="cron",agent_name=agent_name,@@ -4606,8 +4458,6 @@ def cmd_task_add(args):name=_normalize_task_name(getattr(args, "name", None)),session_key=session_key,session_id=session_id,- post_to=args.post_to,- deliver_key=args.deliver_key,prompt=message,schedule_type="at",agent_name=agent_name,@@ -4687,12 +4537,11 @@ def cmd_task_set_enabled(task_id: str, enabled: bool):try:updated = store.set_enabled(task_id, enabled)except TaskResumeBlocked as exc:- lang = _configured_cli_language()_print_task_error(TaskCliError(- i18n_t("error.taskOwnerUnavailable.message", lang),+ i18n_t("error.taskOwnerUnavailable.message"),code=exc.code,- hint=i18n_t("error.taskOwnerUnavailable.hint", lang, id=task_id),+ hint=i18n_t("error.taskOwnerUnavailable.hint", id=task_id),help_command=f"vibe task remove {task_id}",details={"task_id": task_id,@@ -4702,12 +4551,11 @@ def cmd_task_set_enabled(task_id: str, enabled: bool):)return 1except TaskScheduleRetired as exc:- lang = _configured_cli_language()_print_task_error(TaskCliError(- i18n_t("error.taskScheduleRetired.message", lang),+ i18n_t("error.taskScheduleRetired.message"),code=exc.code,- hint=i18n_t("error.taskScheduleRetired.hint", lang, id=task_id),+ hint=i18n_t("error.taskScheduleRetired.hint", id=task_id),help_command=f"vibe task update {task_id} --help",details={"task_id": task_id},)@@ -4787,19 +4635,13 @@ def _validate_task_cron(cron: str, timezone: ZoneInfo, *, help_command: str) ->weekday = ambiguous_weekday_field(cron)if weekday is None:return- lang = _configured_cli_language()- hint = i18n_t("error.cronNumericWeekday.hint", lang)+ hint = "Write weekday names (mon, tue, wed, thu, fri, sat, sun); they mean the same day everywhere."avibe_reading, crontab_reading = weekday_readings(weekday)if avibe_reading is not None and crontab_reading is not None:- readings = i18n_t(- "error.cronNumericWeekday.readings",- lang,- avibe=avibe_reading,- crontab=crontab_reading,- )+ readings = f"Avibe (APScheduler) reads it as {avibe_reading}; crontab(5) reads it as {crontab_reading}."hint = f"{readings} {hint}"raise TaskCliError(- i18n_t("error.cronNumericWeekday.message", lang, field=weekday),+ f"Cron weekday field uses numbers: {weekday}",code="ambiguous_cron_weekday",hint=hint,example="0 9 * * mon-fri",@@ -5026,9 +4868,7 @@ def cmd_task_update(args):return _cmd_task_update_pure_command(args, store, task)if getattr(args, "reset_delivery", False) and (- getattr(args, "post_to", None) is not None- or getattr(args, "deliver_key", None) is not None- or getattr(args, "scope_id", None) is not None+ getattr(args, "scope_id", None) is not Noneor bool(getattr(args, "same_scope", False))):raise TaskCliError(@@ -5054,7 +4894,7 @@ def cmd_task_update(args):caller_context=caller_context,help_command="vibe task update --help",)- session_id_update, session_key_update = _resolve_session_target_args(+ session_id_update = _resolve_session_target_args(args,required=False,help_command="vibe task update --help",@@ -5062,9 +4902,6 @@ def cmd_task_update(args):if session_id_update is not None:session_id = session_id_updatesession_key = ""- elif session_key_update:- session_id = None- session_key = session_key_updateelse:session_id = task.session_idsession_key = task.session_key@@ -5072,17 +4909,8 @@ def cmd_task_update(args):post_to = Nonedeliver_key = Noneelse:- requested_post_to = getattr(args, "post_to", None)- requested_deliver_key = getattr(args, "deliver_key", None)- if requested_post_to is not None:- post_to = requested_post_to- deliver_key = None- elif requested_deliver_key is not None:- post_to = None- deliver_key = requested_deliver_key- else:- post_to = task.post_to- deliver_key = task.deliver_key+ post_to = task.post_to+ deliver_key = task.deliver_keymetadata = dict(task.metadata or {})if requested_scope_key:metadata["session_scope_id"] = requested_scope_key@@ -5128,10 +4956,10 @@ def cmd_task_update(args):message_changed = any(getattr(args, name, None) is not None- for name in ("message", "message_file", "prompt", "prompt_file")+ for name in ("message", "message_file"))message = (- _resolve_prompt_input(+ _resolve_message_input(args,help_command="vibe task update --help",example_command=f"vibe task update {args.task_id}",@@ -5482,104 +5310,6 @@ def cmd_task_run(task_id: str):return 0-def cmd_hook_send(args):- try:- session_id, session_key = _resolve_session_target_args(- args,- required=True,- help_command="vibe hook send --help",- )- session_target, delivery_target = _validate_delivery_args(- session_id=session_id,- session_key=session_key,- post_to=getattr(args, "post_to", None),- deliver_key=getattr(args, "deliver_key", None),- help_command="vibe hook send --help",- )- # Deprecated, but it still queues a real Agent turn, so it is admitted- # like one -- including through the legacy key, which names the same- # Session by its scope and thread.- command_target = _require_cli_turn_authority(- session_id,- session_key=session_key,- help_command="vibe hook send --help",- )- message = _resolve_prompt_input(- args,- help_command="vibe hook send --help",- example_command="vibe hook send --session-id sesk8m4q2p7x",- )- agent_resolution = _resolve_agent_target(- agent_name=getattr(args, "agent", None),- session_id=session_id,- session_key=session_key,- help_command="vibe hook send --help",- )- agent = agent_resolution.agent- # The other half of the gate above, now that the Agent this hook will run- # on is known: a key whose thread has not been opened yet reserves its- # Session at dispatch, in the Scope named here.- _require_cli_target_placement(command_target, agent=agent)- from storage.resource_access_service import metadata_with_resource_user_context-- # Deprecated, but it still enqueues an Agent turn, so it travels with the- # same initiating snapshot ``vibe agent run`` records. Empty for a local- # caller, exactly as before.- provenance_metadata = metadata_with_resource_user_context(None) or None- request = _task_request_store().enqueue_hook_send(- session_key=session_key,- session_id=session_id,- post_to=args.post_to,- deliver_key=args.deliver_key,- prompt=message,- agent_name=agent.name if agent else None,- agent_id=agent.id if agent else None,- run_type="agent_run",- source_kind="cli",- metadata=provenance_metadata,- expected_enabled_agent_id=(- agent.id- if agent is not None and agent_resolution.requires_enabled_write_guard- else None- ),- expected_reference_agent_id=(- agent.id- if agent is not None- and getattr(agent_resolution, "preserves_existing_reference", False)- else None- ),- )- warnings = _collect_target_warnings(session_target, delivery_target)- _print_cli_payload(- "agent_run",- accepted=True,- execution_id=request.id,- run_id=request.id,- request_type=request.request_type,- session_id=session_id,- session_key=session_key,- post_to=args.post_to,- deliver_key=args.deliver_key,- deprecation_warning=(- "vibe hook send is deprecated; use `vibe agent run --session-id <session-id> "- "--no-callback --message ...` for the same fire-and-forget behavior, or pass "- "`--callback-session-id <session-id>` when the async run should report back."- ),- run={- "id": request.id,- "status": "queued",- "run_type": request.request_type,- "agent_name": agent.name if agent else None,- "session_id": session_id,- },- warnings=warnings,- )- return 0- except Exception as exc:- _print_task_error(exc, help_command="vibe hook send --help")- return 1--def _read_optional_text(path: str | None, *, field_name: str) -> str | None:if not path:return None@@ -5606,9 +5336,17 @@ def _parse_metadata_json(value: str | None) -> dict:def _add_json_noop(parser) -> None:+ """``--json`` on a command that already prints the JSON envelope: accepted, changes nothing."""+parser.add_argument("--json", action="store_true", help=argparse.SUPPRESS)+def _add_json_flag(parser) -> None:+ """``--json`` on an operator command that prints text by default."""++ parser.add_argument("--json", action="store_true", help="Print the result as the JSON envelope.")++def cmd_agent_list(args):try:page_request = _page_request_from_args(args, help_command="vibe agent list --help")@@ -5797,7 +5535,7 @@ def cmd_agent_models(args):def _catalog_mismatches(- backend: str, model: Optional[str], reasoning_effort: Optional[str], *, language: str+ backend: str, model: Optional[str], reasoning_effort: Optional[str]) -> tuple[list[str], bool]:"""What the backend's model catalog says against ``model`` and ``reasoning_effort``, and whether it is authoritative.@@ -5809,26 +5547,29 @@ def _catalog_mismatches("""if backend == "opencode" or (not model and not reasoning_effort):return [], False- words = "harness.cli.agentRunModel"authoritative = not is_native_cli_backend(backend)try:options = api.agent_model_options(backend)except Exception:options = {}if not options.get("ok"):- return ([i18n_t(f"{words}.catalogUnavailable", language, backend=backend)] if authoritative else []), authoritative+ unavailable = f"the {backend} model catalog could not be loaded, so the model and reasoning effort cannot be checked"+ return ([unavailable] if authoritative else []), authoritativeby_value = {entry.get("value"): entry for entry in options.get("models") or []}model_unknown = bool(model) and model not in by_valuemismatches: list[str] = []if model_unknown:- key = "modelNotInCatalog" if authoritative else "modelMaybeNewer"- mismatches.append(i18n_t(f"{words}.{key}", language, model=model, backend=backend))+ mismatches.append(+ f"model '{model}' is not in the {backend} model catalog"+ if authoritative+ else f"model '{model}' is not in the {backend} model catalog; it may be a typo or newer than the catalog"+ )if reasoning_effort:if model and not model_unknown:allowed = set(by_value[model].get("reasoning_efforts") or [])# An authoritative model that lists no efforts takes none.constrained = bool(allowed) or authoritative- message = i18n_t(f"{words}.effortInvalidForModel", language, effort=reasoning_effort, model=model)+ message = f"reasoning_effort '{reasoning_effort}' is not valid for model '{model}'"else:# model unset or unknown: accept any effort valid for some model of this backend# (Codex efforts are backend-wide; Claude's widest set still lives in some model)@@ -5836,7 +5577,7 @@ def _catalog_mismatches(for entry in by_value.values():allowed.update(entry.get("reasoning_efforts") or [])constrained = bool(allowed)- message = i18n_t(f"{words}.effortInvalidForBackend", language, effort=reasoning_effort, backend=backend)+ message = f"reasoning_effort '{reasoning_effort}' is not valid for backend '{backend}'"if constrained and reasoning_effort not in allowed:mismatches.append(message)return mismatches, authoritative@@ -5846,13 +5587,12 @@ def _agent_value_warning_fields(agent) -> dict:"""Best-effort, non-fatal warnings when an Agent's model/effort is unknown (``_catalog_mismatches``)."""if agent.backend not in ("claude", "codex"):return {}- language = _configured_cli_language()- warnings, _ = _catalog_mismatches(agent.backend, agent.model, agent.reasoning_effort, language=language)+ warnings, _ = _catalog_mismatches(agent.backend, agent.model, agent.reasoning_effort)if not warnings:return {}return {"warnings": warnings,- "hint": i18n_t("harness.cli.agentRunModel.catalogHint", language, agent=agent.name),+ "hint": f"Run `vibe agent models {agent.name}` to list valid models and reasoning efforts.",}@@ -5865,11 +5605,10 @@ def _session_model_override_fields(otherwise keep. Where the catalog is authoritative (Vibey's Model Hub menu), a pair it does not offer is refusedand its reservation released; elsewhere a mismatch is a warning on the run, as ``vibe agent create/update`` gives."""- language = _configured_cli_language()- mismatches, authoritative = _catalog_mismatches(backend, model, reasoning_effort, language=language)+ mismatches, authoritative = _catalog_mismatches(backend, model, reasoning_effort)if not mismatches:return {}- hint = i18n_t("harness.cli.agentRunModel.catalogHint", language, agent=agent_label)+ hint = f"Run `vibe agent models {agent_label}` to list valid models and reasoning efforts."if authoritative:raise TaskCliError(mismatches[0],@@ -5899,16 +5638,12 @@ def cmd_agent_create(args):_print_cli_payload("agent", agent=_agent_payload(agent), **_agent_value_warning_fields(agent))return 0except AgentNameValidationError as exc:- try:- lang = V2Config.load().language- except Exception:- lang = "en"key = f"error.agentNameValidation.{exc.code}"_print_task_error(TaskCliError(- i18n_t(f"{key}.message", lang, agent=exc.agent_name),+ i18n_t(f"{key}.message", agent=exc.agent_name),code=exc.code,- hint=i18n_t(f"{key}.hint", lang, agent=exc.agent_name),+ hint=i18n_t(f"{key}.hint", agent=exc.agent_name),details={"agent": exc.agent_name},))@@ -5976,29 +5711,21 @@ def cmd_agent_set_enabled(args, *, enabled: bool):def _agent_lifecycle_cli_error(exc: AgentArchivedEditError | AgentAlwaysEnabledError) -> TaskCliError:- try:- lang = V2Config.load().language- except Exception:- lang = "en"key = f"error.agentLifecycle.{exc.code}"return TaskCliError(- i18n_t(f"{key}.message", lang, agent=exc.agent_name),+ i18n_t(f"{key}.message", agent=exc.agent_name),code=exc.code,- hint=i18n_t(f"{key}.hint", lang, agent=exc.agent_name),+ hint=i18n_t(f"{key}.hint", agent=exc.agent_name),details={"agent": exc.agent_name},)def _agent_reference_rewrite_cli_error(exc: AgentReferenceRewriteError) -> TaskCliError:- try:- lang = V2Config.load().language- except Exception:- lang = "en"key = f"error.agentLifecycle.{exc.code}"return TaskCliError(- i18n_t(f"{key}.message", lang),+ i18n_t(f"{key}.message"),code=exc.code,- hint=i18n_t(f"{key}.hint", lang),+ hint=i18n_t(f"{key}.hint"),)@@ -6008,20 +5735,14 @@ def cmd_agent_remove(args):try:archived = store.archive(args.name)except AgentArchiveError as exc:- try:- lang = V2Config.load().language- except Exception:- lang = "en"raise TaskCliError(i18n_t(f"error.agentArchive.{exc.code}.message",- lang,agent=exc.agent_name,),code=exc.code,hint=i18n_t(f"error.agentArchive.{exc.code}.hint",- lang,agent=exc.agent_name,),details={"agent": args.name},@@ -6099,21 +5820,10 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:session_id = (getattr(args, "session_id", None) or "").strip()fork_session = (getattr(args, "fork_session", None) or "").strip()fork_self = bool(getattr(args, "fork_self", False))- create_session = bool(getattr(args, "create_session", False))- create_per_run = bool(getattr(args, "create_session_per_run", False))same_scope = bool(getattr(args, "same_scope", False))scope_id = (getattr(args, "scope_id", None) or "").strip()- deliver_key = (getattr(args, "deliver_key", None) or "").strip()- agent_name = (getattr(args, "agent", None) or "").strip()visibility = (getattr(args, "visibility", None) or "").strip()close_after = bool(getattr(args, "close_after", False))- if bool(getattr(args, "async_run", False)) and bool(getattr(args, "sync_run", False)):- raise TaskCliError(- "use either --async or --sync, not both",- code="conflicting_wait_policy",- hint="Agent runs are async by default. Pass --sync only when the CLI should wait.",- help_command=help_command,- )if _agent_run_is_async(args) and getattr(args, "wait_timeout", None) is not None:raise TaskCliError("use --sync with --wait-timeout",@@ -6135,13 +5845,6 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:hint="Use --same-scope to reuse the caller/source scope, or --scope-id to place the new Session explicitly.",help_command=help_command,)- if deliver_key and (same_scope or scope_id):- raise TaskCliError(- "use either the legacy delivery target or the new scope placement flags, not both",- code="conflicting_scope_placement",- hint="Use --scope-id or --same-scope for new Agent-facing commands.",- help_command=help_command,- )if fork_self and fork_session:raise TaskCliError("use either --fork-self or --fork-session, not both",@@ -6149,29 +5852,21 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:hint="Use --fork-self from inside an Avibe Agent shell, or pass an explicit --fork-session.",help_command=help_command,)- if fork_self and session_id:- raise TaskCliError(- "use --fork-self without --session-id",- code="conflicting_session_policy",- hint="--fork-self resolves the source Session from AVIBE_SESSION_ID.",- help_command=help_command,- )- if (fork_session or fork_self) and (session_id or create_session or create_per_run):+ if (fork_session or fork_self) and session_id:raise TaskCliError(- "use fork without --session-id or session creation flags",+ "use fork without --session-id",code="conflicting_session_policy",- hint="Fork creates a new Session from the source Session.",+ hint="Fork creates a new Session from the source Session; --fork-self resolves it from AVIBE_SESSION_ID.",help_command=help_command,)if session_id and ((getattr(args, "model", None) or "").strip()or (getattr(args, "reasoning_effort", None) or "").strip()):- language = _configured_cli_language()raise TaskCliError(- i18n_t("harness.cli.agentRunModel.existingSession", language),+ "--model and --reasoning-effort only apply when the run creates a new Session",code="model_override_with_existing_session",- hint=i18n_t("harness.cli.agentRunModel.existingSessionHint", language),+ hint="An existing Session keeps its model; change it in the Web UI's Session model picker. To run on another model now, start a new Session (--agent <name> --model ...) or fork this one (--fork-session <id> --model ...).",help_command=help_command,)if session_id and (same_scope or scope_id):@@ -6185,39 +5880,18 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:raise TaskCliError("visibility options only apply when creating or forking a Session",code="visibility_with_existing_session",- hint="Use `vibe session update --visible|--hidden` (or `--visibility ...`) to change an existing Session.",+ hint="Use `vibe session update --session-id <id> --visible` or `--hidden` to change an existing Session.",help_command=help_command,)if close_after and session_id:raise TaskCliError("--close-after requires a new or forked Agent Session",code="close_after_requires_owned_session",- hint="Use --close-after with --agent, --create-session, or --fork-session. Existing Sessions keep their runtime lifecycle.",- help_command=help_command,- )- if session_id and (create_session or create_per_run):- raise TaskCliError(- "use either --session-id or --create-session, not both",- code="conflicting_session_policy",- help_command=help_command,- )- if create_session and create_per_run:- raise TaskCliError(- "use either --create-session or --create-session-per-run, not both",- code="conflicting_session_policy",- help_command=help_command,- )- if create_per_run:- raise TaskCliError(- "--create-session-per-run is only valid on stored recurring definitions",- code="invalid_session_policy",- hint="Use --create-session for a one-shot agent run.",+ hint="Use --close-after with --agent or a fork. Existing Sessions keep their runtime lifecycle.",help_command=help_command,)if fork_session or fork_self:return "fork"- if create_session:- return "create"if session_id:return "existing"return "none"@@ -6231,13 +5905,11 @@ def _validate_definition_session_policy(allow_caller_session_default: bool = False,) -> str:session_id = (getattr(args, "session_id", None) or "").strip()- session_key = (getattr(args, "session_key", None) or "").strip()create_session = bool(getattr(args, "create_session", False))create_per_run = bool(getattr(args, "create_session_per_run", False))- deliver_key = (getattr(args, "deliver_key", None) or "").strip()scope_id = (getattr(args, "scope_id", None) or "").strip()same_scope = bool(getattr(args, "same_scope", False))- specified = sum(1 for value in (bool(session_id or session_key), create_session, create_per_run) if value)+ specified = sum(1 for value in (bool(session_id), create_session, create_per_run) if value)if specified > 1:raise TaskCliError("use exactly one session policy",@@ -6259,7 +5931,7 @@ def _validate_definition_session_policy(hint="Use --create-session or --create-session-per-run with --scope-id/--same-scope, or omit the scope placement flag.",help_command=help_command,)- if create_session and not (deliver_key or scope_id or same_scope):+ if create_session and not (scope_id or same_scope):raise TaskCliError("--scope-id or --same-scope is required when a stored definition creates one reusable Session",code="missing_delivery_target",@@ -6270,7 +5942,7 @@ def _validate_definition_session_policy(return "create_once"if create_per_run:return "create_per_run"- if session_id or session_key:+ if session_id:return "existing"if allow_caller_session_default:return "existing"@@ -6296,7 +5968,6 @@ def _definition_session_policy_for_update(create_session = bool(getattr(args, "create_session", False))create_per_run = bool(getattr(args, "create_session_per_run", False))session_id = (getattr(args, "session_id", None) or "").strip()- session_key = (getattr(args, "session_key", None) or "").strip()scope_id = (getattr(args, "scope_id", None) or "").strip()same_scope = bool(getattr(args, "same_scope", False))if create_session and create_per_run:@@ -6305,7 +5976,7 @@ def _definition_session_policy_for_update(code="conflicting_session_policy",help_command=help_command,)- if (session_id or session_key) and (create_session or create_per_run):+ if session_id and (create_session or create_per_run):raise TaskCliError("use either --session-id or session creation, not both",code="conflicting_session_policy",@@ -6329,7 +6000,7 @@ def _definition_session_policy_for_update(return "create_once"if create_per_run:return "create_per_run"- if session_id or session_key:+ if session_id:return "existing"if current_policy == "create_per_run" and current_schedule_type != next_schedule_type and next_schedule_type == "at":raise TaskCliError(@@ -6768,7 +6439,6 @@ def _reserve_cli_session(scope_key: Optional[str],workdir: Optional[str] = None,metadata: Optional[dict] = None,- session_anchor_target=None,visibility: str = "background",authorization_context=None,model: Optional[str] = None,@@ -6782,8 +6452,7 @@ def _reserve_cli_session(if scope_key:target = _parse_validated_scope_id(scope_key, help_command="vibe agent run --help")- anchor_target = session_anchor_target or target- session_anchor = _session_anchor_with_suffix(anchor_target, suffix="run")+ session_anchor = _session_anchor_with_suffix(target, suffix="run")session_id = sessions_service.reserve_agent_session(scope_key=target.session_scope,agent_backend=agent.backend,@@ -6866,15 +6535,11 @@ def _reserve_forked_cli_session()except SessionForkError as exc:if exc.code == SESSION_AGENT_UNAVAILABLE_CODE:- try:- lang = V2Config.load().language- except Exception:- lang = "en"key = SESSION_AGENT_UNAVAILABLE_I18N_KEYraise TaskCliError(- i18n_t(f"{key}.message", lang),+ i18n_t(f"{key}.message"),code=exc.code,- hint=i18n_t(f"{key}.hint", lang),+ hint=i18n_t(f"{key}.hint"),help_command="vibe agent run --help",details={"source_session_id": source_session_id, **exc.details},) from exc@@ -6983,15 +6648,8 @@ def cmd_agent_run(args):if bool(getattr(args, "queue", False))else AGENT_RUN_DELIVERY_STEER)- if bool(getattr(args, "send_now", False)) and session_policy != "existing":- raise TaskCliError(- "--send-now requires an existing Agent Session",- code="send_now_requires_existing_session",- hint="Pass --session-id <session-id>, or omit --send-now for a new or forked Session.",- help_command="vibe agent run --help",- )agent_name = (args.agent or "").strip()- if session_policy in {"create", "none"} and not agent_name:+ if session_policy == "none" and not agent_name:raise TaskCliError("--agent is required when running without an existing --session-id",code="missing_agent",@@ -7006,20 +6664,6 @@ def cmd_agent_run(args):help_command="vibe agent run --help",)setattr(args, "fork_session", source_session_id)- if session_policy == "none" and (args.deliver_key or args.post_to):- raise TaskCliError(- "delivery options require an explicit Session target",- code="delivery_target_without_session_policy",- hint="Use --same-scope or --scope-id for new Session placement.",- help_command="vibe agent run --help",- )- if session_policy == "fork" and args.post_to:- raise TaskCliError(- "delivery options require an existing Session target",- code="delivery_target_without_session_policy",- hint="Fork creates a new Session. Use scope placement flags for where it lives; callback controls where results return.",- help_command="vibe agent run --help",- )session_id = (args.session_id or "").strip() or Nonesession_key = ""scope_key = (@@ -7038,22 +6682,11 @@ def cmd_agent_run(args):has_resolved_caller_placement = Trueexcept ValueError:pass- legacy_reservation_target = None- if not scope_key and (args.deliver_key or "").strip():- # Hidden legacy compatibility: external docs and prompts should use- # --scope-id/--same-scope, while old callers still map into the same- # internal placement field.- legacy_reservation_target = _parse_validated_session_key(args.deliver_key, help_command="vibe agent run --help")- scope_key = legacy_reservation_target.session_scoperun_cwd = _resolve_run_cwd(args,session_policy=session_policy,- scoped_session=bool(- _has_modern_scope_target(args) or (args.deliver_key or "").strip()- ),- invocation_cwd_default=has_resolved_caller_placement- and not _has_modern_scope_target(args)- and not (args.deliver_key or "").strip(),+ scoped_session=_has_modern_scope_target(args),+ invocation_cwd_default=has_resolved_caller_placement and not _has_modern_scope_target(args),help_command="vibe agent run --help",)agent = _agent_store().require_enabled(agent_name) if agent_name else None@@ -7072,42 +6705,18 @@ def cmd_agent_run(args):# may only restate it -- so admitting the caller to the Session# answers both halves of the turn it is about to queue._require_cli_turn_authority(session_id, help_command="vibe agent run --help")- if session_policy == "existing" and (args.post_to or args.deliver_key):- _validate_delivery_args(- session_id=session_id,- session_key=session_key,- post_to=args.post_to,- deliver_key=args.deliver_key,- help_command="vibe agent run --help",- )callback_session_id, callback_notice = _resolve_callback_session_id(args, caller_context, target_session_id=session_id)if callback_session_id:_validate_callback_session_id(callback_session_id, help_command="vibe agent run --help")close_after = bool(getattr(args, "close_after", False))- legacy_deliver_key = args.deliver_key- if (getattr(args, "same_scope", False) or (getattr(args, "scope_id", None) or "").strip()) and legacy_deliver_key != scope_key:- legacy_deliver_key = None# The caller's own authority, resolved once. A remote caller reserves# under it; a local caller stays ``None`` and keeps Owner semantics.caller_authorization = caller_resource_user_context(caller_context)- # A new Session (blank, --create-session, or a fork) may run on its own model, kept on the Session, which+ # A new Session (blank or a fork) may run on its own model, kept on the Session, which# every later turn reads; it is checked against the Agent's catalog once the Session is reserved (below).model_override = (getattr(args, "model", None) or "").strip() or Noneeffort_override = (getattr(args, "reasoning_effort", None) or "").strip() or None- if session_policy == "create":- session_id = _reserve_cli_session(- agent=agent,- scope_key=scope_key,- workdir=run_cwd,- metadata=session_metadata,- session_anchor_target=legacy_reservation_target,- visibility=visibility,- authorization_context=caller_authorization,- model=model_override,- reasoning_effort=effort_override,- )- reserved_session_id = session_id- elif session_policy == "none":+ if session_policy == "none":session_id = _reserve_cli_session(agent=agent,scope_key=scope_key,@@ -7160,14 +6769,6 @@ def cmd_agent_run(args):),help_command="vibe agent run --help",)- if (session_policy in {"create", "none"} or fork_result) and args.post_to:- _validate_delivery_args(- session_id=session_id,- session_key=session_key,- post_to=args.post_to,- deliver_key=None,- help_command="vibe agent run --help",- )source_kind, source_actor, parent_run_id, provenance_metadata = _agent_run_source_from_caller(caller_context)if fork_result:provenance_metadata = {@@ -7200,8 +6801,6 @@ def cmd_agent_run(args):session_policy=session_policy,session_key=session_key,session_id=session_id,- post_to=args.post_to,- deliver_key=legacy_deliver_key,message=message,source_kind=source_kind,source_actor=source_actor,@@ -7517,10 +7116,7 @@ def _cancel_live_agent_run(store: TaskExecutionStore, run: dict) -> dict:),"controller_status_code": normalized_status_code,"controller_response": body,- "message": i18n_t(- "harness.run.cli.canceledBeforeLiveTurn",- _configured_cli_language(),- ),+ "message": "Run was canceled before its input reached the live Session turn.",}if (normalized_status_code is not None@@ -7603,7 +7199,6 @@ def cmd_data_retention(args):try:ensure_sqlite_state()engine = create_sqlite_engine()- language = _configured_cli_language()days_override = getattr(args, "days", None)# The configured window is the default; --days overrides for this call.# A recovered/unreadable config must not silently run with substituted@@ -7636,12 +7231,7 @@ def cmd_data_retention(args):# Never silently clamp an explicit window: --days 0 would# delete everything older than one day after normalization.print(- i18n_t(- "data.retention.invalidDays",- language,- minimum=agent_events_retention.MIN_RETENTION_DAYS,- maximum=agent_events_retention.MAX_RETENTION_DAYS,- ),+ f"--days must be between {agent_events_retention.MIN_RETENTION_DAYS} and {agent_events_retention.MAX_RETENTION_DAYS}; refusing to run instead of silently clamping the window.",file=sys.stderr,)return 1@@ -7649,7 +7239,7 @@ def cmd_data_retention(args):should_run = bool(getattr(args, "run", False)) or bool(getattr(args, "compact", False))if config_recovered and should_run:print(- i18n_t("data.retention.configRecovered", language),+ "The Avibe config could not be read (recovery defaults active); the retention policy is unknown. Re-run with an explicit --days window to delete anything.",file=sys.stderr,)return 1@@ -7673,82 +7263,70 @@ def cmd_data_retention(args):else:payload = {"mode": "plan", "enabled": enabled, **agent_events_retention.retention_status(engine, retention_days=retention_days)}if getattr(args, "json", False):- print(json.dumps(payload, indent=2))+ _print_cli_payload("data_retention", **payload)else:- _print_data_retention_human(payload, language)+ _print_data_retention_human(payload)return exit_codeexcept Exception as exc: # noqa: BLE001- print(i18n_t("data.retention.error", _configured_cli_language(), error=str(exc)), file=sys.stderr)+ print(f"Trace retention command failed: {str(exc)}", file=sys.stderr)return 1-_COMPACTION_REASON_KEYS = {- "checkpoint_busy": "data.retention.compactionReasonCheckpointBusy",- "post_checkpoint_busy": "data.retention.compactionReasonCheckpointBusy",- "insufficient_free_space": "data.retention.compactionReasonFreeSpace",- "free_space_unknown": "data.retention.compactionReasonFreeSpace",+_COMPACTION_REASONS = {+ "checkpoint_busy": "the database is busy with concurrent readers/writers",+ "post_checkpoint_busy": "the database is busy with concurrent readers/writers",+ "insufficient_free_space": "there is not enough free disk space to rewrite the database safely",+ "free_space_unknown": "there is not enough free disk space to rewrite the database safely",}-def _print_data_retention_human(payload: dict, language: str) -> None:+def _print_data_retention_human(payload: dict) -> None:from storage import agent_events_retention as _retentionmode = str(payload.get("mode") or "run")if mode == "plan":plan = payload.get("plan") or {}print(- i18n_t(- "data.retention.plan",- language,- count=int(plan.get("eligible_count") or 0),- size=_format_byte_size(int(plan.get("eligible_logical_bytes") or 0)),- days=int(plan.get("retention_days") or _retention.DEFAULT_RETENTION_DAYS),- )+ "{count} trace row(s) older than {days} day(s) are eligible ({size} of payload text).".format(count=int(plan.get("eligible_count") or 0), size=_format_byte_size(int(plan.get("eligible_logical_bytes") or 0)), days=int(plan.get("retention_days") or _retention.DEFAULT_RETENTION_DAYS)))last = payload.get("last_run") or {}if last:- print(i18n_t("data.retention.lastRun", language, at=str(last.get("finished_at")), rows=int(last.get("deleted_rows") or 0)))+ print("Last retention run: {at}, deleted {rows} row(s).".format(at=str(last.get("finished_at")), rows=int(last.get("deleted_rows") or 0)))else:- print(i18n_t("data.retention.neverRun", language))+ print("No retention run has completed yet.")if payload.get("enabled") is False:- print(i18n_t("data.retention.disabled", language))+ print("Trace retention is disabled in runtime config; the daily task will not delete anything.")compaction = payload.get("compaction") or {}print(- i18n_t(- "data.retention.compaction",- language,- size=_format_byte_size(int(compaction.get("reclaimable_bytes") or 0)),- )+ "Reclaimable inside the database right now: {size}.".format(size=_format_byte_size(int(compaction.get("reclaimable_bytes") or 0))))returnstatus = str(payload.get("status") or "unknown")if status == "ok":- print(i18n_t("data.retention.ran", language, rows=int(payload.get("deleted_rows") or 0)))+ print("Retention pass deleted {rows} trace row(s).".format(rows=int(payload.get("deleted_rows") or 0)))compaction = payload.get("compaction") or {}compaction_status = str(compaction.get("status") or "not_attempted")if compaction_status == "vacuumed":- print(i18n_t("data.retention.compacted", language, size=_format_byte_size(int(compaction.get("reclaimed_bytes") or 0))))+ print("Database compacted; {size} returned to disk.".format(size=_format_byte_size(int(compaction.get("reclaimed_bytes") or 0))))elif compaction_status == "deferred":print(- i18n_t(- "data.retention.compactionDeferred",- language,- reason=i18n_t(_COMPACTION_REASON_KEYS.get(str(compaction.get("reason")), "data.retention.compactionReasonOther"), language),+ "Compaction deferred ({reason}); rows are deleted, disk space returns on a later safe pass.".format(+ reason=_COMPACTION_REASONS.get(str(compaction.get("reason")), "compaction was not safe to run")))elif compaction_status == "skipped":- print(i18n_t("data.retention.compactionSkipped", language))+ print("Compaction skipped: too little would be reclaimed.")elif status == "not_due":- print(i18n_t("data.retention.notDue", language))+ print("Retention already ran within the last day; nothing to do.")elif status == "busy":- print(i18n_t("data.retention.busy", language))+ print("Another retention run is active; try again later.")elif status == "lease_lost":- print(i18n_t("data.retention.leaseLost", language))+ print("This pass lost its lease to another retention run; deletion stopped partway and no completion was recorded. Retry once the other run finishes.")elif status == "cancelled":- print(i18n_t("data.retention.cancelled", language))+ print("Retention stopped at a batch boundary; no completion was recorded.")elif status == "ok_with_contested_compaction":- print(i18n_t("data.retention.ran", language, rows=int(payload.get("deleted_rows") or 0)))- print(i18n_t("data.retention.compactionDeferred", language, reason=i18n_t("data.retention.compactionReasonOther", language)))+ print("Retention pass deleted {rows} trace row(s).".format(rows=int(payload.get("deleted_rows") or 0)))+ print("Compaction deferred ({reason}); rows are deleted, disk space returns on a later safe pass.".format(reason="compaction was not safe to run"))else:print(f"retention status: {status}")@@ -7761,14 +7339,13 @@ def cmd_data_skill_usage(args):from core.skill_observability import collection_enabledfrom storage.db import get_cached_sqlite_engine- language = _configured_cli_language()caller = caller_resource_user_context(caller_context_from_env())if not resolve_resource_access_context(caller).can_manage_instance:- raise TaskCliError(i18n_t("data.skillUsage.ownerRequired", language), code="forbidden")+ raise TaskCliError("Instance Member or Owner access is required.", code="forbidden")if args.clear and not args.yes:- raise TaskCliError(i18n_t("data.skillUsage.confirmationRequired", language), code="confirmation_required")+ raise TaskCliError("Clearing Skill statistics requires --yes.", code="confirmation_required")if args.yes and not args.clear:- raise TaskCliError(i18n_t("data.skillUsage.clearRequired", language), code="invalid_arguments")+ raise TaskCliError("--yes requires --clear.", code="invalid_arguments")enabled = collection_enabled()from storage.importer import ensure_sqlite_state@@ -7859,24 +7436,6 @@ def _validate_session_type(platform: str) -> None:)-def _session_list_hint() -> str:- return (- "Need richer filtering (by agent, time range, message content, or joins)? "- "Use: vibe data query. Find sessions by what was discussed: vibe data query "- "--sql \"select s.id, s.title from agent_sessions s join messages m "- "on m.session_id = s.id where m.content_text like '%KEYWORD%' "- "order by s.last_active_at desc\""- )---def _session_get_hint(session_id: str) -> str:- return (- f"This session's runs: vibe runs list --session-id {session_id}. "- "Its messages or any cross-session query: vibe data query "- "(join messages on session_id)."- )--def _open_session_engine():# Bootstrap/migrate the SQLite state first so a fresh Avibe home returns a clean# empty list / not-found instead of a raw "no such table" error (Codex P2).@@ -7906,7 +7465,6 @@ def cmd_session_list(args):"agent_sessions",sessions=[_session_row(row, brief=True) for row in result.items],**_paginated_fields(result, command=command),- message=_session_list_hint(),)return 0except Exception as exc:@@ -7918,9 +7476,8 @@ def cmd_session_get(args):from core.services import sessions as sessions_servicetry:- session_id, session_default_notice = _resolve_caller_session_id(+ session_id = _resolve_caller_session_id(args,- purpose="Session",help_command="vibe session get --help",)engine = _open_session_engine()@@ -7945,8 +7502,6 @@ def cmd_session_get(args):_print_cli_payload("agent_session",session=_session_row(payload, brief=False),- message=_session_get_hint(session_id),- **({"session_default_notice": session_default_notice} if session_default_notice else {}),)return 0@@ -7957,8 +7512,12 @@ def cmd_session_send_now(args):from core.services import sessions as sessions_servicefrom vibe import internal_client- session_id = str(getattr(args, "session_id", "") or "").strip()+ session_id = Nonetry:+ session_id = _resolve_caller_session_id(+ args,+ help_command="vibe session send-now --help",+ )engine = _open_session_engine()with engine.connect() as conn:# Promotion is chat work, so it is authorized before the controller@@ -8058,8 +7617,12 @@ def cmd_session_queue_list(args):from core.services import sessions as sessions_servicefrom storage import message_deliveries- session_id = str(getattr(args, "session_id", "") or "").strip()+ session_id = Nonetry:+ session_id = _resolve_caller_session_id(+ args,+ help_command="vibe session queue list --help",+ )page_request = _page_request_from_args(args,help_command="vibe session queue list --help",@@ -8108,7 +7671,7 @@ def cmd_session_queue_list(args):],**_paginated_fields(result,- command=["vibe", "session", "queue", "list", session_id],+ command=["vibe", "session", "queue", "list", "--session-id", session_id],),)return 0@@ -8119,9 +7682,13 @@ def cmd_session_queue_remove(args):from storage import message_deliveriesfrom storage.background import run_update_event_transaction- session_id = str(getattr(args, "session_id", "") or "").strip()+ session_id = Nonemessage_id = str(getattr(args, "message_id", "") or "").strip()try:+ session_id = _resolve_caller_session_id(+ args,+ help_command="vibe session queue remove --help",+ )engine = _open_session_engine()with run_update_event_transaction(engine) as conn:from storage.agent_session_rows import reserve_write_lock@@ -8196,12 +7763,11 @@ def cmd_session_update(args):raise TaskCliError("no update field supplied",code="missing_session_update",- hint="Pass --title, --visible/--hidden, --visibility, or --scope-id.",+ hint="Pass --title, --visible, --hidden, or --scope-id.",help_command="vibe session update --help",)- session_id, session_default_notice = _resolve_caller_session_id(+ session_id = _resolve_caller_session_id(args,- purpose="Session",help_command="vibe session update --help",)engine = _open_session_engine()@@ -8234,7 +7800,6 @@ def cmd_session_update(args):"agent_session",updated=True,session=_session_row(payload, brief=False),- **({"session_default_notice": session_default_notice} if session_default_notice else {}),)return 0@@ -11314,11 +10879,7 @@ def cmd_watch_add(args):caller_context = caller_context_from_env()caller_user_context = caller_resource_user_context(caller_context)# The defaulted target is the definition's ``session_id``; no notice repeats it.- _apply_caller_session_default(- args,- caller_context,- purpose="Watch target Session",- )+ _apply_caller_session_default(args, caller_context)session_policy = _validate_definition_session_policy(args,schedule_type="watch",@@ -11327,11 +10888,12 @@ def cmd_watch_add(args):)scope_key = _resolve_definition_scope_key(args, caller_context=caller_context, help_command="vibe watch add --help")command, shell_command = _resolve_watch_command(args, help_command="vibe watch add --help")- session_id, session_key = _resolve_session_target_args(+ session_id = _resolve_session_target_args(args,required=session_policy == "existing",help_command="vibe watch add --help",)+ session_key = ""# Same gate as ``vibe task add``: the waiter's hook is a turn in this# Session, replayed later under the authority stored with the Watch.command_target = _require_cli_turn_authority(@@ -11385,8 +10947,8 @@ def cmd_watch_add(args):session_policy=session_policy,session_id=session_id,session_key=session_key,- post_to=getattr(args, "post_to", None),- deliver_key=getattr(args, "deliver_key", None),+ post_to=None,+ deliver_key=None,scope_key=scope_key,help_command="vibe watch add --help",)@@ -11398,12 +10960,10 @@ def cmd_watch_add(args):lifetime_timeout_seconds=float(args.lifetime_timeout),help_command="vibe watch add --help",)- prefix = _normalize_task_name(getattr(args, "prefix", None))message = _resolve_optional_message_input(args,help_command="vibe watch add --help",example_command="vibe watch add --session-id sesk8m4q2p7x --message 'Continue when the waiter finishes.'",- legacy_prefix=prefix,)retry_exit_codes = sorted(set(args.retry_exit_code or [DEFAULT_RETRY_EXIT_CODE]))@@ -11414,7 +10974,7 @@ def cmd_watch_add(args):session_id=session_id,command=command,shell_command=shell_command,- prefix=prefix,+ prefix=None,message=message,cwd=cwd,mode=mode,@@ -11422,8 +10982,8 @@ def cmd_watch_add(args):lifetime_timeout_seconds=float(args.lifetime_timeout),retry_exit_codes=retry_exit_codes,retry_delay_seconds=float(args.retry_delay),- post_to=args.post_to,- deliver_key=args.deliver_key,+ post_to=None,+ deliver_key=None,agent_name=agent_name,session_policy=session_policy,metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=session_workdir),@@ -11497,12 +11057,11 @@ def cmd_watch_set_enabled(watch_id: str, enabled: bool):try:updated = store.set_enabled(watch_id, enabled)except JobWatchResumeRefused as exc:- lang = _configured_cli_language()_print_task_error(TaskCliError(- i18n_t("error.jobWatchResumeRefused.message", lang),+ i18n_t("error.jobWatchResumeRefused.message"),code=exc.code,- hint=i18n_t("error.jobWatchResumeRefused.hint", lang, id=watch_id),+ hint=i18n_t("error.jobWatchResumeRefused.hint", id=watch_id),help_command=f"vibe watch remove {watch_id}",details={"watch_id": watch_id},)@@ -11532,9 +11091,7 @@ def cmd_watch_update(args):raise _missing_definition_error("watch", args.watch_id, action="update")if getattr(args, "reset_delivery", False) and (- getattr(args, "post_to", None) is not None- or getattr(args, "deliver_key", None) is not None- or getattr(args, "scope_id", None) is not None+ getattr(args, "scope_id", None) is not Noneor bool(getattr(args, "same_scope", False))):raise TaskCliError(@@ -11574,7 +11131,7 @@ def cmd_watch_update(args):else:name = watch.name- session_id_update, session_key_update = _resolve_session_target_args(+ session_id_update = _resolve_session_target_args(args,required=False,help_command="vibe watch update --help",@@ -11582,9 +11139,6 @@ def cmd_watch_update(args):if session_id_update is not None:session_id = session_id_updatesession_key = ""- elif session_key_update:- session_id = None- session_key = session_key_updateelse:session_id = watch.session_idsession_key = watch.session_key@@ -11592,17 +11146,8 @@ def cmd_watch_update(args):post_to = Nonedeliver_key = Noneelse:- requested_post_to = getattr(args, "post_to", None)- requested_deliver_key = getattr(args, "deliver_key", None)- if requested_post_to is not None:- post_to = requested_post_to- deliver_key = None- elif requested_deliver_key is not None:- post_to = None- deliver_key = requested_deliver_key- else:- post_to = watch.post_to- deliver_key = watch.deliver_key+ post_to = watch.post_to+ deliver_key = watch.deliver_keymetadata = dict(watch.metadata or {})if requested_scope_key:metadata["session_scope_id"] = requested_scope_key@@ -11616,28 +11161,17 @@ def cmd_watch_update(args):waiter_command = []if getattr(args, "shell", None) is not None or waiter_command:command, shell_command = _resolve_watch_command(args, help_command="vibe watch update --help")- prefix = (- None- if getattr(args, "clear_prefix", False)- else (- _normalize_task_name(getattr(args, "prefix", None))- if getattr(args, "prefix", None) is not None- else watch.prefix- )- )+ prefix = watch.prefixmessage_changed = any(getattr(args, name, None) is not None- for name in ("message", "message_file", "prompt", "prompt_file")+ for name in ("message", "message_file"))if message_changed:message = _resolve_optional_message_input(args,help_command="vibe watch update --help",example_command=f"vibe watch update {args.watch_id}",- legacy_prefix=None,)- elif getattr(args, "prefix", None) is not None or getattr(args, "clear_prefix", False):- message = prefixelse:message = getattr(watch, "message", None) or watch.prefix# Same three durable Agent-authority states ``vibe task update`` keeps, on the@@ -11893,12 +11427,11 @@ def cmd_watch_update(args):reserved_session_id,reason="watch update failed before its Session reservation was adopted",)- lang = _configured_cli_language()_print_task_error(TaskCliError(- i18n_t("error.jobWatchUpdateRefused.message", lang),+ "This Watch waits on a command that is already running, so only its name, message, and lifetime can be changed.",code=exc.code,- hint=i18n_t("error.jobWatchUpdateRefused.hint", lang, id=exc.watch_id),+ hint=f"Its Session, Agent, delivery, and command were fixed when the command was handed over. Change the name, message, or lifetime with `vibe watch update {exc.watch_id}`.",help_command="vibe watch update --help",details={"watch_id": exc.watch_id},)@@ -11945,18 +11478,18 @@ def _add_dependency_download_failure(label: str,code_prefix: str,repair_target: str | None,+ language: str = "en",retry_action: str | None = None,failure_status: str = "fail",) -> None:- language = _configured_cli_language()error = error or {}kind = str(error.get("kind") or "unknown")url = str(error.get("url") or i18n_t("doctor.value.selectedDependencyUrl", language))attempts = int(error.get("attempts") or 1)retry_action = retry_action or (- i18n_t("doctor.action.repairCommand", _configured_cli_language(), target=repair_target)+ i18n_t("doctor.action.repairCommand", language, target=repair_target)if repair_target- else i18n_t("doctor.action.askillManual", _configured_cli_language())+ else i18n_t("doctor.action.askillManual", language))if kind == "http" and error.get("http_status") == 404:_add_doctor_item(@@ -12059,10 +11592,9 @@ def _add_dependency_download_failure()-def _managed_dependencies_doctor_items(*, deep: bool = False) -> list[dict]:+def _managed_dependencies_doctor_items(*, language: str = "en", deep: bool = False) -> list[dict]:from core.dependency_network import probe_url- language = _configured_cli_language()labels = {"askill": "askill","avault": "avault",@@ -12253,6 +11785,7 @@ def _managed_dependencies_doctor_items(*, deep: bool = False) -> list[dict]:label=label,code_prefix=f"dependencies.{dependency_id}.download",repair_target=repair_target,+ language=language,retry_action=retry_action,failure_status=severity,)@@ -12277,11 +11810,10 @@ def _show_runtime_install(payload: dict) -> dict:return install if isinstance(install, dict) else {}-def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:+def _show_runtime_doctor_items(*, language: str = "en", deep: bool = False) -> list[dict]:from core.show_runtime import ShowRuntimeManageritems: list[dict] = []- doctor_language = _configured_cli_language()try:manager = ShowRuntimeManager(offline=True if not deep else None)status = manager.status()@@ -12289,8 +11821,8 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:_add_doctor_item(items,"fail",- i18n_t("doctor.item.showRuntimeStatusFailed", doctor_language, reason=exc),- i18n_t("doctor.action.showRuntimeStatusFailed", doctor_language),+ i18n_t("doctor.item.showRuntimeStatusFailed", language, reason=exc),+ i18n_t("doctor.action.showRuntimeStatusFailed", language),code="show_runtime.status_failed",)return items@@ -12304,8 +11836,8 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:_add_doctor_item(items,"warn",- i18n_t("doctor.item.archiveCacheSkipped", doctor_language),- i18n_t("doctor.action.archiveCacheSkippedInspection", doctor_language),+ i18n_t("doctor.item.archiveCacheSkipped", language),+ i18n_t("doctor.action.archiveCacheSkippedInspection", language),code="show_runtime.archive_cache_skipped",archive_cache_skip_reason=archive_skipped_reason,)@@ -12313,8 +11845,8 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:_add_doctor_item(items,"warn",- i18n_t("doctor.item.archiveCacheSkipped", doctor_language),- i18n_t("doctor.action.archiveCacheSkipped", doctor_language),+ i18n_t("doctor.item.archiveCacheSkipped", language),+ i18n_t("doctor.action.archiveCacheSkipped", language),code="show_runtime.archive_cache_skipped",archive_cache_skip_reason=archive_skipped_reason,)@@ -12324,18 +11856,18 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:"warn",i18n_t("doctor.item.archiveCacheReclaimable",- doctor_language,+ language,count=int(archive_cache.get("candidate_count") or 0),size=_format_byte_size(int(archive_cache.get("candidate_bytes") or 0)),),- i18n_t("doctor.action.archiveCacheReclaimable", doctor_language),+ i18n_t("doctor.action.archiveCacheReclaimable", language),code="show_runtime.archive_cache_reclaimable",)elif archive_cache is not None:_add_doctor_item(items,"pass",- i18n_t("doctor.item.archiveCacheClean", doctor_language),+ i18n_t("doctor.item.archiveCacheClean", language),code="show_runtime.archive_cache_clean",)@@ -12354,32 +11886,32 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:"fail",i18n_t("doctor.item.showRuntimeStatusFailed",- doctor_language,+ language,reason=inspection.get("message") or status.get("reason"),),- i18n_t("doctor.action.showRuntimeStatusFailed", doctor_language),+ i18n_t("doctor.action.showRuntimeStatusFailed", language),code="show_runtime.status_failed",status_reason=status.get("reason"),)return itemsinstalled = install.get("state") == "installed"provider = str(status.get("provider") or "unknown")- display_provider = _doctor_display_value(provider, "show_runtime_provider", doctor_language)- current_platform = status.get("platform") or i18n_t("doctor.value.currentPlatform", doctor_language)+ display_provider = _doctor_display_value(provider, "show_runtime_provider", language)+ current_platform = status.get("platform") or i18n_t("doctor.value.currentPlatform", language)explicit_command = status.get("explicit_command")if explicit_command:if installed:_add_doctor_item(items,"pass",- i18n_t("doctor.item.explicitCommandAvailable", doctor_language, command=explicit_command),+ i18n_t("doctor.item.explicitCommandAvailable", language, command=explicit_command),)else:_add_doctor_item(items,"fail",- i18n_t("doctor.item.explicitCommandMissing", doctor_language, command=explicit_command),- i18n_t("doctor.action.explicitCommandMissing", doctor_language),+ i18n_t("doctor.item.explicitCommandMissing", language, command=explicit_command),+ i18n_t("doctor.action.explicitCommandMissing", language),code="show_runtime.explicit_command_missing",)return items@@ -12401,8 +11933,8 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:_add_doctor_item(items,"fail",- i18n_t("doctor.item.manifestMissing", doctor_language),- i18n_t("doctor.action.manifestMissing", doctor_language),+ i18n_t("doctor.item.manifestMissing", language),+ i18n_t("doctor.action.manifestMissing", language),code="show_runtime.manifest_missing",)elif not archive:@@ -12412,10 +11944,10 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:"fail",i18n_t("doctor.item.manifestPlatformUnsupported",- doctor_language,+ language,platform=current_platform,),- i18n_t("doctor.action.manifestPlatformUnsupported", doctor_language),+ i18n_t("doctor.action.manifestPlatformUnsupported", language),code="show_runtime.platform_unsupported",)else:@@ -12424,7 +11956,7 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:"pass",i18n_t("doctor.item.manifestReady",- doctor_language,+ language,name=archive.get("name"),url=archive_url,),@@ -12436,24 +11968,24 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:_add_doctor_item(items,"fail",- i18n_t("doctor.item.legacyArchiveProvider", doctor_language, url=archive_url),- i18n_t("doctor.action.legacyArchiveProvider", doctor_language),+ i18n_t("doctor.item.legacyArchiveProvider", language, url=archive_url),+ i18n_t("doctor.action.legacyArchiveProvider", language),code="show_runtime.legacy_archive_provider",)else:_add_doctor_item(items,"warn",- i18n_t("doctor.item.unpinnedArchiveProvider", doctor_language),- i18n_t("doctor.action.unpinnedArchiveProvider", doctor_language),+ i18n_t("doctor.item.unpinnedArchiveProvider", language),+ i18n_t("doctor.action.unpinnedArchiveProvider", language),code="show_runtime.unpinned_archive_provider",)elif provider == "npm":_add_doctor_item(items,"warn",- i18n_t("doctor.item.developmentProvider", doctor_language, provider=display_provider),- i18n_t("doctor.action.developmentProvider", doctor_language),+ i18n_t("doctor.item.developmentProvider", language, provider=display_provider),+ i18n_t("doctor.action.developmentProvider", language),code="show_runtime.development_provider",show_runtime_provider=provider,)@@ -12462,8 +11994,8 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:_add_doctor_item(items,"fail",- i18n_t("doctor.item.providerUnsupported", doctor_language, provider=display_provider),- i18n_t("doctor.action.providerUnsupported", doctor_language),+ i18n_t("doctor.item.providerUnsupported", language, provider=display_provider),+ i18n_t("doctor.action.providerUnsupported", language),code="show_runtime.provider_unsupported",show_runtime_provider=provider,)@@ -12474,7 +12006,7 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:"pass",i18n_t("doctor.item.showRuntimeInstalled",- doctor_language,+ language,platform=current_platform,),code="show_runtime.installed",@@ -12483,22 +12015,22 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:show_runtime_repairable = provider_repairable and node_available and node_supported and archive_scheme_supportedshow_runtime_retry_action = (- i18n_t("doctor.action.showRuntimeRepair", doctor_language)+ i18n_t("doctor.action.showRuntimeRepair", language)if show_runtime_repairable- else i18n_t("doctor.action.showRuntimeRetry", doctor_language)+ else i18n_t("doctor.action.showRuntimeRetry", language))_add_doctor_item(items,"fail",i18n_t("doctor.item.showRuntimeNotReady",- doctor_language,+ language,platform=current_platform,),(- i18n_t("doctor.action.showRuntimeRepair", doctor_language)+ i18n_t("doctor.action.showRuntimeRepair", language)if show_runtime_repairable- else i18n_t("doctor.action.showRuntimeRetry", doctor_language)+ else i18n_t("doctor.action.showRuntimeRetry", language)),code="show_runtime.not_ready",repair_target="show-runtime" if show_runtime_repairable else None,@@ -12511,8 +12043,8 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:_add_doctor_item(items,"pass",- i18n_t("doctor.item.archiveProbeSkipped", doctor_language),- i18n_t("doctor.action.archiveProbeSkipped", doctor_language),+ i18n_t("doctor.item.archiveProbeSkipped", language),+ i18n_t("doctor.action.archiveProbeSkipped", language),code="show_runtime.archive_probe_skipped",)return items@@ -12524,15 +12056,15 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:_add_doctor_item(items,"pass",- i18n_t("doctor.item.archiveReachable", doctor_language, target=target),+ i18n_t("doctor.item.archiveReachable", language, target=target),code="show_runtime.archive_reachable",)elif probe_reason == "runtime_archive_probe_unsupported":_add_doctor_item(items,"warn",- i18n_t("doctor.item.archiveProbeUnsupported", doctor_language),- i18n_t("doctor.action.archiveProbeUnsupported", doctor_language, retry=show_runtime_retry_action),+ i18n_t("doctor.item.archiveProbeUnsupported", language),+ i18n_t("doctor.action.archiveProbeUnsupported", language, retry=show_runtime_retry_action),code="show_runtime.archive_probe_unsupported",)elif probe.get("download_error"):@@ -12542,10 +12074,11 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:probe.get("download_error"),label=i18n_t("doctor.value.showRuntimeManifest" if is_manifest_failure else "doctor.value.showRuntimeArchive",- doctor_language,+ language,),code_prefix="show_runtime.manifest" if is_manifest_failure else "show_runtime.archive",repair_target="show-runtime" if show_runtime_repairable else None,+ language=language,retry_action=show_runtime_retry_action,)elif probe_reason == "runtime_archive_url_unsupported":@@ -12554,18 +12087,18 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:"fail",i18n_t("doctor.item.archiveUrlUnsupported",- doctor_language,+ language,url=probe.get("url") or (archive or {}).get("url"),),- i18n_t("doctor.action.archiveUrlUnsupported", doctor_language),+ i18n_t("doctor.action.archiveUrlUnsupported", language),code="show_runtime.archive_url_unsupported",)elif probe_reason.startswith("runtime_manifest_"):_add_doctor_item(items,"fail",- i18n_t("doctor.item.manifestUnavailable", doctor_language),- i18n_t("doctor.action.manifestUnavailable", doctor_language),+ i18n_t("doctor.item.manifestUnavailable", language),+ i18n_t("doctor.action.manifestUnavailable", language),code="show_runtime.manifest_unavailable",probe_reason=probe_reason,)@@ -12575,10 +12108,10 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:"fail",i18n_t("doctor.item.manifestPlatformUnsupported",- doctor_language,+ language,platform=current_platform,),- i18n_t("doctor.action.showRuntimePlatformUnsupported", doctor_language),+ i18n_t("doctor.action.showRuntimePlatformUnsupported", language),code="show_runtime.platform_unsupported",)else:@@ -12587,11 +12120,11 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:"fail",i18n_t("doctor.item.archiveCheckFailed",- doctor_language,+ language,),i18n_t("doctor.action.archiveCheckFailed",- doctor_language,+ language,retry=show_runtime_retry_action,),code="show_runtime.archive_check_failed",@@ -12600,9 +12133,12 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:return items-def _doctor(*, deep: bool = False):+def _doctor(*, deep: bool = False, language: str = "en"):"""Run diagnostic checks and return results in UI-compatible format.+ The report is rendered in ``language``: English for the CLI, the configured+ UI language for the Web doctor panel, which passes it explicitly.+Returns:{"mode": "deep|fast",@@ -12613,9 +12149,8 @@ def _doctor(*, deep: bool = False):"""groups = []summary = {"pass": 0, "warn": 0, "fail": 0}- language = _configured_cli_language()- home_items = _home_migration_items()+ home_items = _home_migration_items(language=language)for item in home_items:status = item.get("status")if status in summary:@@ -12969,13 +12504,13 @@ def _doctor(*, deep: bool = False):summary["pass"] += 1for item in [- *_service_lifecycle_items(detect_extra_processes=deep),- *_service_install_family_items(detect_extra_processes=deep),- *_service_generation_items(),- *_restart_state_items(),- *_runtime_architecture_items(),- *_show_git_checkpoint_items(),- *_scheduled_task_weekday_items(),+ *_service_lifecycle_items(language=language, detect_extra_processes=deep),+ *_service_install_family_items(language=language, detect_extra_processes=deep),+ *_service_generation_items(language=language),+ *_restart_state_items(language=language),+ *_runtime_architecture_items(language=language),+ *_show_git_checkpoint_items(language=language),+ *_scheduled_task_weekday_items(language=language),]:runtime_items.append(item)status = item.get("status")@@ -12985,8 +12520,8 @@ def _doctor(*, deep: bool = False):groups.append({"name": i18n_t("doctor.group.runtime", language), "items": runtime_items})dependency_items = [- *_managed_dependencies_doctor_items(deep=deep),- *_show_runtime_doctor_items(deep=deep),+ *_managed_dependencies_doctor_items(language=language, deep=deep),+ *_show_runtime_doctor_items(language=language, deep=deep),]for item in dependency_items:status = item.get("status")@@ -12994,7 +12529,7 @@ def _doctor(*, deep: bool = False):summary[status] += 1groups.append({"name": i18n_t("doctor.group.dependencies", language), "items": dependency_items})- local_cli_items = [*_stable_launcher_items(), *_local_cli_installation_items()]+ local_cli_items = [*_stable_launcher_items(language=language), *_local_cli_installation_items(language=language)]for item in local_cli_items:status = item.get("status")if status in summary:@@ -13204,7 +12739,7 @@ def _current_sqlite_revision() -> str | None:return str(row[0])-def _describe_launcher_selections(selections: list, language: str) -> str:+def _describe_launcher_selections(selections: list, language: str = "en") -> str:unknown = i18n_t("doctor.value.unknown", language)return "; ".join(f"{selection.launcher} -> {selection.version or unknown} ({selection.generation})"@@ -13212,11 +12747,10 @@ def _describe_launcher_selections(selections: list, language: str) -> str:)-def _stable_launcher_items() -> list[dict]:+def _stable_launcher_items(*, language: str = "en") -> list[dict]:"""Fail when two discoverable stable launchers select different installs."""items: list[dict] = []- language = _configured_cli_language()selections = stable_launcher_selections()if len(selections) < 2:return items@@ -13271,9 +12805,8 @@ def _stable_launcher_items() -> list[dict]:return items-def _local_cli_installation_items() -> list[dict]:+def _local_cli_installation_items(*, language: str = "en") -> list[dict]:items: list[dict] = []- language = _configured_cli_language()vibe_paths = _path_entries_for_executable("vibe")preferred_vibe = (Path.home() / ".local" / "bin" / "vibe").expanduser()@@ -13445,7 +12978,7 @@ def _doctor_managed_reason_key(reason: str) -> str | None:return None-def _doctor_managed_failure_detail(target: str, result: dict, language: str) -> str:+def _doctor_managed_failure_detail(target: str, result: dict, language: str = "en") -> str:download_error = result.get("download_error") if isinstance(result.get("download_error"), dict) else Noneif download_error:kind = str(download_error.get("kind") or "")@@ -13499,7 +13032,6 @@ def _start_service_after_repair(*,stopped_pids: list[int],) -> dict:- language = _configured_cli_language()try:new_pid = runtime.start_service()except Exception as exc:@@ -13507,7 +13039,7 @@ def _start_service_after_repair(return _doctor_repair_result(target,"failed",- i18n_t(failure_key, language, reason=exc),+ i18n_t(failure_key, reason=exc),stopped_pids=stopped_pids,)ui_pid = runtime.read_status().get("ui_pid")@@ -13515,7 +13047,7 @@ def _start_service_after_repair(return _doctor_repair_result(target,"repaired",- i18n_t(success_key, language),+ i18n_t(success_key),stopped_pids=stopped_pids,service_pid=new_pid,)@@ -13528,12 +13060,11 @@ def _runtime_home_exists_for_repair() -> bool:def _repair_home_migration(*, dry_run: bool = False) -> dict:target = "home-migration"- language = _configured_cli_language()if os.environ.get(paths.AVIBE_HOME_ENV):return _doctor_repair_result(target,"skipped",- i18n_t("doctor.repair.homeExplicit", language),+ i18n_t("doctor.repair.homeExplicit"),)avibe_home = Path.home() / paths.AVIBE_HOME_DIRNAME@@ -13542,31 +13073,31 @@ def _repair_home_migration(*, dry_run: bool = False) -> dict:legacy_present = legacy_home.exists() or legacy_home.is_symlink()if not avibe_present and not legacy_present:- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.homeNoRuntime", language))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.homeNoRuntime"))if avibe_present and legacy_present and not legacy_home.is_symlink():return _doctor_repair_result(target,"failed",- i18n_t("doctor.repair.homeConflict", language),+ i18n_t("doctor.repair.homeConflict"),)if not avibe_present and legacy_home.is_symlink():return _doctor_repair_result(target,"failed",- i18n_t("doctor.repair.homeSymlinkMissingCanonical", language),+ i18n_t("doctor.repair.homeSymlinkMissingCanonical"),)if avibe_present and legacy_home.is_symlink() and _path_points_to(legacy_home, avibe_home):- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.homeHealthy", language))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.homeHealthy"))if dry_run:if not avibe_present and legacy_present and not legacy_home.is_symlink():- return _doctor_repair_result(target, "planned", i18n_t("doctor.repair.homeDryMove", language))+ return _doctor_repair_result(target, "planned", i18n_t("doctor.repair.homeDryMove"))if avibe_present:- return _doctor_repair_result(target, "planned", i18n_t("doctor.repair.homeDryLink", language))- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.homeNoNeed", language))+ return _doctor_repair_result(target, "planned", i18n_t("doctor.repair.homeDryLink"))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.homeNoNeed"))if avibe_present:if legacy_home.is_symlink() or not legacy_present:@@ -13577,63 +13108,60 @@ def _repair_home_migration(*, dry_run: bool = False) -> dict:return _doctor_repair_result(target,"failed",- i18n_t("doctor.repair.homeLinkFailed", language, reason=exc),+ i18n_t("doctor.repair.homeLinkFailed", reason=exc),)- return _doctor_repair_result(target, "repaired", i18n_t("doctor.repair.homeLinkCreated", language))- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.homeNoNeed", language))+ return _doctor_repair_result(target, "repaired", i18n_t("doctor.repair.homeLinkCreated"))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.homeNoNeed"))migrated_home = paths.migrate_default_home()if not _path_points_to(migrated_home, avibe_home):return _doctor_repair_result(target,"failed",- i18n_t("doctor.repair.homeMigrationIncomplete", language, path=migrated_home),+ i18n_t("doctor.repair.homeMigrationIncomplete", path=migrated_home),)if not _path_points_to(legacy_home, avibe_home):return _doctor_repair_result(target,"failed",- i18n_t("doctor.repair.homeMigrationLinkFailed", language),+ i18n_t("doctor.repair.homeMigrationLinkFailed"),)paths.ensure_data_dirs()- return _doctor_repair_result(target, "repaired", i18n_t("doctor.repair.homeMigrated", language))+ return _doctor_repair_result(target, "repaired", i18n_t("doctor.repair.homeMigrated"))def _repair_stale_restart_state(*, dry_run: bool = False) -> dict:target = "stale-restart-state"- language = _configured_cli_language()restart_path = runtime.get_restart_status_path()payload = runtime.read_json(restart_path) or {}if not payload:- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.restartAbsent", language))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.restartAbsent"))if not _restart_status_is_stale(payload, restart_path):- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.restartCurrent", language))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.restartCurrent"))if dry_run:- return _doctor_repair_result(target, "planned", i18n_t("doctor.repair.restartDryRun", language))+ return _doctor_repair_result(target, "planned", i18n_t("doctor.repair.restartDryRun"))restart_path.unlink(missing_ok=True)_write_refreshed_runtime_status()- return _doctor_repair_result(target, "repaired", i18n_t("doctor.repair.restartRepaired", language))+ return _doctor_repair_result(target, "repaired", i18n_t("doctor.repair.restartRepaired"))def _repair_duplicate_service_processes(*, dry_run: bool = False) -> dict:target = "duplicate-service-processes"- language = _configured_cli_language()if runtime.service_instance_lock_attached_to_process():- return _doctor_repair_result(target, "failed", i18n_t("doctor.repair.cliOnly", language))+ return _doctor_repair_result(target, "failed", i18n_t("doctor.repair.cliOnly"))if not _runtime_home_exists_for_repair():- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.noRuntimeProcessState", language))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.noRuntimeProcessState"))owner_pid = runtime.resolve_service_owner_pid(include_starting=False)extra_pids = runtime.extra_service_process_pids(owner_pid=owner_pid)if not extra_pids:- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.noExtraProcess", language))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.noExtraProcess"))if dry_run:return _doctor_repair_result(target,"planned",i18n_t("doctor.repair.extraProcessDryRun",- language,pids=",".join(map(str, extra_pids)),),pids=extra_pids,@@ -13660,14 +13188,14 @@ def _repair_duplicate_service_processes(*, dry_run: bool = False) -> dict:return _doctor_repair_result(target,"failed",- i18n_t("doctor.repair.extraProcessPartial", language),+ i18n_t("doctor.repair.extraProcessPartial"),stopped_pids=stopped,failed_pids=failed,)return _doctor_repair_result(target,"repaired",- i18n_t("doctor.repair.extraProcessStopped", language),+ i18n_t("doctor.repair.extraProcessStopped"),stopped_pids=stopped,)@@ -13676,12 +13204,11 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:"""Point every managed stable launcher at the newest installed generation."""target_name = "stable-launchers"- language = _configured_cli_language()def in_step(selections: list) -> dict | None:if len({selection.generation for selection in selections}) < 2:return _doctor_repair_result(- target_name, "skipped", i18n_t("doctor.repair.stableLaunchersInStep", language)+ target_name, "skipped", i18n_t("doctor.repair.stableLaunchersInStep"))return None@@ -13690,7 +13217,7 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:if (skipped := in_step(stable_launcher_selections())) is not None:return skippedif dry_run:- return _doctor_repair_result(target_name, "planned", i18n_t("doctor.repair.dryStableLaunchers", language))+ return _doctor_repair_result(target_name, "planned", i18n_t("doctor.repair.dryStableLaunchers"))try:with atomic_upgrade_lock(timeout_seconds=DOCTOR_LAUNCHER_REPAIR_LOCK_TIMEOUT_SECONDS):selections = stable_launcher_selections()@@ -13704,12 +13231,11 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:"failed",i18n_t("doctor.repair.stableLaunchersTied",- language,- launchers=_describe_launcher_selections(top_ranked_selections(selections), language),+ launchers=_describe_launcher_selections(top_ranked_selections(selections)),),reason="stable_launchers_tied",)- unknown = i18n_t("doctor.value.unknown", language)+ unknown = i18n_t("doctor.value.unknown")moved: list[Path] = []running = Nonefor selection in selections:@@ -13734,7 +13260,6 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:"failed",i18n_t("doctor.repair.stableLauncherMoveFailed",- language,launcher=selection.launcher,version=target.version or unknown,generation=target.generation,@@ -13749,7 +13274,6 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:"failed",i18n_t("doctor.repair.stableLauncherRunning",- language,launcher=running.launcher,repairCommand=_launcher_command(target.launcher, *STABLE_LAUNCHER_REPAIR_ARGS),),@@ -13765,8 +13289,7 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:"failed",i18n_t("doctor.repair.stableLaunchersStillSplit",- language,- launchers=_describe_launcher_selections(remaining, language),+ launchers=_describe_launcher_selections(remaining),),reason="stable_launchers_still_split",launchers=[str(launcher) for launcher in moved],@@ -13775,7 +13298,7 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:return _doctor_repair_result(target_name,"failed",- i18n_t("doctor.repair.stableLaunchersBusy", language),+ i18n_t("doctor.repair.stableLaunchersBusy"),reason="upgrade_lock_busy",)except Exception as exc: # noqa: BLE001@@ -13783,7 +13306,7 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:return _doctor_repair_result(target_name,"failed",- i18n_t("doctor.repair.stableLaunchersFailed", language),+ i18n_t("doctor.repair.stableLaunchersFailed"),reason="stable_launcher_repair_exception",error=str(exc),)@@ -13792,9 +13315,8 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:"repaired",i18n_t("doctor.repair.stableLaunchersRepaired",- language,launchers=", ".join(map(str, moved)),- version=target.version or i18n_t("doctor.value.unknown", language),+ version=target.version or i18n_t("doctor.value.unknown"),generation=target.generation,),launchers=[str(launcher) for launcher in moved],@@ -13804,11 +13326,10 @@ def _repair_stable_launchers(*, dry_run: bool = False) -> dict:def _repair_stale_install_runtime(*, dry_run: bool = False) -> dict:target = "stale-install-runtime"- language = _configured_cli_language()if runtime.service_instance_lock_attached_to_process():- return _doctor_repair_result(target, "failed", i18n_t("doctor.repair.cliOnly", language))+ return _doctor_repair_result(target, "failed", i18n_t("doctor.repair.cliOnly"))if not _runtime_home_exists_for_repair():- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.noRuntimeProcessState", language))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.noRuntimeProcessState"))current_family = _current_cli_install_family()owner_pid = runtime.resolve_service_owner_pid(include_starting=False)@@ -13823,12 +13344,12 @@ def _repair_stale_install_runtime(*, dry_run: bool = False) -> dict:elif family == PACKAGE_NAME:current_pids.append(pid)if not stale_pids:- return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.noLegacyProcess", language))+ return _doctor_repair_result(target, "skipped", i18n_t("doctor.repair.noLegacyProcess"))if dry_run:return _doctor_repair_result(target,"planned",- i18n_t("doctor.repair.staleInstallDryRun", language, pids=",".join(map(str, stale_pids))),+ i18n_t("doctor.repair.staleInstallDryRun", pids=",".join(map(str, stale_pids))),pids=stale_pids,)@@ -13845,7 +13366,7 @@ def _repair_stale_install_runtime(*, dry_run: bool = False) -> dict:return _doctor_repair_result(target,"failed",- i18n_t("doctor.repair.staleInstallPartial", language),+ i18n_t("doctor.repair.staleInstallPartial"),stopped_pids=stopped,failed_pids=failed,)@@ -13855,7 +13376,7 @@ def _repair_stale_install_runtime(*, dry_run: bool = False) -> dict:return _doctor_repair_result(target,"repaired",- i18n_t("doctor.repair.staleInstallStopped", language),+ i18n_t("doctor.repair.staleInstallStopped"),stopped_pids=stopped,)@@ -13868,12 +13389,11 @@ def _repair_stale_install_runtime(*, dry_run: bool = False) -> dict:def _repair_managed_dependency(target: str, installer, *, dry_run: bool = False) -> dict:- language = _configured_cli_language()if dry_run:return _doctor_repair_result(target,"planned",- i18n_t(DOCTOR_REPAIR_DRY_RUN_I18N_KEYS[target], language),+ i18n_t(DOCTOR_REPAIR_DRY_RUN_I18N_KEYS[target]),)try:result = installer(force=True)@@ -13883,9 +13403,8 @@ def _repair_managed_dependency(target: str, installer, *, dry_run: bool = False)"failed",i18n_t("doctor.repair.dependencyResultFailed",- language,target=target,- detail=i18n_t("doctor.repair.dependencyException", language, target=target, error=exc),+ detail=i18n_t("doctor.repair.dependencyException", target=target, error=exc),),reason=f"{target}_repair_exception",error=str(exc),@@ -13894,21 +13413,20 @@ def _repair_managed_dependency(target: str, installer, *, dry_run: bool = False)result = {"ok": False,"reason": f"{target}_invalid_result",- "error": i18n_t("doctor.value.unknownError", language),+ "error": i18n_t("doctor.value.unknownError"),}if result.get("ok"):version = result.get("version")detail = (- i18n_t("doctor.repair.dependencyVersion", language, version=version)+ i18n_t("doctor.repair.dependencyVersion", version=version)if version- else i18n_t("doctor.repair.dependencyReadyDefault", language)+ else i18n_t("doctor.repair.dependencyReadyDefault"))return _doctor_repair_result(target,"repaired" if result.get("changed", True) else "skipped",i18n_t("doctor.repair.dependencyReady",- language,target=target,detail=detail,),@@ -13916,13 +13434,12 @@ def _repair_managed_dependency(target: str, installer, *, dry_run: bool = False)version=version,)download_error = result.get("download_error") if isinstance(result.get("download_error"), dict) else None- detail = _doctor_managed_failure_detail(target, result, language)+ detail = _doctor_managed_failure_detail(target, result)return _doctor_repair_result(target,"failed",i18n_t("doctor.repair.dependencyResultFailed",- language,target=target,detail=detail,),@@ -13964,12 +13481,11 @@ def _repair_show_runtime(*, dry_run: bool = False) -> dict:from core.show_runtime import ShowRuntimeManagertarget = "show-runtime"- language = _configured_cli_language()if dry_run:return _doctor_repair_result(target,"planned",- i18n_t(DOCTOR_REPAIR_DRY_RUN_I18N_KEYS[target], language),+ i18n_t(DOCTOR_REPAIR_DRY_RUN_I18N_KEYS[target]),)result = ShowRuntimeManager().repair()@@ -13983,7 +13499,7 @@ def _repair_show_runtime(*, dry_run: bool = False) -> dict:return _doctor_repair_result(target,"skipped",- i18n_t("doctor.repair.showRuntimeHealthy", language),+ i18n_t("doctor.repair.showRuntimeHealthy"),provider=result.get("provider"),platform=result.get("platform"),install_dir=result.get("install_dir"),@@ -13998,7 +13514,6 @@ def _repair_show_runtime(*, dry_run: bool = False) -> dict:if result.get("was_installed")else "doctor.repair.showRuntimeInstalled"),- language,),provider=result.get("provider"),platform=result.get("platform"),@@ -14046,7 +13561,7 @@ def _repair_show_runtime(*, dry_run: bool = False) -> dict:return _doctor_repair_result(target,"failed",- i18n_t(message_key, language, **message_kwargs),+ i18n_t(message_key, **message_kwargs),provider=result.get("provider"),platform=result.get("platform"),install_dir=result.get("install_dir"),@@ -14060,7 +13575,6 @@ def _repair_show_runtime(*, dry_run: bool = False) -> dict:def _repair_doctor_targets(targets: list[str], *, dry_run: bool = False, deep: bool = False) -> dict:- language = _configured_cli_language()requested_targets = targets or list(DOCTOR_DEFAULT_REPAIR_TARGETS)unknown = [target for target in requested_targets if target not in DOCTOR_REPAIR_TARGETS]if unknown:@@ -14074,7 +13588,6 @@ def _repair_doctor_targets(targets: list[str], *, dry_run: bool = False, deep: b"failed",i18n_t("doctor.repair.unknownTarget",- language,target=target,known_targets=", ".join(DOCTOR_REPAIR_TARGETS),),@@ -14092,7 +13605,7 @@ def _repair_doctor_targets(targets: list[str], *, dry_run: bool = False, deep: b_doctor_repair_result(target,"planned",- i18n_t(DOCTOR_REPAIR_DRY_RUN_I18N_KEYS[target], language),+ i18n_t(DOCTOR_REPAIR_DRY_RUN_I18N_KEYS[target]),)for target in requested_targets],@@ -14131,7 +13644,6 @@ def _confirm_doctor_repair(targets: list[str]) -> bool:answer = input(i18n_t("doctor.repairConfirm",- _configured_cli_language(),targets=target_text,))@@ -14158,20 +13670,19 @@ def _handover_superseded_desktop_runtime(*, allowed: bool) -> int:if actual_runtime_id is None or actual_runtime_id == expected_runtime_id:return 0- language = _configured_cli_language()# Only the desktop host asks for a handover, when a user launches or# retries its app; any other start leaves another desktop Runtime alone.if not allowed:- print(i18n_t("desktopRuntime.handoverNotRequested", language), file=sys.stderr)+ print("Another desktop-managed Avibe Runtime is running here; this start does not replace it.", file=sys.stderr)return 3# Health names the Runtime that answered; the stop signals only processes# that carry its id.result = runtime.stop_desktop_runtime(actual_runtime_id)if result.refusal is not None:- print(i18n_t("desktopRuntime.handoverRefused", language, reason=result.refusal), file=sys.stderr)+ print(f"Refused to stop the superseded desktop-managed Avibe Runtime: {result.refusal}", file=sys.stderr)return 3if result.failure is not None:- print(i18n_t("desktopRuntime.handoverFailed", language, part=result.failure), file=sys.stderr)+ print(f"Failed to stop the superseded desktop-managed Avibe Runtime: {result.failure}", file=sys.stderr)return 2# Anything still running is not the superseded Runtime's; the start claims# only what carries this Runtime's id.@@ -14191,7 +13702,7 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):try:runtime.claim_desktop_runtime_start()except runtime.DesktopRuntimeClaimRefused as refusal:- _print_provenance_refusal("desktopRuntime.claimRefused", refusal)+ _print_provenance_refusal("claim", refusal)return 3has_configured_platform_credentials = getattr(config, "has_configured_platform_credentials", None)@@ -14338,7 +13849,7 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):# another Runtime started meanwhile is left running.runtime.roll_back_start(service_start, ui_start)if isinstance(exc, runtime.DesktopRuntimeClaimRefused):- _print_provenance_refusal("desktopRuntime.claimRefused", exc)+ _print_provenance_refusal("claim", exc)return 3raiseif service_ready:@@ -14416,18 +13927,18 @@ def _runtime_process_was_running() -> bool:# The part of a stop that did not stop: its localized diagnostic and the# status detail, which stays English for machine readers._STOP_FAILURES = {- "service": ("runtime.stop.serviceFailed", "service stop failed"),- "ui": ("runtime.stop.uiFailed", "ui stop failed"),- "installer": ("runtime.stop.installerFailed", "desktop backend install drain failed"),- "opencode": ("runtime.stop.opencodeFailed", "opencode stop failed"),- "unknown": ("runtime.stop.unknownFailed", "unidentified runtime process left running"),- "remote_access": ("runtime.stop.remoteAccessFailed", "remote access stop failed"),+ "service": ("ERROR: Avibe service did not stop; preserving pidfile and aborting.", "service stop failed"),+ "ui": ("ERROR: Avibe UI did not stop; preserving pidfile and aborting.", "ui stop failed"),+ "installer": ("ERROR: Desktop backend installer processes did not stop.", "desktop backend install drain failed"),+ "opencode": ("ERROR: The OpenCode server this Runtime started did not stop.", "opencode stop failed"),+ "unknown": ("ERROR: A process this Runtime started could not be identified and was left running.", "unidentified runtime process left running"),+ "remote_access": ("ERROR: The remote access tunnel could not be stopped.", "remote access stop failed"),}def _stop_failed(part: str, write_status: Callable[..., None] | None = None) -> int:- key, detail = _STOP_FAILURES[part]- print(i18n_t(key, _configured_cli_language()), file=sys.stderr)+ message, detail = _STOP_FAILURES[part]+ print(message, file=sys.stderr)(write_status or _write_status)("error", detail)return 2@@ -14440,7 +13951,7 @@ def _write_status_unless_a_service_holds_the_lock(*status: str) -> None:def _report_opencode_stopped() -> None:- print(i18n_t("runtime.stop.opencodeStopped", _configured_cli_language()))+ print("OpenCode server stopped")def _print_stop_json(payload: dict) -> None:@@ -14501,15 +14012,22 @@ def _stop_the_home_s_connector() -> int:return outcome[0]-def _print_provenance_refusal(key: str, refusal: runtime.DesktopRuntimeClaimRefused) -> None:+_PROVENANCE_REFUSALS = {+ "claim": "Another Avibe Runtime is running here and does not belong to this desktop app; nothing was stopped ({part}: {reason}).",+ "stop": "Nothing was stopped: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Stop it from the Avibe that started it.",+ "restart": "Nothing was restarted: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Restart it from the Avibe that started it.",+}+++def _print_provenance_refusal(action: str, refusal: runtime.DesktopRuntimeClaimRefused) -> None:print(- i18n_t(key, _configured_cli_language(), part=refusal.part, reason=refusal.reason),+ _PROVENANCE_REFUSALS[action].format(part=refusal.part, reason=refusal.reason),file=sys.stderr,)def _desktop_provenance_refused(- key: str,+ action: str,*,include_ui: bool = True,runtime_ids: frozenset[str] | None = None,@@ -14519,7 +14037,7 @@ def _desktop_provenance_refused(refusal = runtime.desktop_provenance_refusal(include_ui=include_ui, runtime_ids=runtime_ids)if refusal is None:return False- _print_provenance_refusal(key, refusal)+ _print_provenance_refusal(action, refusal)return True@@ -14573,7 +14091,7 @@ def cmd_stop(*, expect_runtime_id: str | None = None):# that took over in between is refused too. An OpenCode server of another# Runtime is left running.provenance = desktop_caller_provenance()- if _desktop_provenance_refused("desktopRuntime.stopRefused", runtime_ids=provenance):+ if _desktop_provenance_refused("stop", runtime_ids=provenance):return 3service_was_running = _pid_file_points_to_live_process(paths.get_runtime_pid_path())ui_was_running = _pid_file_points_to_live_process(paths.get_runtime_ui_pid_path())@@ -14582,7 +14100,7 @@ def cmd_stop(*, expect_runtime_id: str | None = None):service_stopped = runtime.stop_service(runtime_ids=provenance, shutdown_reason="full_stop")ui_stopped = runtime.stop_ui(runtime_ids=provenance)except runtime.DesktopRuntimeClaimRefused as refusal:- _print_provenance_refusal("desktopRuntime.stopRefused", refusal)+ _print_provenance_refusal("stop", refusal)return 3# Holding the free service lock: neither a service that failed to stop nor one# started since owns these commands while they are stopped.@@ -14610,7 +14128,7 @@ def cmd_stop(*, expect_runtime_id: str | None = None):def cmd_status():- print(_render_status())+ _print_cli_payload("service_status", **json.loads(_render_status()))return 0@@ -14687,7 +14205,6 @@ def _print_remote_pair_start() -> None:def _print_remote_pair_failure(result: dict) -> None:error_code = str(result.get("error") or "unknown_error")- language = _configured_cli_language()if error_code in {"invalid_pairing_key", "pairing_key_expired", "pairing_key_used"}:print("Pairing key is invalid or expired.", file=sys.stderr)print("Create a new pairing key at https://avibe.bot, then run:", file=sys.stderr)@@ -14701,71 +14218,74 @@ def _print_remote_pair_failure(result: dict) -> None:print(f"Detail: {result['detail']}", file=sys.stderr)returnif error_code == "pairing_local_write_unavailable":- print(i18n_t("remote_access.cli.localWriteUnavailableTitle", language), file=sys.stderr)- print(i18n_t("remote_access.cli.localWriteUnavailableBody", language), file=sys.stderr)+ print("Remote access setup stopped before contacting Avibe Cloud.", file=sys.stderr)+ print("The local config cannot durably accept a pairing, so no pairing key was consumed.", file=sys.stderr)if result.get("detail"):print(f"Detail: {result['detail']}", file=sys.stderr)- print(i18n_t("remote_access.cli.retryAfterLocalFix", language), file=sys.stderr)+ print("Fix the local config problem, then run:", file=sys.stderr)print(" vibe remote", file=sys.stderr)returnif error_code == "pairing_save_failed_after_redeem":orphan = result.get("orphaned_binding") or {}- print(i18n_t("remote_access.cli.saveFailedAfterRedeemTitle", language), file=sys.stderr)+ print("The pairing was redeemed cloud-side but could not be saved locally.", file=sys.stderr)if orphan.get("instance_id"):- print(i18n_t(- "remote_access.cli.orphanedBinding",- language,- instance_id=orphan["instance_id"],- device_name=orphan.get("device_name") or "unknown",- ), file=sys.stderr)- print(i18n_t("remote_access.cli.recoveryRetained", language), file=sys.stderr)- print(i18n_t("remote_access.cli.retryAfterLocalFix", language), file=sys.stderr)+ print("Orphaned binding: instance {instance_id} (device {device_name}).".format(instance_id=orphan["instance_id"], device_name=orphan.get("device_name") or "unknown"), file=sys.stderr)+ print("The redeemed credentials are kept on this host, so no new pairing key is needed.", file=sys.stderr)+ print("Fix the local config problem, then run:", file=sys.stderr)print(" vibe remote pair", file=sys.stderr)if result.get("detail"):print(f"Detail: {result['detail']}", file=sys.stderr)returnif error_code == "pairing_recovery_invalid":- print(i18n_t("remote_access.cli.recoveryInvalid", language), file=sys.stderr)+ print("The saved pairing recovery record is invalid and cannot be replayed.", file=sys.stderr)if result.get("detail"):print(f"Detail: {result['detail']}", file=sys.stderr)returnif error_code == "pairing_recovery_unavailable":- print(i18n_t("remote_access.cli.recoveryUnavailable", language), file=sys.stderr)+ print("Local pairing recovery could not start. No new pairing key was consumed.", file=sys.stderr)if result.get("detail"):print(f"Detail: {result['detail']}", file=sys.stderr)- print(i18n_t("remote_access.cli.retryAfterLocalFix", language), file=sys.stderr)+ print("Fix the local config problem, then run:", file=sys.stderr)print(" vibe remote pair", file=sys.stderr)returnif error_code in {"pairing_recovery_not_ready", "pairing_superseded_after_redeem", "pairing_redeem_indeterminate",}:- message_key = "recoveryNotReady" if error_code == "pairing_recovery_not_ready" else "recoveryIndeterminate"- print(i18n_t(f"remote_access.cli.{message_key}", language), file=sys.stderr)- print(i18n_t("remote_access.cli.replacePendingPairing", language), file=sys.stderr)+ message = (+ "A pairing operation has no durably recorded response. It may still be running or may have consumed the key. A keyless retry cannot recover it."+ if error_code == "pairing_recovery_not_ready"+ else "The pairing outcome is uncertain or was superseded locally. No recoverable response is guaranteed; do not reuse the submitted key."+ )+ print(message, file=sys.stderr)+ print("Check the cloud console and ensure no pairing is still running. To explicitly replace the pending attempt, substitute a fresh key and the intended backend URL in this command (the default backend is https://avibe.bot):", file=sys.stderr)print(" vibe remote pair NEW_PAIRING_KEY --backend-url BACKEND_URL", file=sys.stderr)if result.get("detail"):print(f"Detail: {result['detail']}", file=sys.stderr)returnif error_code == "pairing_recovery_revoked":- print(i18n_t("remote_access.cli.recoveryRevoked", language), file=sys.stderr)+ print("The saved pairing recovery was invalidated by a local unpair operation.", file=sys.stderr)if result.get("detail"):print(f"Detail: {result['detail']}", file=sys.stderr)returnif error_code == "pairing_retirement_failed":pairing = result.get("pairing") or {}if pairing.get("applied") is False:- key = "failedClaimCleanup" if pairing.get("retirement_pending") else "failedClaimUnrecorded"+ message = (+ "This pairing attempt failed and was not applied. Fix local storage, then retry without a key to clear its failed-operation record."+ if pairing.get("retirement_pending")+ else "This pairing attempt failed and was not applied. Its cleanup could not be recorded. After fixing local storage, supply a fresh pairing key explicitly to 'vibe remote pair'; a keyless retry cannot recover this result."+ )else:- key = "retirementFailed"- print(i18n_t(f"remote_access.cli.{key}", language), file=sys.stderr)+ message = "Pairing was applied, but its recovery record could not be retired. Retry without a new key."+ print(message, file=sys.stderr)if result.get("detail"):print(f"Detail: {result['detail']}", file=sys.stderr)if pairing.get("applied") is not False or pairing.get("retirement_pending"):- print(i18n_t("remote_access.cli.retryPairCommand", language), file=sys.stderr)+ print("Retry local pairing recovery with:", file=sys.stderr)print(" vibe remote pair", file=sys.stderr)returnif error_code == "pairing_failure_retired":- print(i18n_t("remote_access.cli.failedClaimRetired", language), file=sys.stderr)+ print("The failed pairing record was cleared. Get a fresh pairing key, then run the following command to enter it securely:", file=sys.stderr)print(" vibe remote pair", file=sys.stderr)returnif error_code == "invalid_pairing_response":@@ -14885,7 +14405,7 @@ def _run_remote_pair(args, *, guided: bool) -> int:if not pairing_key and not pending_operation_exists:payload = {"ok": False, "error": "missing_pairing_key", "hint": "Run 'vibe remote' to restart setup."}if getattr(args, "json", False):- _print_json(payload)+ _print_cli_payload("remote_pair", **payload)else:print("Pairing failed: missing pairing key.", file=sys.stderr)print("Run 'vibe remote' to restart setup.", file=sys.stderr)@@ -14905,7 +14425,7 @@ def _run_remote_pair(args, *, guided: bool) -> int:if result.get("ok") and not command_ok:payload.setdefault("pairing", {"ok": True})payload.setdefault("error", str(start_result.get("error") or "remote_start_failed"))- _print_json(payload)+ _print_cli_payload("remote_pair", **payload)return 0 if command_ok else 1if not result.get("ok"):@@ -14929,7 +14449,7 @@ def cmd_remote_status(args):result = remote_access.status()if getattr(args, "json", False):- _print_json(result)+ _print_cli_payload("remote_status", **result)else:_print_remote_status(result)return 0 if result.get("ok") else 1@@ -14940,7 +14460,7 @@ def cmd_remote_start(args):result = remote_access.start()if getattr(args, "json", False):- _print_json(result)+ _print_cli_payload("remote_start", **result)else:if result.get("ok"):if result.get("started"):@@ -14963,7 +14483,7 @@ def cmd_remote_stop(args):result = remote_access.stop()if getattr(args, "json", False):- _print_json(result)+ _print_cli_payload("remote_stop", **result)else:if result.get("ok"):print("Remote access tunnel stopped." if result.get("stopped") else "Remote access tunnel is already stopped.")@@ -14977,6 +14497,7 @@ def cmd_remote_stop(args):def _show_page_result(page,*,+ kind: str = "show_page",message: str,previous_payload: dict | None = None,extra: dict | None = None,@@ -14984,11 +14505,7 @@ def _show_page_result() -> dict:from core.show_pages import show_page_payload- payload = {- "ok": True,- **show_page_payload(page),- "message": message,- }+ payload = _cli_payload(kind, **show_page_payload(page), message=message)if previous_payload:payload.update(previous_payload)if extra:@@ -15023,81 +14540,12 @@ def _show_page_next_actions(payload: dict, *, include_annotation_guidance: boolreturn actions-def _print_show_page_result(payload: dict) -> None:- print("Show Page:")- print(f" Path: {payload.get('path')}")- print(f" URL: {payload.get('active_url') or 'none'}")- print(f" Visibility: {payload.get('visibility')}")- if payload.get("previous_active_url"):- print(f" Previous URL: {payload.get('previous_active_url')} (inactive)")- elif payload.get("previous_public_url"):- print(f" Previous URL: {payload.get('previous_public_url')} (inactive)")- elif payload.get("previous_private_url"):- print(f" Previous URL: {payload.get('previous_private_url')} (inactive)")- if payload.get("message"):- print(f" Status: {payload.get('message')}")- if payload.get("url_guidance"):- print(f" URL guidance: {payload.get('url_guidance')}")- next_actions = payload.get("next_actions") or []- if next_actions:- print("")- print("Use it:")- for action in next_actions:- print(f" - {action}")---def _print_show_page_status_missing(session_id: str) -> None:- print("Show Page: not created")- print(" Path: none")- print(" URL: none")- print(" Visibility: none")- print("")- print("Use it:")- print(f" - Create the workspace with: vibe show path --session-id {session_id}")- print(" - Then edit src/App.tsx in the returned directory.")- print(" - For more options, run: vibe show --help")---def _print_show_page_list(payload: dict) -> None:- pages = payload.get("pages") or []- print("Show Pages:")- if payload.get("global"):- print(" Sessions: all")- elif payload.get("session_id"):- print(f" Session: {payload['session_id']}")- print(f" Count: {payload.get('count', 0)}")- visibility = payload.get("visibility")- if visibility:- print(f" Filter: visibility={visibility}")- if payload.get("url_guidance"):- print(f" URL guidance: {payload.get('url_guidance')}")- if not pages:- print("")- print("No Show Pages found.")- print("Create one with: vibe show path --session-id <session-id>")- return- print("")- for page in pages:- print(f"- {page.get('session_id')}")- print(f" Path: {page.get('path')}")- print(f" URL: {page.get('active_url') or 'none'}")- print(f" Visibility: {page.get('visibility')}")- print(f" Updated: {page.get('updated_at')}")- continuation = _text_page_continuation(payload)- if continuation:- print("")- print(continuation)- print("")- print("Use it:")- print(" - Open a page: vibe show status --session-id <session-id>")- print(" - Edit files under the listed Path.")- print(" - For more options, run: vibe show --help")--def _print_show_page_error(exc: Exception) -> None:code = getattr(exc, "code", "show_page_failed")payload = {+ "schema_version": 1,"ok": False,+ "kind": "error","code": code,"error": str(exc),"help_command": getattr(exc, "help_command", None) or "vibe show --help",@@ -15108,7 +14556,7 @@ def _print_show_page_error(exc: Exception) -> None:details = getattr(exc, "details", None)if details:payload["details"] = details- print(json.dumps(payload, indent=2), file=sys.stderr)+ print(_json_text(payload, stream=sys.stderr), file=sys.stderr)def _load_show_page_store():@@ -15147,21 +14595,15 @@ def cmd_show_list(args):_add_optional_arg(command, "--updated-after", updated_after)_add_optional_arg(command, "--updated-before", updated_before)_add_optional_arg(command, "--q", getattr(args, "query", None))- if getattr(args, "json", False):- command.append("--json")- payload = {- "ok": True,+ _print_cli_payload(+ "show_pages",**scope.payload(),- "count": len(result.items),- "visibility": getattr(args, "visibility", None),- "pages": [show_page_payload(page) for page in result.items],+ count=len(result.items),+ visibility=getattr(args, "visibility", None),+ pages=[show_page_payload(page) for page in result.items],**_paginated_fields(result, command=command),- "url_guidance": avibe_cloud_connect_guidance(),- }- if getattr(args, "json", False):- _print_json(payload)- else:- _print_show_page_list(payload)+ url_guidance=avibe_cloud_connect_guidance(),+ )return 0except Exception as exc:_print_show_page_error(exc)@@ -15176,7 +14618,7 @@ def cmd_show_path(args):store = _load_show_page_store()try:- session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show path --help")+ session_id = _resolve_caller_session_id(args, help_command="vibe show path --help")page = store.ensure(session_id)page_dir = ensure_show_page_dir(session_id)_prewarm_show_page_session_best_effort(@@ -15186,13 +14628,9 @@ def cmd_show_path(args):payload = _show_page_result(page,message=f"Show Page workspace is ready at {page_dir}.",- extra={"session_default_notice": session_default_notice} if session_default_notice else None,include_annotation_guidance=True,)- if getattr(args, "json", False):- _print_json(payload)- else:- _print_show_page_result(payload)+ _print_json(payload)return 0except Exception as exc:_print_show_page_error(exc)@@ -15215,36 +14653,24 @@ def cmd_show_status(args):store = _load_show_page_store()try:- session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show status --help")+ session_id = _resolve_caller_session_id(args, help_command="vibe show status --help")page = store.get(session_id)if page is None:- payload = {- "ok": False,- "code": "show_page_not_found",- "session_id": session_id,- "message": "No Show Page exists for this session.",- "next_actions": [f"Run `vibe show path --session-id {session_id}` to create the workspace."],- }- if session_default_notice:- payload["session_default_notice"] = session_default_notice- if getattr(args, "json", False):- _print_json(payload)- else:- print("No Show Page exists for this session.")- print(f"Run: vibe show path --session-id {session_id}")- return 1+ raise TaskCliError(+ "No Show Page exists for this session.",+ code="show_page_not_found",+ hint=f"Run `vibe show path --session-id {session_id}` to create the workspace.",+ help_command="vibe show path --help",+ details={"session_id": session_id},+ )payload = _show_page_result(page,message=f"Show Page is {page.visibility}.",extra={"history": show_history_status(session_id),- **({"session_default_notice": session_default_notice} if session_default_notice else {}),- },+ },)- if getattr(args, "json", False):- _print_json(payload)- else:- _print_show_page_result(payload)+ _print_json(payload)return 0except Exception as exc:_print_show_page_error(exc)@@ -15260,9 +14686,7 @@ def cmd_show_update(args):store = _load_show_page_store()try:extra: dict = {}- session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show update --help")- if session_default_notice:- extra["session_default_notice"] = session_default_notice+ session_id = _resolve_caller_session_id(args, help_command="vibe show update --help")if getattr(args, "rotate_share", False):updated, previous_share_id = store.rotate_share(session_id)@@ -15312,10 +14736,7 @@ def cmd_show_update(args):context=context.value,)payload = _show_page_result(updated, message=message, extra=extra)- if getattr(args, "json", False):- _print_json(payload)- else:- _print_show_page_result(payload)+ _print_json(payload)return 0except Exception as exc:_print_show_page_error(exc)@@ -15686,16 +15107,8 @@ def _read_event_json_argument(value: str | None, file_path: str | None) -> dict:def _show_mark_target(args) -> str:- positional = (getattr(args, "target", None) or "").strip()- option = (getattr(args, "target_option", None) or "").strip()- if positional and option and positional != option:- raise TaskCliError(- "positional target and --target must match when both are provided",- code="conflicting_mark_targets",- help_command="vibe show mark --help",- )return _read_cli_text_argument(- value=positional or option,+ value=args.target,file_path=None,field_name="target",help_command="vibe show mark --help",@@ -15746,12 +15159,12 @@ def cmd_show_mark(args):page_store = ShowPageStore()event_store = ShowSessionEventStore()try:- session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show mark --help")+ session_id = _resolve_caller_session_id(args, help_command="vibe show mark --help")page = page_store.ensure(session_id)target = _show_mark_target(args)body = _read_cli_text_argument(- value=args.body,- file_path=args.body_file,+ value=args.message,+ file_path=args.message_file,field_name="--message",help_command="vibe show mark --help",)@@ -15784,25 +15197,17 @@ def cmd_show_mark(args):event = _record_show_mark_event(session_id, payload, event_store)result = _show_page_result(page,+ kind="show_mark",message="Assistant mark replaced." if replaced else "Assistant mark recorded.",extra={- **({"session_default_notice": session_default_notice} if session_default_notice else {}),- "event": event,+ "event": event,"event_id": event["id"],"mark_id": mark_id,"message_id": event.get("message_id"),"replaced": replaced,},)- if getattr(args, "json", False):- _print_json(result)- else:- _print_show_page_result(result)- print("")- print("Mark:")- print(f" Event: {event['id']}")- print(f" Message: {event.get('message_id') or 'none'}")- print(f" Target: {target}")+ _print_json(result)return 0except Exception as exc:_print_show_page_error(exc)@@ -15819,7 +15224,7 @@ def cmd_show_reply(args):page_store = ShowPageStore()event_store = ShowSessionEventStore()try:- session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show reply --help")+ session_id = _resolve_caller_session_id(args, help_command="vibe show reply --help")annotation = event_store.get_annotation_event(session_id, args.show_event_id)if annotation is None:recent_ids = event_store.recent_annotation_event_ids(session_id)@@ -15862,10 +15267,10 @@ def cmd_show_reply(args):replacement_notice = "This annotation already had a reply; the active reply was replaced. Run: vibe show marks"result = _show_page_result(page,+ kind="show_reply",message="Show Page reply replaced." if replaced else "Show Page reply recorded.",extra={- **({"session_default_notice": session_default_notice} if session_default_notice else {}),- "event": event,+ "event": event,"event_id": event["id"],"mark_id": mark_id,"reply_to": annotation["id"],@@ -15873,18 +15278,7 @@ def cmd_show_reply(args):**({"replacement_notice": replacement_notice} if replacement_notice else {}),},)- if getattr(args, "json", False):- _print_json(result)- else:- _print_show_page_result(result)- print("")- print("Reply:")- print(f" Event: {event['id']}")- print(f" Mark: {mark_id}")- print(f" Reply to: {annotation['id']}")- print(f" Target: {target}")- if replacement_notice:- print(f" Note: {replacement_notice}")+ _print_json(result)return 0except Exception as exc:_print_show_page_error(exc)@@ -15899,35 +15293,18 @@ def cmd_show_marks(args):event_store = ShowSessionEventStore()try:- session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show marks --help")+ session_id = _resolve_caller_session_id(args, help_command="vibe show marks --help")page_request = _page_request_from_args(args, help_command="vibe show marks --help")marks = [_show_mark_listing(mark) for mark in event_store.active_marks(session_id)]page = page_sequence(marks, page_request)command = ["vibe", "show", "marks", "--session-id", session_id]- if getattr(args, "json", False):- command.append("--json")- result = {- "ok": True,- "session_id": session_id,- "count": len(page.items),- "marks": page.items,+ _print_cli_payload(+ "show_marks",+ session_id=session_id,+ count=len(page.items),+ marks=page.items,**_paginated_fields(page, command=command),- **({"session_default_notice": session_default_notice} if session_default_notice else {}),- }- if getattr(args, "json", False):- _print_json(result)- else:- print(f"Assistant marks ({len(page.items)} shown):")- if not page.items:- print(" none")- for mark in page.items:- print(f"- {mark['id']} {mark['kind']} {mark['read_state']}")- print(f" Target: {mark['target']}")- print(f" Body: {mark['body_head']}")- continuation = _text_page_continuation(result)- if continuation:- print("")- print(continuation)+ )return 0except Exception as exc:_print_show_page_error(exc)@@ -15941,7 +15318,7 @@ def cmd_show_unmark(args):event_store = ShowSessionEventStore()try:- session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show unmark --help")+ session_id = _resolve_caller_session_id(args, help_command="vibe show unmark --help")active_marks = event_store.active_marks(session_id)results = []succeeded = 0@@ -15988,23 +15365,19 @@ def cmd_show_unmark(args):})- result = {- "ok": succeeded > 0,- "session_id": session_id,- "succeeded": succeeded,- "failed": len(results) - succeeded,- "results": results,- **({"session_default_notice": session_default_notice} if session_default_notice else {}),- }- if getattr(args, "json", False):- _print_json(result)- else:- for item in results:- if item["ok"]:- print(f"Resolved {item['input']}: {', '.join(item['mark_ids'])}")- else:- detail = "; ".join(item.get("errors") or []) or item.get("error") or "failed"- print(f"Failed {item['input']}: {detail}", file=sys.stderr)+ _print_json(+ {+ **_cli_payload(+ "show_unmark",+ session_id=session_id,+ succeeded=succeeded,+ failed=len(results) - succeeded,+ results=results,+ ),+ # A partial result is still a result; ``ok`` is false only when nothing resolved.+ "ok": succeeded > 0,+ }+ )return 0 if succeeded > 0 else 1except Exception as exc:_print_show_page_error(exc)@@ -16019,7 +15392,7 @@ def cmd_show_event(args):page_store = ShowPageStore()event_id_for_retry = Nonetry:- session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show event --help")+ session_id = _resolve_caller_session_id(args, help_command="vibe show event --help")page = page_store.ensure(session_id)payload = _read_event_json_argument(args.event_json, args.event_json_file)if args.type:@@ -16044,23 +15417,15 @@ def cmd_show_event(args):event = record_local_show_event(session_id, payload)result = _show_page_result(page,+ kind="show_event",message="Show event recorded.",extra={- **({"session_default_notice": session_default_notice} if session_default_notice else {}),- "event": event,+ "event": event,"event_id": event["id"],"message_id": event.get("message_id"),},)- if getattr(args, "json", False):- _print_json(result)- else:- _print_show_page_result(result)- print("")- print("Event:")- print(f" Event: {event['id']}")- print(f" Type: {event['type']}")- print(f" Message: {event.get('message_id') or 'none'}")+ _print_json(result)return 0except Exception as exc:if event_id_for_retry:@@ -16081,7 +15446,7 @@ def cmd_show_annotate(args):page_store = ShowPageStore()event_store = Nonetry:- session_id, session_default_notice = _resolve_show_session_id(+ session_id = _resolve_caller_session_id(args,help_command="vibe show annotate --help",)@@ -16113,24 +15478,15 @@ def cmd_show_annotate(args):result = _show_page_result(page,+ kind="show_annotation",message="Annotation control recorded.",extra={- **({"session_default_notice": session_default_notice} if session_default_notice else {}),- "event": event,+ "event": event,"event_id": event["id"],"message_id": event.get("message_id"),},)- if getattr(args, "json", False):- _print_json(result)- else:- _print_show_page_result(result)- print("")- print("Annotation:")- print(f" Event: {event['id']}")- print(f" Action: {event['payload']['action']}")- if event["payload"].get("mode"):- print(f" Mode: {event['payload']['mode']}")+ _print_json(result)return 0except Exception as exc:_print_show_page_error(exc)@@ -16180,10 +15536,9 @@ def _doctor_repair_requested(args) -> bool:def _print_doctor_repair_result(result: dict) -> None:- language = _configured_cli_language()- title = i18n_t("doctor.repairTitle", language)+ title = i18n_t("doctor.repairTitle")if result.get("dry_run"):- title += i18n_t("doctor.dryRunSuffix", language)+ title += i18n_t("doctor.dryRunSuffix")print(f"\n {title}")print(" " + "=" * 40)for item in result.get("results", []):@@ -16203,22 +15558,27 @@ def cmd_doctor(args=None):targets = list(getattr(args, "doctor_repair_targets", []) or [])dry_run = bool(getattr(args, "dry_run", False))if not dry_run and not getattr(args, "yes", False) and not _confirm_doctor_repair(targets):- print(i18n_t("doctor.repairNotRun", _configured_cli_language()), file=sys.stderr)+ print(i18n_t("doctor.repairNotRun"), file=sys.stderr)return 2result = _repair_doctor_targets(targets,dry_run=dry_run,deep=bool(getattr(args, "doctor_deep", False)),)- _print_doctor_repair_result(result)+ if getattr(args, "json", False):+ _print_cli_payload("doctor_repair", **result)+ else:+ _print_doctor_repair_result(result)return 0 if result.get("ok") else 1deep = bool(getattr(args, "doctor_deep", False)) if args is not None else Falseresult = _doctor(deep=deep)+ if getattr(args, "json", False):+ _print_cli_payload("doctor_report", **result)+ return 0 if result["ok"] else 1# Terminal-friendly output- language = _configured_cli_language()- print(f"\n {i18n_t('doctor.title', language)}")+ print(f"\n {i18n_t('doctor.title')}")print(" " + "=" * 40)for group in result.get("groups", []):@@ -16240,9 +15600,9 @@ def cmd_doctor(args=None):summary = result.get("summary", {})print("\n " + "-" * 30)print(- f" \033[32m{i18n_t('doctor.summary.passed', language, count=summary.get('pass', 0))}\033[0m "- f"\033[33m{i18n_t('doctor.summary.warnings', language, count=summary.get('warn', 0))}\033[0m "- f"\033[31m{i18n_t('doctor.summary.failed', language, count=summary.get('fail', 0))}\033[0m"+ f" \033[32m{i18n_t('doctor.summary.passed', count=summary.get('pass', 0))}\033[0m "+ f"\033[33m{i18n_t('doctor.summary.warnings', count=summary.get('warn', 0))}\033[0m "+ f"\033[31m{i18n_t('doctor.summary.failed', count=summary.get('fail', 0))}\033[0m")print()@@ -16253,35 +15613,24 @@ def cmd_screenshot(args):try:result = capture_screenshot(getattr(args, "output", None))except ScreenshotError as exc:- payload = {- "ok": False,- "code": "screenshot_failed",- "error": str(exc),- }if getattr(args, "json", False):- print(json.dumps(payload, indent=2), file=sys.stderr)+ _print_task_error(TaskCliError(str(exc), code="screenshot_failed"))else:print(f"Screenshot failed: {exc}", file=sys.stderr)return 1if getattr(args, "json", False):- print(- json.dumps(- {- "ok": True,- "path": str(result.path),- "backend": result.backend,- },- indent=2,- )- )+ _print_cli_payload("screenshot", path=str(result.path), backend=result.backend)else:print(str(result.path))return 0-def cmd_version():+def cmd_version(args=None):"""Show current version."""+ if getattr(args, "json", False):+ _print_cli_payload("version", version=__version__)+ return 0print(f"avibe-os {__version__}")return 0@@ -16295,11 +15644,27 @@ def get_latest_version() -> dict:return get_latest_version_info(__version__)-def cmd_check_update():+def cmd_check_update(args=None):"""Check for available updates."""+ if getattr(args, "json", False):+ if is_desktop_managed_runtime():+ _print_cli_payload("update_check", current=__version__, desktop_managed=True)+ return 0+ info = get_latest_version()+ if info["error"]:+ _print_task_error(+ TaskCliError(+ f"Failed to check for updates: {info['error']}",+ code="update_check_failed",+ details={"current": info.get("current") or __version__},+ )+ )+ return 1+ _print_cli_payload("update_check", **info, desktop_managed=False)+ return 0print(f"Current version: {__version__}")if is_desktop_managed_runtime():- print(i18n_t("desktopRuntime.checkUpdate", V2Config.load().language))+ print("Updates are delivered with the Avibe desktop app.")return 0print("Checking for updates...")@@ -16322,7 +15687,7 @@ def cmd_upgrade():"""Upgrade avibe-os to the latest version."""print(f"Current version: {__version__}")if is_desktop_managed_runtime():- print(i18n_t("desktopRuntime.upgrade", V2Config.load().language))+ print("This Runtime is managed by the Avibe desktop app. Update the app to update Avibe.")return 0print("Checking for updates...")@@ -16573,7 +15938,7 @@ def cmd_runtime(args) -> int:payload = manager.status()payload["git"] = _git_runtime_status()if getattr(args, "json", False):- print(json.dumps(payload, indent=2))+ _print_cli_payload("runtime_status", **payload)else:_print_runtime_status(payload)return 0@@ -16602,35 +15967,27 @@ def cmd_runtime(args) -> int:policy = payload.get("policy") if isinstance(payload.get("policy"), dict) else {}runtime_prepared = bool(payload.get("ok"))if getattr(args, "json", False):- print(json.dumps(payload, indent=2))+ _print_cli_payload("runtime_prepare", **payload)else:- language = _configured_cli_language()if runtime_prepared:- print(i18n_t("runtime.prepare.prepared", language))+ print(i18n_t("runtime.prepare.prepared"))status = payload.get("status") or {}status_install = _show_runtime_install(status)if status_install.get("install_dir"):print(f"Install dir: {status_install['install_dir']}")elif policy.get("state") == "skipped":print(- i18n_t(- "runtime.prepare.skipped",- language,- reason=policy.get("reason") or "unknown",- ),+ "Show Runtime preparation skipped: {reason}".format(reason=policy.get("reason") or "unknown"),file=sys.stderr,)else:reason = payload.get("reason") or install.get("reason") or "unknown"print(- i18n_t(- (- "runtime.prepare.unsupportedSource"- if reason == "runtime_source_unsupported"- else "runtime.prepare.failed"- ),- language,- reason=reason,+ (+ f"Show Runtime preparation failed: {reason}. Remove VIBE_SHOW_RUNTIME_SOURCE and use the "+ "packaged runtime, or set VIBE_SHOW_RUNTIME_BIN to a runtime you built."+ if reason == "runtime_source_unsupported"+ else f"Show Runtime preparation failed: {reason}"),file=sys.stderr,)@@ -16648,34 +16005,19 @@ def cmd_runtime(args) -> int:print(f"avault not ready: {avault.get('message') or 'install failed'}", file=sys.stderr)if model_hub_engine.get("skipped"):print(- i18n_t(- "runtime.prepare.modelHubEngineSkipped",- language,- reason=model_hub_engine.get("reason") or "skipped",- )+ "Model Hub engine: skipped ({reason}).".format(reason=model_hub_engine.get("reason") or "skipped"))elif model_hub_engine.get("ok"):print(- i18n_t(- (- "runtime.prepare.modelHubEngineInstalled"- if model_hub_engine.get("changed")- else "runtime.prepare.modelHubEngineReady"- ),- language,- )+ "Model Hub engine installed."+ if model_hub_engine.get("changed")+ else "Model Hub engine ready.")else:print(- i18n_t(- "runtime.prepare.modelHubEngineNotReady",- language,- reason=(- model_hub_engine.get("message")+ "Model Hub engine not ready: {reason}".format(reason=model_hub_engine.get("message")or model_hub_engine.get("reason")- or "install failed"- ),- ),+ or "install failed"),file=sys.stderr,)if tmux.get("skipped") or tmux.get("status") == "skipped":@@ -16695,40 +16037,22 @@ def cmd_runtime(args) -> int:)if ripgrep.get("ok"):print(- i18n_t(- "runtime.prepare.ripgrepInstalled" if ripgrep.get("changed") else "runtime.prepare.ripgrepReady",- language,- )+ "ripgrep installed." if ripgrep.get("changed") else "ripgrep ready.")else:print(- i18n_t(- "runtime.prepare.ripgrepNotReady",- language,- reason=ripgrep.get("message") or ripgrep.get("reason") or "install failed",- ),+ "ripgrep not ready: {reason}".format(reason=ripgrep.get("message") or ripgrep.get("reason") or "install failed"),file=sys.stderr,)if cloudflared.get("skipped"):passelif cloudflared.get("ok"):print(- i18n_t(- (- "runtime.prepare.cloudflaredInstalled"- if cloudflared.get("changed")- else "runtime.prepare.cloudflaredReady"- ),- language,- )+ "cloudflared installed." if cloudflared.get("changed") else "cloudflared ready.")else:print(- i18n_t(- "runtime.prepare.cloudflaredNotReady",- language,- reason=cloudflared.get("message") or cloudflared.get("reason") or "install failed",- ),+ "cloudflared not ready: {reason}".format(reason=cloudflared.get("message") or cloudflared.get("reason") or "install failed"),file=sys.stderr,)strict_ok = runtime_prepared and _git_prepare_satisfies_strict(git)@@ -16751,9 +16075,8 @@ def cmd_runtime(args) -> int:for runtime_id, result in managed_runtimes.items()}if getattr(args, "json", False):- print(json.dumps(payload, indent=2))+ _print_cli_payload("runtime_clean", **payload)else:- language = _configured_cli_language()archives_value = payload.get("archives")archives = archives_value if isinstance(archives_value, Mapping) else {}skipped_reason = str(archives.get("skipped_reason") or "")@@ -16761,28 +16084,22 @@ def cmd_runtime(args) -> int:# Consumer results are reported independently of the Show archive# outcome: a skipped archive pass must not hide what the rest of# the cleanup actually reclaimed (or would reclaim).- prefix_key = "runtime.clean.wouldRemove" if dry_run else "runtime.clean.removed"+ verb = "Would remove" if dry_run else "Removed"removed = payload.get("removed") or []- print(i18n_t(f"{prefix_key}Items", language, count=len(removed)))+ print(f"{verb} {len(removed)} Show Runtime cache item(s).")if show_verdict.failed:_print_runtime_clean_failure(consumer="Show Runtime",reason=show_verdict.reason,dry_run=dry_run,- language=language,)is_partial_run = outcome == "partial" and not dry_runif is_partial_run:print(- i18n_t(- "runtime.clean.removedArchives",- language,- count=int(archives.get("removed_count") or 0),- size=_format_byte_size(int(archives.get("removed_bytes") or 0)),- )+ "Removed {count} downloaded Show Runtime archive(s) ({size}).".format(count=int(archives.get("removed_count") or 0), size=_format_byte_size(int(archives.get("removed_bytes") or 0))))print(- i18n_t("runtime.clean.partiallyRemoved", language, failed=int(archives.get("failed_count") or 0)),+ " {failed} archive(s) could not be removed; check permissions and the Avibe log.".format(failed=int(archives.get("failed_count") or 0)),file=sys.stderr,)elif skipped_reason:@@ -16791,37 +16108,29 @@ def cmd_runtime(args) -> int:# remediation that matches the actual reason.if skipped_reason == "archive_removal_failed":print(- i18n_t(- "runtime.clean.removalFailed",- language,- failed=int(archives.get("failed_count") or 0),- ),+ "{failed} archive(s) could not be removed; stale archives remain. Check runtime directory permissions and the Avibe log.".format(failed=int(archives.get("failed_count") or 0)),file=sys.stderr,)else:- skip_key = (- "runtime.clean.skippedInspection"+ message = (+ f"Archive cleanup could not inspect the cache ({skipped_reason}); stale archives may remain. "+ "Check runtime directory permissions and the Avibe log."if skipped_reason == "archive_inspection_failed"- else "runtime.clean.skipped"+ else f"Archive cleanup skipped ({skipped_reason}); stale archives may remain. "+ "Try again after the running install or cleanup finishes.")- print(i18n_t(skip_key, language, reason=skipped_reason), file=sys.stderr)+ print(message, file=sys.stderr)elif not show_verdict.archives_failed and (archives or not show_verdict.failed):archive_count = int(archives.get("candidate_count") or 0) if dry_run else int(archives.get("removed_count") or 0)archive_bytes = int(archives.get("candidate_bytes") or 0) if dry_run else int(archives.get("removed_bytes") or 0)print(- i18n_t(- f"{prefix_key}Archives",- language,- count=archive_count,- size=_format_byte_size(archive_bytes),- )+ f"{verb} {archive_count} downloaded Show Runtime archive(s) ({_format_byte_size(archive_bytes)}).")for runtime_id, result in managed_runtimes.items():_print_managed_runtime_clean_result(runtime_id=runtime_id,result=result,dry_run=dry_run,- language=language,verdict=managed_verdicts[runtime_id],)failed = show_verdict.failed or any(verdict.failed for verdict in managed_verdicts.values())@@ -17086,16 +16395,12 @@ def _print_runtime_clean_failure(consumer: str,reason: str | None,dry_run: bool,- language: str,) -> None:- key = "runtime.clean.consumerPreviewFailed" if dry_run else "runtime.clean.consumerFailed"+ reason = reason or "unknown"print(- i18n_t(- key,- language,- consumer=consumer,- reason=reason or "unknown",- ),+ f"{consumer} cache preview failed ({reason}); stale entries may remain."+ if dry_run+ else f"{consumer} cleanup failed ({reason}); stale entries remain.",file=sys.stderr,)@@ -17105,21 +16410,19 @@ def _print_managed_runtime_clean_result(runtime_id: str,result: Mapping[str, Any],dry_run: bool,- language: str,verdict: _RuntimeCleanVerdict,) -> None:consumer = _managed_runtime_label(runtime_id)- prefix_key = "runtime.clean.consumerWouldRemove" if dry_run else "runtime.clean.consumerRemoved"+ verb = "Would remove" if dry_run else "Removed"removed = result.get("removed")removed_count = len(removed) if isinstance(removed, list) else 0- print(i18n_t(f"{prefix_key}Items", language, consumer=consumer, count=removed_count))+ print(f"{verb} {removed_count} {consumer} cache item(s).")if verdict.failed:_print_runtime_clean_failure(consumer=consumer,reason=verdict.reason,dry_run=dry_run,- language=language,)archives_value = result.get("archives")@@ -17130,33 +16433,16 @@ def _print_managed_runtime_clean_result(outcome = str(archives.get("outcome") or "")if outcome == "partial" and not dry_run:print(- i18n_t(- "runtime.clean.consumerRemovedArchives",- language,- consumer=consumer,- count=int(archives.get("removed_count") or 0),- size=_format_byte_size(int(archives.get("removed_bytes") or 0)),- )+ "Removed {count} downloaded {consumer} archive(s) ({size}).".format(consumer=consumer, count=int(archives.get("removed_count") or 0), size=_format_byte_size(int(archives.get("removed_bytes") or 0))))print(- i18n_t(- "runtime.clean.consumerArchivesPartial",- language,- consumer=consumer,- reason=skipped_reason or "archive_removal_failed",- failed=int(archives.get("failed_count") or 0),- ),+ "{consumer} archive cleanup was partial ({reason}); {failed} archive(s) could not be removed.".format(consumer=consumer, reason=skipped_reason or "archive_removal_failed", failed=int(archives.get("failed_count") or 0)),file=sys.stderr,)returnif skipped_reason:print(- i18n_t(- "runtime.clean.consumerArchivesSkipped",- language,- consumer=consumer,- reason=skipped_reason,- ),+ f"{consumer} archive cleanup skipped ({skipped_reason}); stale archives may remain.",file=sys.stderr,)return@@ -17164,15 +16450,9 @@ def _print_managed_runtime_clean_result(returncount_key = "candidate_count" if dry_run else "removed_count"bytes_key = "candidate_bytes" if dry_run else "removed_bytes"- print(- i18n_t(- f"{prefix_key}Archives",- language,- consumer=consumer,- count=int(archives.get(count_key) or 0),- size=_format_byte_size(int(archives.get(bytes_key) or 0)),- )- )+ count = int(archives.get(count_key) or 0)+ size = _format_byte_size(int(archives.get(bytes_key) or 0))+ print(f"{verb} {count} downloaded {consumer} archive(s) ({size}).")def _clean_git_runtime(*, keep_previous: int, dry_run: bool = False) -> dict:@@ -17266,13 +16546,13 @@ def _generation_downgrade_blocks(command: str | None, *, allow_downgrade: bool =return Falsesupervised = command is None or is_desktop_managed_runtime()if supervised:- key = "update.downgradeWarning"+ template = "Warning: this vibe runs Avibe {version} ({generation}), older than the last activated install {activatedVersion} ({activatedGeneration}). Use `{launcher}`, or run `{repairCommand}` to move every launcher to it."+ elif allow_downgrade:+ template = "Warning: running Avibe {version} ({generation}), older than the last activated install {activatedVersion} ({activatedGeneration}), because --allow-downgrade was given."else:- key = "update.downgradeAllowed" if allow_downgrade else "update.downgradeRefused"+ template = "Refusing to {command} from Avibe {version} ({generation}): the last activated install is {activatedVersion} ({activatedGeneration}). Run `{rerunCommand}` instead, or pass --allow-downgrade to run the older build on purpose."print(- i18n_t(- key,- _configured_cli_language(),+ template.format(command=command or "",version=downgrade.version,generation=downgrade.generation,@@ -17289,7 +16569,7 @@ def _generation_downgrade_blocks(command: str | None, *, allow_downgrade: bool =def _cmd_restart_with_delay(delay_seconds: float) -> int:# Checked again by the restart job, which acts on whatever runs by then.- if _desktop_provenance_refused("desktopRuntime.restartRefused"):+ if _desktop_provenance_refused("restart"):return 3if delay_seconds > 0:return _schedule_delayed_restart(delay_seconds)@@ -17325,11 +16605,12 @@ def build_parser():help="Start this install even though a newer one was activated since.",)start_parser.add_argument("--hand-over", action="store_true", help=argparse.SUPPRESS)- desktop_parser = subparsers.add_parser("desktop", help=argparse.SUPPRESS)+ # The desktop shell's own entry points: runnable, but never listed.+ desktop_parser = subparsers.add_parser("desktop")desktop_subparsers = desktop_parser.add_subparsers(dest="desktop_command", required=True)- desktop_endpoint_parser = desktop_subparsers.add_parser("endpoint", help=argparse.SUPPRESS)+ desktop_endpoint_parser = desktop_subparsers.add_parser("endpoint")desktop_endpoint_parser.add_argument("--json", action="store_true", required=True, help=argparse.SUPPRESS)- desktop_subparsers.add_parser("remove-backends", help=argparse.SUPPRESS)+ desktop_subparsers.add_parser("remove-backends")restart_parser = subparsers.add_parser("restart", help="Restart all services")restart_parser.add_argument("--delay-seconds",@@ -17347,7 +16628,8 @@ def build_parser():# builds and the parser that reads it back. Restating those flags here made# this parser a second, silently authoritative owner -- and the one that runs# first. See `_dispatch_restart_supervisor`.- subparsers.add_parser("status", help="Show service status")+ status_parser = subparsers.add_parser("status", help="Show service status")+ _add_json_noop(status_parser)doctor_parser = subparsers.add_parser("doctor",help="Run diagnostics and optional safe repairs",@@ -17382,13 +16664,15 @@ def build_parser():doctor_parser.add_argument("--fix", action="store_true", help="Alias for 'vibe doctor repair'.")doctor_parser.add_argument("--dry-run", action="store_true", help="Show repair actions without changing state.")doctor_parser.add_argument("-y", "--yes", action="store_true", help="Confirm repair actions non-interactively.")- subparsers.add_parser("version", help="Show version")- subparsers.add_parser("check-update", help="Check for updates")+ _add_json_flag(doctor_parser)+ version_parser = subparsers.add_parser("version", help="Show version")+ _add_json_flag(version_parser)+ check_update_parser = subparsers.add_parser("check-update", help="Check for updates")+ _add_json_flag(check_update_parser)subparsers.add_parser("upgrade", help="Upgrade to latest version")- skill_help_language = _configured_cli_language()skill_parser = subparsers.add_parser("skill",- help=i18n_t("skill.cli.help.command", skill_help_language),+ help="List and load Skills through Avibe",)skill_subparsers = skill_parser.add_subparsers(dest="skill_command",@@ -17397,33 +16681,31 @@ def build_parser():skill_subparsers.required = Trueskill_list_parser = skill_subparsers.add_parser("list",- help=i18n_t("skill.cli.help.list", skill_help_language),+ help="List available Skills",)skill_list_parser.add_argument("--page",type=int,default=1,- help=i18n_t("skill.cli.help.page", skill_help_language),+ help="Catalog page (default: 1)",)+ _add_json_noop(skill_list_parser)skill_load_parser = skill_subparsers.add_parser("load",- help=i18n_t("skill.cli.help.load", skill_help_language),+ help="Load one or more Skills, printing each in the order given",)skill_load_parser.add_argument(- "name",- help=i18n_t("skill.cli.help.name", skill_help_language),+ "names",+ nargs="+",+ metavar="name",+ help="Skill name. Pass several to load them in one call.",)- computer_help_language = _configured_cli_language()computer_parser = subparsers.add_parser("computer",- help=i18n_t("computer.cli.help.command", computer_help_language),- description=i18n_t("computer.cli.help.description", computer_help_language),+ help="Use the local desktop through the active Avibe Agent Turn",+ description="Run an allowlisted Computer Use operation through the Avibe service. The caller Session is taken from the Agent environment and the service checks that it has an active Turn.",error_help_command="vibe computer --help",- error_hint=i18n_t(- "computer.cli.hint.invalidArguments",- computer_help_language,- ),- error_i18n_key="computer.cli.error.invalidArguments",+ error_hint="Check the command syntax and run `vibe computer --help` for the Computer Use contract.",)computer_subparsers = computer_parser.add_subparsers(dest="computer_command",@@ -17433,95 +16715,79 @@ def build_parser():computer_run_parser = computer_subparsers.add_parser("run",- help=i18n_t("computer.cli.help.run", computer_help_language),- description=i18n_t(- "computer.cli.help.runDescription",- computer_help_language,- ),+ help="Run a JavaScript Computer Use script",+ description="Run an ESM file with the shipped @avibe/computer module, bound to this exact Avibe Agent Turn.",error_help_command="vibe computer run --help",- error_hint=i18n_t("computer.cli.hint.invalidArguments", computer_help_language),- error_i18n_key="computer.cli.error.invalidArguments",+ error_hint="Check the command syntax and run `vibe computer --help` for the Computer Use contract.",)computer_run_parser.add_argument("file",- help=i18n_t("computer.cli.help.scriptFile", computer_help_language),+ help="Path to a readable .mjs script.",)computer_run_parser.add_argument("--arg",action="append",default=[],metavar="NAME=VALUE",- help=i18n_t("computer.cli.help.scriptArg", computer_help_language),+ help="Pass one script argument as name=value or name=@file. Values remain strings.",)+ _add_json_noop(computer_run_parser)computer_js_parser = computer_subparsers.add_parser("js",- help=i18n_t("computer.cli.help.js", computer_help_language),- description=i18n_t("computer.cli.help.jsDescription", computer_help_language),+ help="Evaluate JavaScript in this Session's persistent Computer Use kernel",+ description="Evaluate code in a Node kernel that keeps top-level bindings between calls in this Avibe Session. computer and avibe are preloaded; top-level await is supported. Each call is bound to the current Agent Turn.",error_help_command="vibe computer js --help",- error_hint=i18n_t("computer.cli.hint.invalidArguments", computer_help_language),- error_i18n_key="computer.cli.error.invalidArguments",+ error_hint="Check the command syntax and run `vibe computer --help` for the Computer Use contract.",)computer_js_parser.add_argument("--code",required=True,- help=i18n_t("computer.cli.help.jsCode", computer_help_language),+ help="JavaScript source, or @FILE to read it from a UTF-8 file.",)computer_js_parser.add_argument("--timeout-ms",type=int,default=30000,- help=i18n_t("computer.cli.help.jsTimeout", computer_help_language),+ help="Per-call timeout in milliseconds (default 30000, max 300000).",)- computer_subparsers.add_parser(+ _add_json_noop(computer_js_parser)+ computer_js_reset_parser = computer_subparsers.add_parser("js-reset",- help=i18n_t("computer.cli.help.jsReset", computer_help_language),- description=i18n_t("computer.cli.help.jsReset", computer_help_language),+ help="Discard this Session's JavaScript kernel and all of its bindings; open apps are untouched",+ description="Discard this Session's JavaScript kernel and all of its bindings; open apps are untouched",error_help_command="vibe computer js-reset --help",- error_hint=i18n_t("computer.cli.hint.invalidArguments", computer_help_language),- error_i18n_key="computer.cli.error.invalidArguments",+ error_hint="Check the command syntax and run `vibe computer --help` for the Computer Use contract.",)+ _add_json_noop(computer_js_reset_parser)def _add_computer_options(command_parser) -> None:command_parser.add_argument("--args-json",- help=i18n_t(- "computer.cli.help.argsJson",- computer_help_language,- ),+ help="JSON object of driver arguments, or @path to a JSON file.",)command_parser.add_argument("--arg",action="append",default=[],metavar="NAME=VALUE",- help=i18n_t(- "computer.cli.help.arg",- computer_help_language,- ),+ help="Override one driver argument; JSON values are parsed when valid.",)command_parser.add_argument("--output",- help=i18n_t(- "computer.cli.help.output",- computer_help_language,- ),+ help="Caller-selected screenshot path for 'observe window'.",)command_parser.add_argument("--json",action="store_true",- help=i18n_t(- "computer.cli.help.json",- computer_help_language,- ),+ help="Print the structured service response.",)computer_observe_parser = computer_subparsers.add_parser("observe",- help=i18n_t("computer.cli.help.observe", computer_help_language),+ help="Observe apps, windows, or one exact window",error_help_command="vibe computer observe --help",- error_hint=i18n_t("computer.cli.hint.invalidArguments", computer_help_language),- error_i18n_key="computer.cli.error.invalidArguments",+ error_hint="Check the command syntax and run `vibe computer --help` for the Computer Use contract.",)computer_observe_subparsers = computer_observe_parser.add_subparsers(dest="computer_observe_command",@@ -17531,53 +16797,50 @@ def build_parser():for name, help_text in (("apps",- i18n_t("computer.cli.help.observeApps", computer_help_language),+ "List visible applications",),("windows",- i18n_t("computer.cli.help.observeWindows", computer_help_language),+ "List windows",),("window",- i18n_t("computer.cli.help.observeWindow", computer_help_language),+ "Observe one exact window and optionally save a screenshot",),):leaf = computer_observe_subparsers.add_parser(name,help=help_text,error_help_command=f"vibe computer observe {name} --help",- error_hint=i18n_t("computer.cli.hint.invalidArguments", computer_help_language),- error_i18n_key="computer.cli.error.invalidArguments",+ error_hint="Check the command syntax and run `vibe computer --help` for the Computer Use contract.",)_add_computer_options(leaf)for name, help_text in (- ("zoom", "zoom"),- ("click", "click"),- ("type", "type"),- ("key", "key"),- ("hotkey", "hotkey"),- ("scroll", "scroll"),- ("drag", "drag"),- ("set-value", "setValue"),- ("launch", "launch"),- ("force-quit", "forceQuit"),+ ("zoom", "Inspect one exact window at a readable scale"),+ ("click", "Click an observed element or exact window coordinate"),+ ("type", "Type text into an observed target"),+ ("key", "Press one key"),+ ("hotkey", "Press a key combination"),+ ("scroll", "Scroll an observed target"),+ ("drag", "Drag an observed target"),+ ("set-value", "Set an observed control value"),+ ("launch", "Launch an application or URL"),+ ("force-quit", "Force-terminate an application; unsaved state is lost."),):leaf = computer_subparsers.add_parser(name,- help=i18n_t(f"computer.cli.help.{help_text}", computer_help_language),+ help=help_text,error_help_command=f"vibe computer {name} --help",- error_hint=i18n_t("computer.cli.hint.invalidArguments", computer_help_language),- error_i18n_key="computer.cli.error.invalidArguments",+ error_hint="Check the command syntax and run `vibe computer --help` for the Computer Use contract.",)_add_computer_options(leaf)computer_clipboard_parser = computer_subparsers.add_parser("clipboard",- help=i18n_t("computer.cli.help.clipboard", computer_help_language),+ help="Read or write the system clipboard",error_help_command="vibe computer clipboard --help",- error_hint=i18n_t("computer.cli.hint.invalidArguments", computer_help_language),- error_i18n_key="computer.cli.error.invalidArguments",+ error_hint="Check the command syntax and run `vibe computer --help` for the Computer Use contract.",)computer_clipboard_subparsers = computer_clipboard_parser.add_subparsers(dest="computer_clipboard_command",@@ -17587,32 +16850,30 @@ def build_parser():for name, help_text in (("read",- i18n_t("computer.cli.help.clipboardRead", computer_help_language),+ "Read the system clipboard",),("write",- i18n_t("computer.cli.help.clipboardWrite", computer_help_language),+ "Write the system clipboard",),):leaf = computer_clipboard_subparsers.add_parser(name,help=help_text,error_help_command=f"vibe computer clipboard {name} --help",- error_hint=i18n_t("computer.cli.hint.invalidArguments", computer_help_language),- error_i18n_key="computer.cli.error.invalidArguments",+ error_hint="Check the command syntax and run `vibe computer --help` for the Computer Use contract.",)_add_computer_options(leaf)- debug_help_language = _configured_cli_language()debug_parser = subparsers.add_parser("debug",- help=i18n_t("debug.cli.help.command", debug_help_language),+ help="Inspect internal Avibe state",)debug_subparsers = debug_parser.add_subparsers(dest="debug_command", metavar="{prompt}")debug_subparsers.required = Truedebug_prompt_parser = debug_subparsers.add_parser("prompt",- help=i18n_t("debug.cli.help.prompt", debug_help_language),+ help="Inspect authored prompt sources",)debug_prompt_subparsers = debug_prompt_parser.add_subparsers(dest="prompt_debug_command",@@ -17621,18 +16882,19 @@ def build_parser():debug_prompt_subparsers.required = Truedebug_prompt_export_parser = debug_prompt_subparsers.add_parser("export",- help=i18n_t("debug.cli.help.promptExport", debug_help_language),+ help="Export all prompt sources, optionally with the production rendering",)debug_prompt_export_parser.add_argument("--context-file",- help=i18n_t("debug.cli.help.promptContext", debug_help_language),+ help="JSON file with backend, optional agent_instructions and production builder options",)debug_prompt_export_parser.add_argument("--format",choices=("json",),default="json",- help=i18n_t("debug.cli.help.promptFormat", debug_help_language),+ help="Export format",)+ _add_json_noop(debug_prompt_export_parser)runtime_parser = subparsers.add_parser("runtime",help="Inspect and prepare managed runtimes",@@ -17656,7 +16918,7 @@ def build_parser():runtime_status_parser = runtime_subparsers.add_parser("status", help="Show managed runtime status")add_runtime_provider_args(runtime_status_parser)runtime_status_parser.add_argument("--offline", action="store_true", help="Do not fetch a remote manifest.")- runtime_status_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_flag(runtime_status_parser)runtime_prepare_parser = runtime_subparsers.add_parser("prepare",@@ -17666,10 +16928,9 @@ def build_parser():runtime_prepare_parser.add_argument("--force", action="store_true", help="Reinstall even when the cached runtime matches.")runtime_prepare_parser.add_argument("--offline", action="store_true", help="Use only the verified local cache.")runtime_prepare_parser.add_argument("--strict", action="store_true", help="Return a non-zero exit code when preparation fails.")- runtime_prepare_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_flag(runtime_prepare_parser)- runtime_clean_language = _configured_cli_language()- runtime_clean_help = i18n_t("runtime.clean.commandHelp", runtime_clean_language)+ runtime_clean_help = "Remove stale Show, Git, Model Hub, tmux, ripgrep, and cloudflared runtime installs and archives; exit nonzero if any cleanup fails."runtime_clean_parser = runtime_subparsers.add_parser("clean",help=runtime_clean_help,@@ -17679,9 +16940,9 @@ def build_parser():runtime_clean_parser.add_argument("--dry-run",action="store_true",- help=i18n_t("runtime.clean.dryRunHelp", runtime_clean_language),+ help="Report stale archives and cache entries without removing anything.",)- runtime_clean_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_flag(runtime_clean_parser)remote_parser = subparsers.add_parser("remote",help="Manage Avibe Cloud remote access",@@ -17723,7 +16984,7 @@ def build_parser():remote_pair_parser.add_argument("--json",action="store_true",- help="Print the raw machine-readable pairing result.",+ help="Print the pairing result as the JSON envelope.",)remote_status_parser = remote_subparsers.add_parser(@@ -17733,7 +16994,7 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe remote status --help",)- remote_status_parser.add_argument("--json", action="store_true", help="Print the raw machine-readable status.")+ _add_json_flag(remote_status_parser)remote_start_parser = remote_subparsers.add_parser("start",@@ -17742,7 +17003,7 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe remote start --help",)- remote_start_parser.add_argument("--json", action="store_true", help="Print the raw machine-readable result.")+ _add_json_flag(remote_start_parser)remote_stop_parser = remote_subparsers.add_parser("stop",@@ -17751,7 +17012,7 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe remote stop --help",)- remote_stop_parser.add_argument("--json", action="store_true", help="Print the raw machine-readable result.")+ _add_json_flag(remote_stop_parser)screenshot_parser = subparsers.add_parser("screenshot",@@ -17835,7 +17096,6 @@ def build_parser():agent_create_parser.add_argument("--description")agent_create_parser.add_argument("--model")agent_create_parser.add_argument("--reasoning-effort")- agent_create_parser.add_argument("--effort", dest="reasoning_effort", help=argparse.SUPPRESS)system_prompt_group = agent_create_parser.add_mutually_exclusive_group()system_prompt_group.add_argument("--system-prompt")system_prompt_group.add_argument("--system-prompt-file")@@ -17850,7 +17110,6 @@ def build_parser():agent_update_parser.add_argument("--model")agent_update_parser.add_argument("--clear-model", action="store_true")agent_update_parser.add_argument("--reasoning-effort")- agent_update_parser.add_argument("--effort", dest="reasoning_effort", help=argparse.SUPPRESS)agent_update_parser.add_argument("--clear-reasoning-effort", action="store_true")update_prompt_group = agent_update_parser.add_mutually_exclusive_group()update_prompt_group.add_argument("--system-prompt")@@ -17893,43 +17152,27 @@ def build_parser():)agent_run_parser.add_argument("--agent", help="Avibe Agent name")agent_run_parser.add_argument("--session-id", help="Existing Agent Session ID to continue")- agent_run_delivery_group = agent_run_parser.add_mutually_exclusive_group()- agent_run_delivery_group.add_argument(- "--send-now",- action="store_true",- help="Explicitly deliver this Run as P1 to an existing Session (the default behavior)",- )- agent_run_delivery_group.add_argument(+ agent_run_parser.add_argument("--queue",action="store_true",help="Queue this Run behind the active Turn instead of steering it",)agent_run_parser.add_argument("--fork-session", help="Existing Agent Session ID to fork into a new Session")agent_run_parser.add_argument("--fork-self", action="store_true", help="Fork this current Agent Session")- agent_run_parser.add_argument("--create-session", action="store_true", help="Create a new Avibe Session ID before running")- agent_run_parser.add_argument("--create-session-per-run", action="store_true", help=argparse.SUPPRESS)agent_run_parser.add_argument("--same-scope", action="store_true", help="Place a new or forked Session in the caller/source Session scope")agent_run_parser.add_argument("--scope-id", help="Existing scopes.id that should own the new or forked Session")- agent_visibility_group = agent_run_parser.add_mutually_exclusive_group()- agent_visibility_group.add_argument(- "--visibility",- choices=("foreground", "background"),- help="Visibility for the new or forked Session (default: background)",- )- agent_visibility_group.add_argument(+ agent_run_parser.add_argument("--visible",dest="visibility",action="store_const",const="foreground",- help="Make the new or forked Session user-facing from the start",+ help="Make the new or forked Session user-facing from the start (default: background)",)- agent_run_parser.add_argument("--deliver-key", help=argparse.SUPPRESS)- agent_run_help_language = _configured_cli_language()agent_run_parser.add_argument(- "--model", help=i18n_t("harness.cli.agentRunModel.helpModel", agent_run_help_language)+ "--model", help="Model for the new Session this run creates (a blank new Session or a fork); kept on that Session for its later turns. Not valid with --session-id. See `vibe agent models <agent>`.")agent_run_parser.add_argument(- "--reasoning-effort", help=i18n_t("harness.cli.agentRunModel.helpEffort", agent_run_help_language)+ "--reasoning-effort", help="Reasoning effort for the new Session this run creates; kept on that Session. Not valid with --session-id.")agent_run_parser.add_argument("--cwd",@@ -17939,7 +17182,6 @@ def build_parser():"(an existing session keeps its own working directory)."),)- agent_run_parser.add_argument("--post-to", choices=("thread", "channel"), help=argparse.SUPPRESS)agent_run_parser.add_argument("--callback-session-id", help="Caller Session ID to receive the completed async run result")agent_run_parser.add_argument("--no-callback",@@ -17951,20 +17193,11 @@ def build_parser():action="store_true",help="Close the newly-created Agent runtime after the run settles while keeping its Session and transcript.",)- agent_wait_group = agent_run_parser.add_mutually_exclusive_group()- agent_wait_group.add_argument(- "--async",- dest="async_run",- action="store_true",- help="Queue the run and return immediately (default; kept for compatibility)",- )- agent_wait_group.add_argument("--sync", dest="sync_run", action="store_true", help="Wait for the run result before exiting")+ agent_run_parser.add_argument("--sync", dest="sync_run", action="store_true", help="Wait for the run result before exiting")agent_run_parser.add_argument("--wait-timeout", type=float, help="Maximum seconds the CLI waits for a synchronous run result")agent_message_group = agent_run_parser.add_mutually_exclusive_group(required=True)agent_message_group.add_argument("--message")agent_message_group.add_argument("--message-file")- agent_message_group.add_argument("--prompt", help=argparse.SUPPRESS)- agent_message_group.add_argument("--prompt-file", help=argparse.SUPPRESS)_add_json_noop(agent_run_parser)runs_parser = subparsers.add_parser(@@ -18002,16 +17235,15 @@ def build_parser():_add_json_noop(runs_show_parser)runs_cancel_parser = runs_subparsers.add_parser("cancel",- help=i18n_t("harness.run.cli.help.cancel", _configured_cli_language()),+ help="Request best-effort cancellation for one run; a run already in the live Session turn stops that whole turn, like Session Stop",)runs_cancel_parser.add_argument("run_id")_add_json_noop(runs_cancel_parser)- harness_help_language = _configured_cli_language()harness_parser = subparsers.add_parser("harness",- help=i18n_t("harness.cli.help.command", harness_help_language),- description=i18n_t("harness.cli.help.description", harness_help_language),+ help="Inspect unified Harness live state and anomalies",+ description="Inspect active Runs, armed Watches, upcoming Tasks, and live anomalies.",error_help_command="vibe harness --help",)harness_subparsers = harness_parser.add_subparsers(@@ -18021,8 +17253,8 @@ def build_parser():harness_subparsers.required = Trueharness_status_parser = harness_subparsers.add_parser("status",- help=i18n_t("harness.cli.help.status", harness_help_language),- description=i18n_t("harness.cli.help.statusDescription", harness_help_language),+ help="Show the bounded live/anomaly snapshot",+ description="Show live Runs, armed Watches, upcoming Tasks, and anomalies for the caller Session. Use --session-id for another Session or --global for every Session.",error_help_command="vibe harness status --help",)_add_session_scope_args(harness_status_parser, items="Harness work")@@ -18034,8 +17266,9 @@ def build_parser():description=("Manage Avibe Agent sessions. 'list' and 'get' are read-only views; ""'send-now' promotes the exact queued head, steering it when active; "- "'update' changes title, visibility, or scope. Archived sessions are "- "soft-deleted and never surfaced."+ "'update' changes title, visibility, or scope. Commands that act on one "+ "Session take --session-id and default to the caller Session. Archived "+ "sessions are soft-deleted and never surfaced."),formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe session --help",@@ -18065,11 +17298,14 @@ def build_parser():session_get_parser = session_subparsers.add_parser("get",help="Show one session's full detail by ID",- description="Show full detail for one active session. An archived or missing ID is reported as not found.",+ description=(+ "Show full detail for one active session: the caller Session by default, or --session-id. "+ "An archived or missing ID is reported as not found."+ ),formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe session get --help",)- session_get_parser.add_argument("session_id", nargs="?", help="Agent Session ID")+ _add_session_target_arg(session_get_parser)_add_brief_arg(session_get_parser, list_command="vibe session list")_add_json_noop(session_get_parser)session_send_now_parser = session_subparsers.add_parser(@@ -18084,7 +17320,7 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe session send-now --help",)- session_send_now_parser.add_argument("session_id", help="Target Agent Session ID")+ _add_session_target_arg(session_send_now_parser)_add_json_noop(session_send_now_parser)session_queue_parser = session_subparsers.add_parser("queue",@@ -18108,7 +17344,7 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe session queue list --help",)- session_queue_list_parser.add_argument("session_id", help="Target Agent Session ID")+ _add_session_target_arg(session_queue_list_parser)_add_pagination_args(session_queue_list_parser,help_command="vibe session queue list --help",@@ -18124,8 +17360,8 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe session queue remove --help",)- session_queue_remove_parser.add_argument("session_id", help="Target Agent Session ID")session_queue_remove_parser.add_argument("message_id", help="Queued message ID")+ _add_session_target_arg(session_queue_remove_parser)_add_json_noop(session_queue_remove_parser)session_update_parser = session_subparsers.add_parser("update",@@ -18134,16 +17370,11 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe session update --help",)- session_update_parser.add_argument("session_id", nargs="?", help="Agent Session ID")+ _add_session_target_arg(session_update_parser)session_update_parser.add_argument("--title", help="New title. Pass an empty string to clear it (reverts to id-based display).")session_visibility_group = session_update_parser.add_mutually_exclusive_group()- session_visibility_group.add_argument(- "--visibility",- choices=("foreground", "background"),- help="Show the Session in normal chat lists or keep it background-only.",- )session_visibility_group.add_argument("--visible",dest="visibility",@@ -18520,25 +17751,24 @@ def build_parser():show_list_parser.add_argument("--updated-before", help="Filter by updated_at <= timestamp, or relative value such as 6h or 7d.")show_list_parser.add_argument("--q", dest="query", help="Search session ID, share ID, or visibility.")_add_pagination_args(show_list_parser, help_command="vibe show list --help")- show_list_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_list_parser)- _data_help_lang = _configured_cli_language()data_parser = subparsers.add_parser("data",- help=i18n_t("data.helpCommand", _data_help_lang),- description=i18n_t("data.helpDescription", _data_help_lang),+ help="Inspect Avibe data, and run explicit trace-retention maintenance",+ description="Inspect local Avibe SQLite state with guarded read-only SQL, or run explicit maintenance: `query` is read-only, while `retention --run` deletes old internal trace events and may compact the database.",formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe data --help",)data_subparsers = data_parser.add_subparsers(dest="data_command", metavar="{query,retention,skill-usage}")data_subparsers.required = Trueskill_usage_parser = data_subparsers.add_parser(- "skill-usage", help=i18n_t("data.skillUsage.helpCommand", _data_help_lang),- description=i18n_t("data.skillUsage.helpCommand", _data_help_lang),+ "skill-usage", help="Inspect or clear local Skill statistics (Instance Member or Owner)",+ description="Inspect or clear local Skill statistics (Instance Member or Owner)",error_help_command="vibe data skill-usage --help",)- skill_usage_parser.add_argument("--clear", action="store_true", help=i18n_t("data.skillUsage.helpClear", _data_help_lang))- skill_usage_parser.add_argument("--yes", action="store_true", help=i18n_t("data.skillUsage.helpYes", _data_help_lang))+ skill_usage_parser.add_argument("--clear", action="store_true", help="Clear Skill events and daily statistics.")+ skill_usage_parser.add_argument("--yes", action="store_true", help="Confirm clearing Skill statistics.")_add_json_noop(skill_usage_parser)data_query_parser = data_subparsers.add_parser("query",@@ -18560,35 +17790,30 @@ def build_parser():sql_group.add_argument("--sql-file", help="Read SQL from a UTF-8 file, or '-' for stdin.")_add_pagination_args(data_query_parser, help_command="vibe data query --help")_add_json_noop(data_query_parser)- _retention_help_lang = _configured_cli_language()data_retention_parser = data_subparsers.add_parser("retention",- help=i18n_t("data.retention.helpCommand", _retention_help_lang),- description=i18n_t("data.retention.helpDescription", _retention_help_lang),+ help="Show or run bounded retention for internal agent trace events",+ description="Status and manual control for the agent_events trace retention policy: tool_call trace rows older than the retention window are deleted; messages, non-trace events, and newer traces are never touched.",formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe data retention --help",)data_retention_parser.add_argument("--run",action="store_true",- help=i18n_t("data.retention.helpRun", _retention_help_lang),+ help="Run one retention pass now (bypasses the daily cadence gate, still respects the lease).",)data_retention_parser.add_argument("--days",type=int,default=None,- help=i18n_t(- "data.retention.helpDays",- _retention_help_lang,- current=_configured_trace_retention_days(_retention_help_lang),- ),+ help=f"Retention window override in days (default: the configured value, currently {_configured_trace_retention_days()}).",)data_retention_parser.add_argument("--compact",action="store_true",- help=i18n_t("data.retention.helpCompact", _retention_help_lang),+ help="Also physically compact the database (VACUUM) when safe; implies --run. Off by default: VACUUM holds the database's sole writer lock and can stall the running service's writes; run it during a maintenance window or with the service stopped.",)- _add_json_noop(data_retention_parser)+ _add_json_flag(data_retention_parser)show_path_parser = show_subparsers.add_parser("path",@@ -18600,7 +17825,7 @@ def build_parser():error_hint="Pass --session-id, or run from an Avibe Agent shell where AVIBE_SESSION_ID is injected.",)show_path_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")- show_path_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_path_parser)show_status_parser = show_subparsers.add_parser("status",@@ -18612,7 +17837,7 @@ def build_parser():error_hint="Pass --session-id, or run from an Avibe Agent shell where AVIBE_SESSION_ID is injected.",)show_status_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")- show_status_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_status_parser)show_update_parser = show_subparsers.add_parser("update",@@ -18647,7 +17872,7 @@ def build_parser():action="store_true",help="Revoke the current public URL and create a new one. Allowed only while public.",)- show_update_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_update_parser)show_mark_parser = show_subparsers.add_parser("mark",@@ -18660,19 +17885,16 @@ def build_parser():)show_mark_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")show_mark_parser.add_argument("--scope", default="default", help='Mark scope. Defaults to "default".')- show_mark_parser.add_argument("target", nargs="?", help="Target mark id or selector.")- show_mark_parser.add_argument("--target", dest="target_option", help="Alias for the positional target.")+ show_mark_parser.add_argument("target", help="Target mark id or selector.")mark_body_group = show_mark_parser.add_mutually_exclusive_group(required=True)- mark_body_group.add_argument("--message", "--body", dest="body", help="Assistant mark body text.")+ mark_body_group.add_argument("--message", help="Assistant mark body text.")mark_body_group.add_argument("--message-file",- "--body-file",- dest="body_file",help="Read assistant mark body from a UTF-8 file, or '-' for stdin.",)show_mark_parser.add_argument("--anchor-selector", help="Optional DOM selector for the anchored element.")show_mark_parser.add_argument("--anchor-text", help="Optional selected or summarized anchor text.")- show_mark_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_mark_parser)show_reply_parser = show_subparsers.add_parser("reply",@@ -18687,7 +17909,7 @@ def build_parser():reply_message_group = show_reply_parser.add_mutually_exclusive_group(required=True)reply_message_group.add_argument("--message", help="Reply body text.")reply_message_group.add_argument("--message-file", help="Read reply text from a UTF-8 file, or '-' for stdin.")- show_reply_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_reply_parser)show_marks_parser = show_subparsers.add_parser("marks",@@ -18698,7 +17920,7 @@ def build_parser():)show_marks_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")_add_pagination_args(show_marks_parser, help_command="vibe show marks --help")- show_marks_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_marks_parser)show_unmark_parser = show_subparsers.add_parser("unmark",@@ -18709,7 +17931,7 @@ def build_parser():)show_unmark_parser.add_argument("identifiers", nargs="+", metavar="ID_OR_TARGET")show_unmark_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")- show_unmark_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_unmark_parser)show_event_parser = show_subparsers.add_parser("event",@@ -18730,7 +17952,7 @@ def build_parser():action="store_true",help="For human intent/annotation events, request an Agent turn after recording the event.",)- show_event_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_event_parser)show_annotate_parser = show_subparsers.add_parser("annotate",@@ -18750,7 +17972,7 @@ def build_parser():choices=("smart", "screenshot"),help="Set annotation mode; with --on, enable directly in this mode.",)- show_annotate_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _add_json_noop(show_annotate_parser)task_parser = subparsers.add_parser("task",@@ -18784,10 +18006,6 @@ def build_parser():"--session-id",help="Agent Session ID to continue when the task runs.",)- task_add_parser.add_argument(- "--session-key",- help="Legacy compatibility target; prefer --session-id.",- )task_add_parser.add_argument("--create-session", action="store_true", help="Create one reusable Avibe Session ID for this task")task_add_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID each time this task runs")task_add_parser.add_argument("--same-scope", action="store_true", help="Place a created Session in the caller Session scope")@@ -18800,16 +18018,6 @@ def build_parser():"the directory its command runs in. Defaults to the caller's current directory."),)- delivery_group = task_add_parser.add_mutually_exclusive_group()- delivery_group.add_argument(- "--post-to",- choices=("thread", "channel"),- help=argparse.SUPPRESS,- )- delivery_group.add_argument(- "--deliver-key",- help=argparse.SUPPRESS,- )schedule_group = task_add_parser.add_mutually_exclusive_group(required=True)schedule_group.add_argument("--cron", help="Recurring schedule in 5-field crontab format; write weekdays as names (mon ... sun)"@@ -18821,8 +18029,6 @@ def build_parser():prompt_group = task_add_parser.add_mutually_exclusive_group()prompt_group.add_argument("--message", help="Stored user message to send each time the task runs")prompt_group.add_argument("--message-file", help="Read stored user message from a UTF-8 text file")- prompt_group.add_argument("--prompt", help=argparse.SUPPRESS)- prompt_group.add_argument("--prompt-file", help=argparse.SUPPRESS)task_add_parser.add_argument("--timezone", help="IANA timezone name used for --cron and naive --at values")task_add_parser.add_argument("--shell",@@ -18863,7 +18069,6 @@ def build_parser():help="Remove the stored custom task name",)task_update_parser.add_argument("--session-id", help="Replace the stored Agent Session ID")- task_update_parser.add_argument("--session-key", help="Legacy compatibility target; prefer --session-id")task_update_parser.add_argument("--create-session", action="store_true", help="Replace the task with one reusable newly-created Avibe Session ID")task_update_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID each time this task runs")task_update_parser.add_argument("--same-scope", action="store_true", help="Place created Sessions in the caller Session scope")@@ -18874,16 +18079,6 @@ def build_parser():"--cwd",help="Set working directory for Sessions created by this task, or for a command task, where its command runs",)- update_delivery_group = task_update_parser.add_mutually_exclusive_group()- update_delivery_group.add_argument(- "--post-to",- choices=("thread", "channel"),- help=argparse.SUPPRESS,- )- update_delivery_group.add_argument(- "--deliver-key",- help=argparse.SUPPRESS,- )task_update_parser.add_argument("--reset-delivery",action="store_true",@@ -18895,8 +18090,6 @@ def build_parser():task_update_parser.add_argument("--at", help="Replace the schedule with a one-shot ISO 8601 timestamp")task_update_parser.add_argument("--message", help="Replace the stored user message text")task_update_parser.add_argument("--message-file", help="Replace the stored user message from a UTF-8 text file")- task_update_parser.add_argument("--prompt", help=argparse.SUPPRESS)- task_update_parser.add_argument("--prompt-file", help=argparse.SUPPRESS)task_update_parser.add_argument("--timezone", help="Replace the stored IANA timezone name")task_update_parser.add_argument("--shell",@@ -18940,11 +18133,10 @@ def build_parser():task_list_parser.add_argument("--q",dest="query",- help=i18n_t("harness.cli.help.query", _configured_cli_language(), items="task"),+ help="Search common task text fields",)_add_pagination_args(task_list_parser, help_command="vibe task list --help")_add_json_noop(task_list_parser)- _add_hidden_task_alias(task_subparsers, "ls", task_list_parser)task_show_parser = task_subparsers.add_parser("show",@@ -19001,52 +18193,6 @@ def build_parser():)task_rm_parser.add_argument("task_id", help="Task ID from 'vibe task list'")_add_json_noop(task_rm_parser)- _add_hidden_task_alias(task_subparsers, "rm", task_rm_parser)-- hook_parser = subparsers.add_parser(- "hook",- help="Deprecated compatibility one-shot async hooks",- description="Deprecated compatibility entrypoint. Use 'vibe agent run' for new one-shot asynchronous turns.",- formatter_class=argparse.RawDescriptionHelpFormatter,- error_help_command="vibe hook --help",- error_hint="Use 'vibe agent run --help' for the current async Agent Run command shape.",- )- hook_subparsers = hook_parser.add_subparsers(dest="hook_command", metavar="{send}")- hook_subparsers.required = True- hook_send_parser = hook_subparsers.add_parser(- "send",- help="Deprecated compatibility async send",- description="Deprecated compatibility entrypoint. Use 'vibe agent run' for new one-shot asynchronous Agent Runs.",- epilog=_hook_send_examples_text(),- formatter_class=argparse.RawDescriptionHelpFormatter,- error_help_command="vibe hook send --help",- error_hint="Use 'vibe agent run' for new async Agent Runs.",- )- hook_send_parser.add_argument(- "--session-id",- help="Agent Session ID to continue for this one-shot async turn.",- )- hook_send_parser.add_argument(- "--session-key",- help="Legacy compatibility target; prefer --session-id.",- )- hook_send_parser.add_argument("--agent", help="Avibe Agent name to use for this one-shot async turn")- hook_delivery_group = hook_send_parser.add_mutually_exclusive_group()- hook_delivery_group.add_argument(- "--post-to",- choices=("thread", "channel"),- help=argparse.SUPPRESS,- )- hook_delivery_group.add_argument(- "--deliver-key",- help=argparse.SUPPRESS,- )- hook_prompt_group = hook_send_parser.add_mutually_exclusive_group(required=True)- hook_prompt_group.add_argument("--message", help="One-shot async user message to queue immediately")- hook_prompt_group.add_argument("--message-file", help="Read one-shot async user message from a UTF-8 text file")- hook_prompt_group.add_argument("--prompt", help=argparse.SUPPRESS)- hook_prompt_group.add_argument("--prompt-file", help=argparse.SUPPRESS)- _add_json_noop(hook_send_parser)watch_parser = subparsers.add_parser("watch",@@ -19077,34 +18223,14 @@ def build_parser():"--session-id",help="Agent Session ID to continue for follow-up messages from this watch.",)- watch_add_parser.add_argument(- "--session-key",- help="Legacy compatibility target; prefer --session-id.",- )watch_add_parser.add_argument("--create-session", action="store_true", help="Create one reusable Avibe Session ID for this watch")watch_add_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID each time this watch triggers")watch_add_parser.add_argument("--same-scope", action="store_true", help="Place a created Session in the caller Session scope")watch_add_parser.add_argument("--scope-id", help="Existing scopes.id that should own created Sessions")watch_add_parser.add_argument("--agent", help="Avibe Agent name to use for follow-up messages")- watch_delivery_group = watch_add_parser.add_mutually_exclusive_group()- watch_delivery_group.add_argument(- "--post-to",- choices=("thread", "channel"),- help=argparse.SUPPRESS,- )- watch_delivery_group.add_argument(- "--deliver-key",- help=argparse.SUPPRESS,- )- watch_add_parser.add_argument(- "--prefix",- help="Optional follow-up instruction text prepended before waiter stdout, joined with a blank line when both exist.",- )watch_message_group = watch_add_parser.add_mutually_exclusive_group()watch_message_group.add_argument("--message", help="Follow-up user message template sent with waiter output")watch_message_group.add_argument("--message-file", help="Read follow-up user message from a UTF-8 text file")- watch_message_group.add_argument("--prompt", help=argparse.SUPPRESS)- watch_message_group.add_argument("--prompt-file", help=argparse.SUPPRESS)watch_add_parser.add_argument("--cwd", help="Working directory for the waiter process")watch_add_parser.add_argument("--timeout",@@ -19164,41 +18290,20 @@ def build_parser():"--session-id",help="Agent Session ID to continue for follow-up messages from this watch.",)- watch_update_parser.add_argument(- "--session-key",- help="Legacy compatibility target; prefer --session-id.",- )watch_update_parser.add_argument("--create-session", action="store_true", help="Replace the watch with one reusable newly-created Avibe Session ID")watch_update_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Avibe Session ID each time this watch triggers")watch_update_parser.add_argument("--same-scope", action="store_true", help="Place created Sessions in the caller Session scope")watch_update_parser.add_argument("--scope-id", help="Existing scopes.id that should own created Sessions")watch_update_parser.add_argument("--agent", help="Replace the Avibe Agent used for follow-up messages")watch_update_parser.add_argument("--clear-agent", action="store_true", help="Clear the stored Avibe Agent override")- watch_update_delivery_group = watch_update_parser.add_mutually_exclusive_group()- watch_update_delivery_group.add_argument(- "--post-to",- choices=("thread", "channel"),- help=argparse.SUPPRESS,- )- watch_update_delivery_group.add_argument(- "--deliver-key",- help=argparse.SUPPRESS,- )- watch_update_delivery_group.add_argument(+ watch_update_parser.add_argument("--reset-delivery",action="store_true",help="Clear any stored delivery override and deliver back to the continued session target.",)- watch_update_parser.add_argument(- "--prefix",- help="Set follow-up instruction text prepended before waiter stdout.",- )- watch_update_parser.add_argument("--clear-prefix", action="store_true", help="Clear the stored follow-up prefix")watch_update_message_group = watch_update_parser.add_mutually_exclusive_group()watch_update_message_group.add_argument("--message", help="Replace the follow-up user message template")watch_update_message_group.add_argument("--message-file", help="Read replacement follow-up user message from a UTF-8 text file")- watch_update_message_group.add_argument("--prompt", help=argparse.SUPPRESS)- watch_update_message_group.add_argument("--prompt-file", help=argparse.SUPPRESS)watch_update_parser.add_argument("--cwd", help="Set working directory for the waiter process")watch_update_parser.add_argument("--clear-cwd", action="store_true", help="Clear the stored waiter working directory")watch_update_parser.add_argument("--timeout", type=float, help="Set per-cycle timeout in seconds")@@ -19244,11 +18349,10 @@ def build_parser():watch_list_parser.add_argument("--q",dest="query",- help=i18n_t("harness.cli.help.query", _configured_cli_language(), items="watch"),+ help="Search common watch text fields",)_add_pagination_args(watch_list_parser, help_command="vibe watch list --help")_add_json_noop(watch_list_parser)- _add_hidden_task_alias(watch_subparsers, "ls", watch_list_parser)watch_show_parser = watch_subparsers.add_parser("show",@@ -19294,7 +18398,7 @@ def build_parser():)watch_remove_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")_add_json_noop(watch_remove_parser)- _add_hidden_task_alias(watch_subparsers, "rm", watch_remove_parser)+ _hide_subcommands(subparsers, "desktop")return parser@@ -19564,23 +18668,18 @@ _CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {("task", "add"): "editor",("task", "update"): "editor",("task", "list"): "editor",- ("task", "ls"): "editor",("task", "show"): "editor",("task", "pause"): "editor",("task", "resume"): "editor",("task", "run"): "editor",("task", "remove"): "editor",- ("task", "rm"): "editor",("watch", "add"): "editor",("watch", "update"): "editor",("watch", "list"): "editor",- ("watch", "ls"): "editor",("watch", "show"): "editor",("watch", "pause"): "editor",("watch", "resume"): "editor",("watch", "remove"): "editor",- ("watch", "rm"): "editor",- ("hook", "send"): "editor",# Sessions and their queue, mirroring the HTTP surface: reading is Viewer# work, editing and the queue are Editor work, and both sides are narrowed# further by the effective Project role of each session the command touches.@@ -19795,9 +18894,9 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:_print_task_error(exc, help_command="vibe show --help")sys.exit(1)if args.command == "version":- sys.exit(cmd_version())+ sys.exit(cmd_version(args))if args.command == "check-update":- sys.exit(cmd_check_update())+ sys.exit(cmd_check_update(args))if args.command == "upgrade":sys.exit(cmd_upgrade())if args.command == "runtime":@@ -19843,7 +18942,7 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:sys.exit(cmd_agent_run(args))parser.error("agent command is required")if args.command == "runs":- if args.runs_command in {"list", "ls"}:+ if args.runs_command == "list":sys.exit(cmd_runs_list(args))if args.runs_command == "show":sys.exit(cmd_runs_show(args))@@ -19917,7 +19016,7 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:sys.exit(cmd_task_add(args))if args.task_command == "update":sys.exit(cmd_task_update(args))- if args.task_command in {"list", "ls"}:+ if args.task_command == "list":try:page_request = _page_request_from_args(args, help_command="vibe task list --help")except TaskCliError as exc:@@ -19944,19 +19043,15 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:sys.exit(cmd_task_set_enabled(args.task_id, True))if args.task_command == "run":sys.exit(cmd_task_run(args.task_id))- if args.task_command in {"remove", "rm"}:+ if args.task_command == "remove":sys.exit(cmd_task_remove(args.task_id))parser.error("task command is required")- if args.command == "hook":- if args.hook_command == "send":- sys.exit(cmd_hook_send(args))- parser.error("hook command is required")if args.command == "watch":if args.watch_command == "add":sys.exit(cmd_watch_add(args))if args.watch_command == "update":sys.exit(cmd_watch_update(args))- if args.watch_command in {"list", "ls"}:+ if args.watch_command == "list":try:page_request = _page_request_from_args(args, help_command="vibe watch list --help")except TaskCliError as exc:@@ -19981,7 +19076,7 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:sys.exit(cmd_watch_set_enabled(args.watch_id, False))if args.watch_command == "resume":sys.exit(cmd_watch_set_enabled(args.watch_id, True))- if args.watch_command in {"remove", "rm"}:+ if args.watch_command == "remove":sys.exit(cmd_watch_remove(args.watch_id))parser.error("watch command is required")# Bare `vibe` is also the supervisor entry (systemd, launchd); it is neverdiff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 01b73bf7d..9642fed0b 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -52,7 +52,6 @@"back": "Back to home"},"markdown": {- "help": "Public Show Page links automatically return agent-readable Markdown to Agents and command-line clients. For an authorized private read, request the URL with Accept: text/markdown.","errors": {"authenticationRequired": "Authentication is required to read this Show Page.","forbidden": "You do not have permission to read this Show Page.",@@ -93,34 +92,6 @@},"harness": {"agentInitiatedContinuation": "Agent-initiated continuation",- "cli": {- "agentRunModel": {- "existingSession": "--model and --reasoning-effort only apply when the run creates a new Session",- "existingSessionHint": "An existing Session keeps its model; change it in the Web UI's Session model picker. To run on another model now, start a new Session (--agent <name> --model ...) or fork this one (--fork-session <id> --model ...).",- "modelNotInCatalog": "model '{model}' is not in the {backend} model catalog",- "modelMaybeNewer": "model '{model}' is not in the {backend} model catalog; it may be a typo or newer than the catalog",- "effortInvalidForModel": "reasoning_effort '{effort}' is not valid for model '{model}'",- "effortInvalidForBackend": "reasoning_effort '{effort}' is not valid for backend '{backend}'",- "catalogUnavailable": "the {backend} model catalog could not be loaded, so the model and reasoning effort cannot be checked",- "catalogHint": "Run `vibe agent models {agent}` to list valid models and reasoning efforts.",- "helpModel": "Model for the new Session this run creates (a blank new Session, --create-session, or a fork); kept on that Session for its later turns. Not valid with --session-id. See `vibe agent models <agent>`.",- "helpEffort": "Reasoning effort for the new Session this run creates; kept on that Session. Not valid with --session-id."- },- "help": {- "command": "Inspect unified Harness live state and anomalies",- "description": "Inspect active Runs, armed Watches, upcoming Tasks, and live anomalies.",- "status": "Show the bounded live/anomaly snapshot",- "statusDescription": "Show live Runs, armed Watches, upcoming Tasks, and anomalies for the caller Session. Use --session-id for another Session or --global for every Session.",- "brief": "Print only the compact row that '{list_command}' prints for this record",- "query": "Search common {items} text fields"- },- "error": {- "sqliteRequired": "Harness status requires the SQLite task store.",- "controllerStatus": "The controller returned status {status}.",- "controllerTimeout": "The controller request timed out.",- "controllerUnavailable": "The controller is unreachable."- }- },"promptEcho": {"scheduled": "⏰ Scheduled task","watch": "👀 Watch",@@ -205,13 +176,7 @@"failed": "The run failed before producing a result."},"bindingUnresolvedRetry": "Pinned agent session {session} cannot accept a turn ({attempt}/{threshold}). This definition will be paused after {threshold} consecutive unresolvable-target failures. Re-point it with: vibe task update {id} --session-id <id>.",- "bindingUnresolvedPaused": "paused: pinned agent session {session} cannot accept a turn. This definition would fail on every run. Re-point it with: vibe task update {id} --session-id <id>; then resume it with: vibe task resume {id}.",- "cli": {- "help": {- "cancel": "Request best-effort cancellation for one run; a run already in the live Session turn stops that whole turn, like Session Stop"- },- "canceledBeforeLiveTurn": "Run was canceled before its input reached the live Session turn."- }+ "bindingUnresolvedPaused": "paused: pinned agent session {session} cannot accept a turn. This definition would fail on every run. Re-point it with: vibe task update {id} --session-id <id>; then resume it with: vibe task resume {id}."},"notice": {"failed": "[Avibe Harness] Scheduled work \"{name}\" failed.",@@ -294,9 +259,7 @@"selectOne": "Select one","selectOneOrMore": "Select one or more","processing": "Processing `/{command}`...",- "submitted": "Submitted",- "moreRecordsAddPage": "More records are available. Add --page to continue.",- "moreRecordsContinueWith": "More records are available. Continue with: {command}"+ "submitted": "Submitted"},"dependencies": {"askill": {@@ -370,15 +333,6 @@"message": "A Watch on a running command cannot be resumed once it is paused or finished.","hint": "Pausing or finishing ended its command. Run the command again to watch a new run, or remove this Watch with `vibe watch remove {id}`."},- "jobWatchUpdateRefused": {- "message": "This Watch waits on a command that is already running, so only its name, message, and lifetime can be changed.",- "hint": "Its Session, Agent, delivery, and command were fixed when the command was handed over. Change the name, message, or lifetime with `vibe watch update {id}`."- },- "cronNumericWeekday": {- "message": "Cron weekday field uses numbers: {field}",- "readings": "Avibe (APScheduler) reads it as {avibe}; crontab(5) reads it as {crontab}.",- "hint": "Write weekday names (mon, tue, wed, thu, fri, sat, sun); they mean the same day everywhere."- },"sessionFork": {"agentUnavailable": {"message": "The source session's Agent is no longer available for a new fork.",@@ -586,10 +540,7 @@"availableDiscord": "🚀 **Avibe Update Available**\n\nUpdate from {current} → {latestLink}","availableMarkdown": "🚀 Avibe Update Available\n\nUpdate from {current} → {latestLink}","availableText": "🚀 Avibe Update Available\n\nUpdate from {current} → {latestLink}",- "actionUpdateNow": "Update Now",- "downgradeRefused": "Refusing to {command} from Avibe {version} ({generation}): the last activated install is {activatedVersion} ({activatedGeneration}). Run `{rerunCommand}` instead, or pass --allow-downgrade to run the older build on purpose.",- "downgradeAllowed": "Warning: running Avibe {version} ({generation}), older than the last activated install {activatedVersion} ({activatedGeneration}), because --allow-downgrade was given.",- "downgradeWarning": "Warning: this vibe runs Avibe {version} ({generation}), older than the last activated install {activatedVersion} ({activatedGeneration}). Use `{launcher}`, or run `{repairCommand}` to move every launcher to it."+ "actionUpdateNow": "Update Now"},"discord": {"settingsSubtitle": "Adjust message visibility, mention behavior, and language.",@@ -855,60 +806,9 @@"permission": {"adminOnly": "🔒 Only admins can change bot settings. Contact an admin if you need access."},- "skill": {- "cli": {- "help": {- "command": "List and load Skills through Avibe",- "list": "List available Skills",- "load": "Load one Skill",- "page": "Catalog page (default: 1)",- "name": "Skill name"- },- "more": "More skills are available. Run `vibe skill list --page {page}` to view more.",- "error": {- "invalidPage": "error: page must be a positive integer",- "notFound": "Skill not found: {name}"- }- }- },"computer": {"cli": {- "help": {- "command": "Use the local desktop through the active Avibe Agent Turn",- "description": "Run an allowlisted Computer Use operation through the Avibe service. The caller Session is taken from the Agent environment and the service checks that it has an active Turn.",- "argsJson": "JSON object of driver arguments, or @path to a JSON file.",- "arg": "Override one driver argument; JSON values are parsed when valid.",- "output": "Caller-selected screenshot path for 'observe window'.",- "json": "Print the structured service response.",- "run": "Run a JavaScript Computer Use script",- "runDescription": "Run an ESM file with the shipped @avibe/computer module, bound to this exact Avibe Agent Turn.",- "scriptFile": "Path to a readable .mjs script.",- "scriptArg": "Pass one script argument as name=value or name=@file. Values remain strings.",- "js": "Evaluate JavaScript in this Session's persistent Computer Use kernel",- "jsDescription": "Evaluate code in a Node kernel that keeps top-level bindings between calls in this Avibe Session. computer and avibe are preloaded; top-level await is supported. Each call is bound to the current Agent Turn.",- "jsCode": "JavaScript source, or @FILE to read it from a UTF-8 file.",- "jsTimeout": "Per-call timeout in milliseconds (default 30000, max 300000).",- "jsReset": "Discard this Session's JavaScript kernel and all of its bindings; open apps are untouched",- "observe": "Observe apps, windows, or one exact window",- "observeApps": "List visible applications",- "observeWindows": "List windows",- "observeWindow": "Observe one exact window and optionally save a screenshot",- "zoom": "Inspect one exact window at a readable scale",- "click": "Click an observed element or exact window coordinate",- "type": "Type text into an observed target",- "key": "Press one key",- "hotkey": "Press a key combination",- "scroll": "Scroll an observed target",- "drag": "Drag an observed target",- "setValue": "Set an observed control value",- "launch": "Launch an application or URL",- "forceQuit": "Force-terminate an application; unsaved state is lost.",- "clipboard": "Read or write the system clipboard",- "clipboardRead": "Read the system clipboard",- "clipboardWrite": "Write the system clipboard"- },"error": {- "invalidArguments": "Invalid Computer Use arguments: {detail}","cannotReadArgsJson": "Cannot read the --args-json file: {error}","argsJsonObject": "--args-json must contain a JSON object","argNameValue": "--arg values must use name=value",@@ -1058,43 +958,14 @@}}},- "debug": {- "cli": {- "help": {- "command": "Inspect internal Avibe state",- "prompt": "Inspect authored prompt sources",- "promptExport": "Export all prompt sources, optionally with the production rendering",- "promptContext": "JSON file with backend, optional agent_instructions and production builder options",- "promptFormat": "Export format"- },- "error": {- "promptExport": "Prompt export failed: {error}",- "invalidContext": "The context must be a JSON object containing only backend, agent_instructions and options.",- "invalidBackend": "backend must be claude, codex or opencode.",- "invalidField": "Invalid field type or missing required field: {field}",- "unknownField": "Unknown field: {field}",- "unreadableContext": "Cannot read the context file. Check its path and permissions.",- "invalidJson": "The context file must contain valid UTF-8 JSON.",- "renderFailed": "Cannot render the prompt sources. Check the sources and rendering inputs."- }- }- },"language": {"systemDefault": "(System Default)","en": "English","zh": "中文"},"desktopRuntime": {- "checkUpdate": "Updates are delivered with the Avibe desktop app.",- "upgrade": "This Runtime is managed by the Avibe desktop app. Update the app to update Avibe.","apiUpgrade": "This Runtime is managed by the Avibe desktop app.",- "backendUpgrade": "This Codex backend belongs to an older Avibe desktop Runtime and cannot be updated in place. Reopen the current desktop app to install it privately.",- "handoverNotRequested": "Another desktop-managed Avibe Runtime is running here; this start does not replace it.",- "handoverRefused": "Refused to stop the superseded desktop-managed Avibe Runtime: {reason}",- "handoverFailed": "Failed to stop the superseded desktop-managed Avibe Runtime: {part}",- "claimRefused": "Another Avibe Runtime is running here and does not belong to this desktop app; nothing was stopped ({part}: {reason}).",- "stopRefused": "Nothing was stopped: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Stop it from the Avibe that started it.",- "restartRefused": "Nothing was restarted: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Restart it from the Avibe that started it."+ "backendUpgrade": "This Codex backend belongs to an older Avibe desktop Runtime and cannot be updated in place. Reopen the current desktop app to install it privately."},"cliHealth": {"installReadbackFailed": "The installer finished, but the selected CLI is missing or cannot run. Installation was not verified; repair it and try again.",@@ -1288,26 +1159,6 @@"oauth_time_mismatch_body": "Avibe Cloud finished the sign-in, but this machine rejected the security token because the local clock appears out of sync. Correct the system time, then try again.","invalid_oauth_nonce_title": "We couldn't verify this sign-in","invalid_oauth_nonce_body": "This sign-in attempt couldn't be verified, so we stopped to keep your account secure. Start over to continue."- },- "cli": {- "pairHelpEpilog": "Guidance:\n This is the direct pairing command for users who already have a pairing key.\n For the guided setup flow, run `vibe remote`.\n Without a key, the CLI resumes a recoverable local pairing, or prompts if none is pending.\n To replace an uncertain pending attempt, explicitly supply a fresh key and the same backend URL.\n Pairing saves the remote-access config and then starts the managed tunnel automatically.\n The pairing key is one-time use; create a fresh key from the Avibe Cloud console if it fails.\n\nExamples:\n vibe remote\n vibe remote pair vrp_abc123\n vibe remote pair --device-name \"Mac Studio\"\n vibe remote pair --backend-url https://avibe.bot",- "localWriteUnavailableTitle": "Remote access setup stopped before contacting Avibe Cloud.",- "localWriteUnavailableBody": "The local config cannot durably accept a pairing, so no pairing key was consumed.",- "saveFailedAfterRedeemTitle": "The pairing was redeemed cloud-side but could not be saved locally.",- "orphanedBinding": "Orphaned binding: instance {instance_id} (device {device_name}).",- "recoveryRetained": "The redeemed credentials are kept on this host, so no new pairing key is needed.",- "retryAfterLocalFix": "Fix the local config problem, then run:",- "recoveryInvalid": "The saved pairing recovery record is invalid and cannot be replayed.",- "recoveryUnavailable": "Local pairing recovery could not start. No new pairing key was consumed.",- "recoveryNotReady": "A pairing operation has no durably recorded response. It may still be running or may have consumed the key. A keyless retry cannot recover it.",- "recoveryRevoked": "The saved pairing recovery was invalidated by a local unpair operation.",- "recoveryIndeterminate": "The pairing outcome is uncertain or was superseded locally. No recoverable response is guaranteed; do not reuse the submitted key.",- "replacePendingPairing": "Check the cloud console and ensure no pairing is still running. To explicitly replace the pending attempt, substitute a fresh key and the intended backend URL in this command (the default backend is https://avibe.bot):",- "retirementFailed": "Pairing was applied, but its recovery record could not be retired. Retry without a new key.",- "failedClaimCleanup": "This pairing attempt failed and was not applied. Fix local storage, then retry without a key to clear its failed-operation record.",- "failedClaimUnrecorded": "This pairing attempt failed and was not applied. Its cleanup could not be recorded. After fixing local storage, supply a fresh pairing key explicitly to 'vibe remote pair'; a keyless retry cannot recover this result.",- "failedClaimRetired": "The failed pairing record was cleared. Get a fresh pairing key, then run the following command to enter it securely:",- "retryPairCommand": "Retry local pairing recovery with:"}},"turn": {@@ -1322,39 +1173,7 @@"runtime": {"prepare": {"prepared": "Show Runtime prepared.",- "skipped": "Show Runtime preparation skipped: {reason}",- "failed": "Show Runtime preparation failed: {reason}",- "unsupportedSource": "Show Runtime preparation failed: {reason}. Remove VIBE_SHOW_RUNTIME_SOURCE and use the packaged runtime, or set VIBE_SHOW_RUNTIME_BIN to a runtime you built.",- "modelHubEngineSkipped": "Model Hub engine: skipped ({reason}).",- "modelHubEngineInstalled": "Model Hub engine installed.",- "modelHubEngineReady": "Model Hub engine ready.",- "modelHubEngineNotReady": "Model Hub engine not ready: {reason}",- "ripgrepInstalled": "ripgrep installed.",- "ripgrepReady": "ripgrep ready.",- "ripgrepNotReady": "ripgrep not ready: {reason}",- "cloudflaredInstalled": "cloudflared installed.",- "cloudflaredReady": "cloudflared ready.",- "cloudflaredNotReady": "cloudflared not ready: {reason}"- },- "clean": {- "commandHelp": "Remove stale Show, Git, Model Hub, tmux, ripgrep, and cloudflared runtime installs and archives; exit nonzero if any cleanup fails.",- "dryRunHelp": "Report stale archives and cache entries without removing anything.",- "wouldRemoveItems": "Would remove {count} Show Runtime cache item(s).",- "wouldRemoveArchives": "Would remove {count} downloaded Show Runtime archive(s) ({size}).",- "consumerWouldRemoveItems": "Would remove {count} {consumer} cache item(s).",- "consumerWouldRemoveArchives": "Would remove {count} downloaded {consumer} archive(s) ({size}).",- "removedItems": "Removed {count} Show Runtime cache item(s).",- "removedArchives": "Removed {count} downloaded Show Runtime archive(s) ({size}).",- "consumerRemovedItems": "Removed {count} {consumer} cache item(s).",- "consumerRemovedArchives": "Removed {count} downloaded {consumer} archive(s) ({size}).",- "consumerPreviewFailed": "{consumer} cache preview failed ({reason}); stale entries may remain.",- "consumerFailed": "{consumer} cleanup failed ({reason}); stale entries remain.",- "consumerArchivesPartial": "{consumer} archive cleanup was partial ({reason}); {failed} archive(s) could not be removed.",- "consumerArchivesSkipped": "{consumer} archive cleanup skipped ({reason}); stale archives may remain.",- "partiallyRemoved": " {failed} archive(s) could not be removed; check permissions and the Avibe log.",- "skipped": "Archive cleanup skipped ({reason}); stale archives may remain. Try again after the running install or cleanup finishes.",- "removalFailed": "{failed} archive(s) could not be removed; stale archives remain. Check runtime directory permissions and the Avibe log.",- "skippedInspection": "Archive cleanup could not inspect the cache ({reason}); stale archives may remain. Check runtime directory permissions and the Avibe log."+ "failed": "Show Runtime preparation failed: {reason}"},"doctor": {"archiveCacheReclaimable": "Show Runtime archive cache holds {count} reclaimable archive(s) ({size}); the current and rollback archives are kept.",@@ -1374,15 +1193,6 @@"repairExplicitCommandFailed": "The Show Runtime command from VIBE_SHOW_RUNTIME_BIN could not start: {reason}. Fix or remove the override, then rerun Doctor.","repairPrepareFailed": "Show Runtime preparation failed: {detail}","repairLegacyArchiveUnavailable": "The packaged Show Runtime manifest is unavailable and the legacy upstream archive URL has no release asset. Upgrade or reinstall the official Avibe package, or remove stale runtime source overrides."- },- "stop": {- "opencodeStopped": "OpenCode server stopped",- "serviceFailed": "ERROR: Avibe service did not stop; preserving pidfile and aborting.",- "uiFailed": "ERROR: Avibe UI did not stop; preserving pidfile and aborting.",- "installerFailed": "ERROR: Desktop backend installer processes did not stop.",- "opencodeFailed": "ERROR: The OpenCode server this Runtime started did not stop.",- "unknownFailed": "ERROR: A process this Runtime started could not be identified and was left running.",- "remoteAccessFailed": "ERROR: The remote access tunnel could not be stopped."}},"doctor": {@@ -1764,44 +1574,6 @@"dryTmux": "Would install or refresh the manifest-pinned tmux runtime."}},- "data": {- "helpCommand": "Inspect Avibe data, and run explicit trace-retention maintenance",- "helpDescription": "Inspect local Avibe SQLite state with guarded read-only SQL, or run explicit maintenance: `query` is read-only, while `retention --run` deletes old internal trace events and may compact the database.",- "skillUsage": {- "ownerRequired": "Instance Member or Owner access is required.",- "confirmationRequired": "Clearing Skill statistics requires --yes.",- "clearRequired": "--yes requires --clear.",- "helpCommand": "Inspect or clear local Skill statistics (Instance Member or Owner)",- "helpClear": "Clear Skill events and daily statistics.",- "helpYes": "Confirm clearing Skill statistics."- },- "retention": {- "invalidDays": "--days must be between {minimum} and {maximum}; refusing to run instead of silently clamping the window.",- "helpCommand": "Show or run bounded retention for internal agent trace events",- "helpDescription": "Status and manual control for the agent_events trace retention policy: tool_call trace rows older than the retention window are deleted; messages, non-trace events, and newer traces are never touched.",- "helpRun": "Run one retention pass now (bypasses the daily cadence gate, still respects the lease).",- "helpDays": "Retention window override in days (default: the configured value, currently {current}).",- "helpCompact": "Also physically compact the database (VACUUM) when safe; implies --run. Off by default: VACUUM holds the database's sole writer lock and can stall the running service's writes; run it during a maintenance window or with the service stopped.",- "configRecovered": "The Avibe config could not be read (recovery defaults active); the retention policy is unknown. Re-run with an explicit --days window to delete anything.",- "compactionReasonCheckpointBusy": "the database is busy with concurrent readers/writers",- "compactionReasonFreeSpace": "there is not enough free disk space to rewrite the database safely",- "compactionReasonOther": "compaction was not safe to run",- "error": "Trace retention command failed: {error}",- "plan": "{count} trace row(s) older than {days} day(s) are eligible ({size} of payload text).",- "lastRun": "Last retention run: {at}, deleted {rows} row(s).",- "neverRun": "No retention run has completed yet.",- "disabled": "Trace retention is disabled in runtime config; the daily task will not delete anything.",- "compaction": "Reclaimable inside the database right now: {size}.",- "ran": "Retention pass deleted {rows} trace row(s).",- "compacted": "Database compacted; {size} returned to disk.",- "compactionDeferred": "Compaction deferred ({reason}); rows are deleted, disk space returns on a later safe pass.",- "compactionSkipped": "Compaction skipped: too little would be reclaimed.",- "leaseLost": "This pass lost its lease to another retention run; deletion stopped partway and no completion was recorded. Retry once the other run finishes.",- "notDue": "Retention already ran within the last day; nothing to do.",- "busy": "Another retention run is active; try again later.",- "cancelled": "Retention stopped at a batch boundary; no completion was recorded."- }- },"vibeyAgent": {"error": {"refusal": "The model declined to answer this request.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 5caf79542..e151d3275 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -52,7 +52,6 @@"back": "返回首页"},"markdown": {- "help": "公共 Show Page 链接会自动向 Agent 和命令行客户端返回 Agent 可读的 Markdown。读取已授权的私有页面时,请在请求 URL 时设置 Accept: text/markdown。","errors": {"authenticationRequired": "需要先完成身份验证才能读取此 Show Page。","forbidden": "你无权读取此 Show Page。",@@ -93,34 +92,6 @@},"harness": {"agentInitiatedContinuation": "Agent 主动发起的续接",- "cli": {- "agentRunModel": {- "existingSession": "--model 和 --reasoning-effort 只在这次运行创建新 Session 时可用",- "existingSessionHint": "已有 Session 保持自己的模型;请在 Web UI 的 Session 模型选择器中修改。如果现在就要换模型运行,请新建一个 Session(--agent <名称> --model ...),或分叉当前 Session(--fork-session <id> --model ...)。",- "modelNotInCatalog": "模型 '{model}' 不在 {backend} 的模型目录中",- "modelMaybeNewer": "模型 '{model}' 不在 {backend} 的模型目录中;可能是拼写错误,也可能比目录更新",- "effortInvalidForModel": "推理强度 '{effort}' 不适用于模型 '{model}'",- "effortInvalidForBackend": "推理强度 '{effort}' 不适用于 backend '{backend}'",- "catalogUnavailable": "无法加载 {backend} 的模型目录,因此无法检查模型和推理强度",- "catalogHint": "运行 `vibe agent models {agent}` 查看可用的模型和推理强度。",- "helpModel": "这次运行所创建的新 Session(空白新 Session、--create-session 或分叉)使用的模型;该 Session 之后的轮次会沿用它。不能与 --session-id 一起使用。参见 `vibe agent models <agent>`。",- "helpEffort": "这次运行所创建的新 Session 使用的推理强度;该 Session 会沿用它。不能与 --session-id 一起使用。"- },- "help": {- "command": "检查统一的 Harness 实时状态和异常",- "description": "检查活跃 Run、已启用 Watch、即将触发的 Task 和实时异常。",- "status": "显示有界的实时状态与异常快照",- "statusDescription": "显示调用方 Session 的活跃 Run、已启用 Watch、即将触发的 Task 和实时异常。用 --session-id 查看其他 Session,用 --global 查看所有 Session。",- "brief": "只输出 '{list_command}' 为这条记录打印的那一行精简记录",- "query": "搜索常见的 {items} 文本字段"- },- "error": {- "sqliteRequired": "Harness 状态需要 SQLite Task 存储。",- "controllerStatus": "控制器返回状态码 {status}。",- "controllerTimeout": "控制器请求超时。",- "controllerUnavailable": "无法连接控制器。"- }- },"promptEcho": {"scheduled": "⏰ 定时任务","watch": "👀 监听",@@ -205,13 +176,7 @@"failed": "本次 run 在产出结果前失败,因此没有结果。"},"bindingUnresolvedRetry": "绑定的 Agent 会话 {session} 无法接收请求({attempt}/{threshold})。连续 {threshold} 次出现目标会话不可用后,该定义将自动暂停。请用以下命令重新绑定:vibe task update {id} --session-id <id>。",- "bindingUnresolvedPaused": "已暂停:绑定的 Agent 会话 {session} 无法接收请求,该定义继续运行只会反复失败。请用以下命令重新绑定:vibe task update {id} --session-id <id>;然后恢复:vibe task resume {id}。",- "cli": {- "help": {- "cancel": "\u8bf7\u6c42\u5c3d\u529b\u53d6\u6d88\u4e00\u4e2a run\uff1b\u82e5\u8be5 run \u5df2\u8fdb\u5165\u6b63\u5728\u8fd0\u884c\u7684 Session turn\uff0c\u4f1a\u50cf Session Stop \u4e00\u6837\u505c\u6b62\u6574\u4e2a turn"- },- "canceledBeforeLiveTurn": "\u8be5 run \u5728\u5176\u8f93\u5165\u8fdb\u5165\u6b63\u5728\u8fd0\u884c\u7684 Session turn \u4e4b\u524d\u5df2\u88ab\u53d6\u6d88\u3002"- }+ "bindingUnresolvedPaused": "已暂停:绑定的 Agent 会话 {session} 无法接收请求,该定义继续运行只会反复失败。请用以下命令重新绑定:vibe task update {id} --session-id <id>;然后恢复:vibe task resume {id}。"},"notice": {"failed": "[Avibe Harness] 后台任务「{name}」执行失败。",@@ -294,9 +259,7 @@"selectOne": "选择一个","selectOneOrMore": "选择一个或多个","processing": "正在处理 `/{command}`...",- "submitted": "已提交",- "moreRecordsAddPage": "还有更多记录。加上 --page 继续翻页。",- "moreRecordsContinueWith": "还有更多记录。继续翻页:{command}"+ "submitted": "已提交"},"dependencies": {"askill": {@@ -370,15 +333,6 @@"message": "等待运行中命令的 Watch 一旦暂停或结束,就无法恢复。","hint": "暂停或结束时它的命令已经停止。如需继续,请重新运行该命令;也可以用 `vibe watch remove {id}` 删除这个 Watch。"},- "jobWatchUpdateRefused": {- "message": "这个 Watch 等待的是一个已在运行的命令,只能修改它的名称、消息和生命周期上限。",- "hint": "它的 Session、Agent、投递目标和命令在命令交接时已经确定。可用 `vibe watch update {id}` 修改名称、消息或生命周期上限。"- },- "cronNumericWeekday": {- "message": "cron 的星期字段使用了数字:{field}",- "readings": "Avibe(APScheduler)解析为 {avibe};标准 crontab(5) 解析为 {crontab}。",- "hint": "请改用星期英文名(mon、tue、wed、thu、fri、sat、sun),它们在两种规则下含义一致。"- },"sessionFork": {"agentUnavailable": {"message": "源会话的 Agent 已无法用于创建新的复刻会话。",@@ -586,10 +540,7 @@"availableDiscord": "🚀 **Avibe 有可用更新**\n\n从 {current} 更新到 {latestLink}","availableMarkdown": "🚀 Avibe 有可用更新\n\n从 {current} 更新到 {latestLink}","availableText": "🚀 Avibe 有可用更新\n\n从 {current} 更新到 {latestLink}",- "actionUpdateNow": "立即更新",- "downgradeRefused": "拒绝从 Avibe {version}({generation})执行 {command}:最近激活的安装是 {activatedVersion}({activatedGeneration})。请改为运行 `{rerunCommand}`;如确需运行旧版本,请加 --allow-downgrade。",- "downgradeAllowed": "警告:由于指定了 --allow-downgrade,正在运行 Avibe {version}({generation}),它比最近激活的安装 {activatedVersion}({activatedGeneration})旧。",- "downgradeWarning": "警告:这个 vibe 运行的是 Avibe {version}({generation}),比最近激活的安装 {activatedVersion}({activatedGeneration})旧。请使用 `{launcher}`,或运行 `{repairCommand}` 让所有启动器都指向它。"+ "actionUpdateNow": "立即更新"},"discord": {"settingsSubtitle": "调整消息可见性、@提及策略与语言。",@@ -855,60 +806,9 @@"permission": {"adminOnly": "🔒 仅管理员可以修改 Bot 设置。如需权限请联系管理员。"},- "skill": {- "cli": {- "help": {- "command": "通过 Avibe 列出和加载 Skills",- "list": "列出可用的 Skills",- "load": "加载一个 Skill",- "page": "Catalog 页码(默认:1)",- "name": "Skill 名称"- },- "more": "还有更多 Skills。运行 `vibe skill list --page {page}` 查看下一页。",- "error": {- "invalidPage": "错误:页码必须是正整数",- "notFound": "未找到 Skill:{name}"- }- }- },"computer": {"cli": {- "help": {- "command": "通过当前 Avibe Agent Turn 使用本机桌面",- "description": "通过 Avibe 服务执行 allowlist 中的 Computer Use 操作。调用方 Session 来自 Agent 环境,服务端会检查它是否有当前活动 Turn。",- "argsJson": "Driver 参数 JSON 对象,或使用 @路径读取 JSON 文件。",- "arg": "覆盖一个 driver 参数;有效 JSON 值会按 JSON 解析。",- "output": "调用方选择的截图路径,用于“observe window”。",- "json": "输出结构化服务响应。",- "run": "运行 JavaScript Computer Use 脚本",- "runDescription": "使用随 Avibe 发货的 @avibe/computer 模块运行 ESM 文件,并绑定到当前这个 Avibe Agent Turn。",- "scriptFile": "可读的 .mjs 脚本路径。",- "scriptArg": "以 name=value 或 name=@file 传入脚本参数;值保持为字符串。",- "js": "在本 Session 的常驻 Computer Use 内核中执行 JavaScript",- "jsDescription": "在一个 Node 内核中执行代码,同一 Avibe Session 的多次调用之间保留顶层变量。已预载 computer 和 avibe,支持顶层 await。每次调用都绑定到当前 Agent Turn。",- "jsCode": "JavaScript 源码,或用 @FILE 从 UTF-8 文件读取。",- "jsTimeout": "单次调用超时(毫秒,默认 30000,最大 300000)。",- "jsReset": "丢弃本 Session 的 JavaScript 内核及其全部变量;已打开的应用不受影响",- "observe": "观察应用、窗口或一个精确窗口",- "observeApps": "列出可见应用",- "observeWindows": "列出窗口",- "observeWindow": "观察一个精确窗口,并可选择保存截图",- "zoom": "以易读比例检查一个精确窗口",- "click": "点击已观察的元素或精确窗口坐标",- "type": "向已观察的目标输入文本",- "key": "按下一个按键",- "hotkey": "按下组合键",- "scroll": "滚动已观察的目标",- "drag": "拖动已观察的目标",- "setValue": "设置已观察控件的值",- "launch": "启动应用或 URL",- "forceQuit": "强制终止应用;未保存的数据会丢失。",- "clipboard": "读取或写入系统剪贴板",- "clipboardRead": "读取系统剪贴板",- "clipboardWrite": "写入系统剪贴板"- },"error": {- "invalidArguments": "Computer Use 参数无效:{detail}","cannotReadArgsJson": "无法读取 --args-json 文件:{error}","argsJsonObject": "--args-json 必须包含 JSON 对象","argNameValue": "--arg 的值必须使用 name=value 格式",@@ -1058,43 +958,14 @@}}},- "debug": {- "cli": {- "help": {- "command": "查看 Avibe 内部状态",- "prompt": "查看维护中的 Prompt 源",- "promptExport": "导出完整 Prompt 源区块,可附带生产渲染结果",- "promptContext": "包含 backend、可选 agent_instructions 和生产构建参数 options 的 JSON 文件",- "promptFormat": "导出格式"- },- "error": {- "promptExport": "Prompt 导出失败:{error}",- "invalidContext": "上下文必须是 JSON 对象,且只能包含 backend、agent_instructions 和 options。",- "invalidBackend": "backend 必须为 claude、codex 或 opencode。",- "invalidField": "字段类型无效或缺少必填字段:{field}",- "unknownField": "未知字段:{field}",- "unreadableContext": "无法读取上下文文件,请检查路径和权限。",- "invalidJson": "上下文文件必须包含有效的 UTF-8 JSON。",- "renderFailed": "无法渲染提示词来源,请检查源文件和渲染输入。"- }- }- },"language": {"systemDefault": "(系统默认)","en": "English","zh": "中文"},"desktopRuntime": {- "checkUpdate": "更新由 Avibe 桌面应用统一提供。",- "upgrade": "此 Runtime 由 Avibe 桌面应用管理。请更新桌面应用来更新 Avibe。","apiUpgrade": "此 Runtime 由 Avibe 桌面应用管理。",- "backendUpgrade": "此 Codex 后端属于旧版 Avibe 桌面 Runtime,无法原地更新。请重新打开当前桌面应用,将其安装为私有后端。",- "handoverNotRequested": "此处正在运行另一个桌面托管的 Avibe Runtime;本次启动不会替换它。",- "handoverRefused": "已拒绝停止被取代的桌面托管 Avibe Runtime:{reason}",- "handoverFailed": "未能停止被取代的桌面托管 Avibe Runtime:{part}",- "claimRefused": "此处正在运行另一个不属于本桌面应用的 Avibe Runtime;未停止任何进程({part}:{reason})。",- "stopRefused": "未停止任何进程:此命令来自桌面托管的 Avibe Runtime,而正在运行的 {part} 不属于该 Runtime({reason})。请从启动它的 Avibe 停止它。",- "restartRefused": "未重启任何进程:此命令来自桌面托管的 Avibe Runtime,而正在运行的 {part} 不属于该 Runtime({reason})。请从启动它的 Avibe 重启它。"+ "backendUpgrade": "此 Codex 后端属于旧版 Avibe 桌面 Runtime,无法原地更新。请重新打开当前桌面应用,将其安装为私有后端。"},"cliHealth": {"installReadbackFailed": "安装程序已结束,但所选 CLI 仍然缺失或无法运行,尚未验证安装成功。请修复后重试。",@@ -1288,26 +1159,6 @@"oauth_time_mismatch_body": "Avibe Cloud 已完成登录,但这台机器因为本地时间不同步而拒绝了安全令牌。请校准系统时间后重试。","invalid_oauth_nonce_title": "无法验证此次登录","invalid_oauth_nonce_body": "本次登录未能通过验证,为保护你的账户已中止。请重新登录以继续。"- },- "cli": {- "pairHelpEpilog": "使用说明:\n 已有配对密钥时,可直接使用此命令。\n 如需引导式设置,请运行 `vibe remote`。\n 不提供密钥时,命令会继续本机可恢复的配对;没有待处理操作时会提示输入密钥。\n 要替换结果不确定的待处理配对,请明确提供新密钥和原本使用的后端地址。\n 配对会保存远程访问配置,然后自动启动托管隧道。\n 配对密钥只能使用一次;若配对失败,请在 Avibe Cloud 控制台获取新密钥。\n\n示例:\n vibe remote\n vibe remote pair vrp_abc123\n vibe remote pair --device-name \"Mac Studio\"\n vibe remote pair --backend-url https://avibe.bot",- "localWriteUnavailableTitle": "远程访问设置已在联系 Avibe Cloud 前停止。",- "localWriteUnavailableBody": "本地配置无法可靠保存配对信息,因此没有消耗配对密钥。",- "saveFailedAfterRedeemTitle": "云端已完成配对,但本地保存失败。",- "orphanedBinding": "孤立绑定:实例 {instance_id}(设备 {device_name})。",- "recoveryRetained": "已兑换的凭据仍保存在本机,不需要新的配对密钥。",- "retryAfterLocalFix": "修复本地配置问题后运行:",- "recoveryInvalid": "已保存的配对恢复记录无效,无法重放。",- "recoveryUnavailable": "本地配对恢复无法启动,没有消耗新的配对密钥。",- "recoveryNotReady": "配对尚无可靠保存的响应,可能仍在运行,也可能已消耗密钥。无密钥重试无法恢复此结果。",- "recoveryRevoked": "已保存的配对恢复记录已被本地解绑操作作废。",- "recoveryIndeterminate": "配对结果不确定,或已被本地后续操作取代,无法保证存在可恢复的响应;不要重复使用已提交的密钥。",- "replacePendingPairing": "先检查云端控制台,并确认没有仍在进行的配对。若要明确替换待处理操作,请将以下命令中的占位符替换为新密钥和原本要使用的后端地址(默认后端为 https://avibe.bot):",- "retirementFailed": "配对已应用,但恢复记录未能清理。请不要更换密钥并重试。",- "failedClaimCleanup": "本次配对失败,尚未应用。修复本地存储后,不提供密钥重试,以清理失败操作的记录。",- "failedClaimUnrecorded": "本次配对失败,尚未应用,且无法记录清理状态。修复本地存储后,请向 'vibe remote pair' 显式提供新的配对密钥;无密钥重试无法恢复此结果。",- "failedClaimRetired": "失败的配对记录已清理。获取新的配对密钥后,运行以下命令安全输入:",- "retryPairCommand": "使用以下命令重试本地配对恢复:"}},"turn": {@@ -1322,39 +1173,7 @@"runtime": {"prepare": {"prepared": "Show Runtime 已准备完成。",- "skipped": "Show Runtime 准备已跳过:{reason}",- "failed": "Show Runtime 准备失败:{reason}",- "unsupportedSource": "Show Runtime 准备失败:{reason}。请移除 VIBE_SHOW_RUNTIME_SOURCE 以使用随 Avibe 发布的运行时,或将 VIBE_SHOW_RUNTIME_BIN 指向你自行构建的运行时。",- "modelHubEngineSkipped": "Model Hub 引擎:已跳过({reason})。",- "modelHubEngineInstalled": "Model Hub 引擎已安装。",- "modelHubEngineReady": "Model Hub 引擎已就绪。",- "modelHubEngineNotReady": "Model Hub 引擎尚未就绪:{reason}",- "ripgrepInstalled": "ripgrep 已安装。",- "ripgrepReady": "ripgrep 已就绪。",- "ripgrepNotReady": "ripgrep 尚未就绪:{reason}",- "cloudflaredInstalled": "cloudflared 已安装。",- "cloudflaredReady": "cloudflared 已就绪。",- "cloudflaredNotReady": "cloudflared 尚未就绪:{reason}"- },- "clean": {- "commandHelp": "清理过期的 Show、Git、Model Hub、tmux、ripgrep 和 cloudflared 运行时安装与归档;任一清理失败时以非零状态退出。",- "dryRunHelp": "仅报告可清理的归档与缓存条目,不删除任何内容。",- "wouldRemoveItems": "将清理 {count} 项 Show Runtime 缓存。",- "wouldRemoveArchives": "将清理 {count} 个已下载的 Show Runtime 归档({size})。",- "consumerWouldRemoveItems": "将清理 {count} 项 {consumer} 缓存。",- "consumerWouldRemoveArchives": "将清理 {count} 个已下载的 {consumer} 归档({size})。",- "removedItems": "已清理 {count} 项 Show Runtime 缓存。",- "removedArchives": "已清理 {count} 个已下载的 Show Runtime 归档({size})。",- "consumerRemovedItems": "已清理 {count} 项 {consumer} 缓存。",- "consumerRemovedArchives": "已清理 {count} 个已下载的 {consumer} 归档({size})。",- "consumerPreviewFailed": "{consumer} 缓存预览失败({reason});可能仍有过期条目。",- "consumerFailed": "{consumer} 清理失败({reason});过期条目仍保留。",- "consumerArchivesPartial": "{consumer} 归档清理仅部分完成({reason});有 {failed} 个归档无法清理。",- "consumerArchivesSkipped": "{consumer} 归档清理已跳过({reason});可能仍有过期归档。",- "partiallyRemoved": " 有 {failed} 个归档无法删除;请检查权限与 Avibe 日志。",- "skipped": "归档清理已跳过({reason});可能仍有过期归档。请在正在运行的安装或清理结束后重试。",- "removalFailed": "有 {failed} 个归档无法删除;过期归档仍保留。请检查运行目录权限与 Avibe 日志。",- "skippedInspection": "归档清理无法检查缓存({reason});可能仍有过期归档。请检查运行目录权限与 Avibe 日志。"+ "failed": "Show Runtime 准备失败:{reason}"},"doctor": {"archiveCacheReclaimable": "Show Runtime 归档缓存中有 {count} 个可回收归档({size});当前与回滚归档会被保留。",@@ -1374,15 +1193,6 @@"repairPostVerificationFailed": "Show Runtime 准备已完成,但无法验证是否可启动:{detail}","repairPrepareFailed": "Show Runtime 准备失败:{detail}","repairLegacyArchiveUnavailable": "打包的 Show Runtime 清单不可用,旧版上游归档地址也没有发布资产。请升级或重新安装官方 Avibe 软件包,或移除过期的 runtime 来源覆盖配置。"- },- "stop": {- "opencodeStopped": "OpenCode 服务已停止",- "serviceFailed": "错误:Avibe 服务未能停止;已保留 pidfile 并中止。",- "uiFailed": "错误:Avibe UI 未能停止;已保留 pidfile 并中止。",- "installerFailed": "错误:桌面后端安装进程未能停止。",- "opencodeFailed": "错误:此 Runtime 启动的 OpenCode 服务未能停止。",- "unknownFailed": "错误:此 Runtime 启动的一个进程无法识别,已保留运行。",- "remoteAccessFailed": "错误:远程访问隧道无法停止。"}},"doctor": {@@ -1764,44 +1574,6 @@"dryTmux": "将安装或刷新清单固定的 tmux runtime。"}},- "data": {- "helpCommand": "查看 Avibe 数据,或执行显式的 trace 保留维护",- "helpDescription": "通过受保护的只读 SQL 查看本地 Avibe SQLite 状态,或执行显式维护:`query` 为只读;`retention --run` 会删除旧的内部 trace 事件并可能压实数据库。",- "skillUsage": {- "ownerRequired": "需要实例管理者或所有者权限。",- "confirmationRequired": "清除 Skill 统计需要使用 --yes 确认。",- "clearRequired": "--yes 必须与 --clear 一起使用。",- "helpCommand": "查看或清除本地 Skill 统计(实例管理者或所有者)",- "helpClear": "清除 Skill 事件及每日统计。",- "helpYes": "确认清除 Skill 统计。"- },- "retention": {- "invalidDays": "--days 必须在 {minimum} 到 {maximum} 之间;拒绝运行而不是静默收窄窗口。",- "helpCommand": "查看或执行内部 agent trace 事件的有界保留",- "helpDescription": "agent_events trace 保留策略的状态与手动控制:超过保留窗口的 tool_call trace 会被删除;聊天消息、非 trace 事件与较新的 trace 永远不会被触碰。",- "helpRun": "立即执行一次保留清理(绕过每日节流,仍遵守租约)。",- "helpDays": "以天为单位的保留窗口覆盖值(默认:配置值,当前为 {current})。",- "helpCompact": "在安全时同时物理压实数据库(VACUUM);蕴含 --run。默认关闭:VACUUM 会持有数据库唯一写锁并可能阻塞运行中服务的写入;请在维护窗口或服务停止时执行。",- "configRecovered": "Avibe 配置无法读取(处于恢复默认状态);保留策略未知。如需删除,请使用显式 --days 窗口重新运行。",- "compactionReasonCheckpointBusy": "数据库正被并发读写占用",- "compactionReasonFreeSpace": "磁盘空闲空间不足以安全重写数据库",- "compactionReasonOther": "当前不满足安全压实条件",- "error": "trace 保留命令执行失败:{error}",- "plan": "有 {count} 条早于 {days} 天的 trace 记录待清理(载荷文本约 {size})。",- "lastRun": "上次保留清理:{at},删除 {rows} 条。",- "neverRun": "尚未执行过保留清理。",- "disabled": "trace 保留策略已在运行配置中关闭;每日任务不会删除任何内容。",- "compaction": "数据库内部当前可回收空间:{size}。",- "ran": "本次保留清理删除了 {rows} 条 trace 记录。",- "compacted": "数据库已压实;向磁盘归还 {size}。",- "compactionDeferred": "压实已推迟({reason});行已删除,磁盘空间将在下次安全通过时归还。",- "compactionSkipped": "压实已跳过:可回收空间过小。",- "leaseLost": "本次运行将租约丢失给了另一个保留清理;删除中途停止且未记录完成。请在另一运行结束后重试。",- "notDue": "保留清理在最近一天内已运行过,无需重复。",- "busy": "另一个保留清理正在运行,请稍后重试。",- "cancelled": "保留清理已在批次边界停止;未记录完成状态。"- }- },"vibeyAgent": {"error": {"refusal": "模型拒绝回答这个请求。",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex ef96474a4..83055e0b9 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -8380,11 +8380,12 @@ async def wechat_qr_login_poll():@app.route("/api/doctor", methods=["POST"])def doctor_post():+ from core.services import settings as settings_servicefrom vibe.cli import _doctorpayload = request.json or {}deep = _parse_explicit_bool(payload.get("deep")) or _parse_explicit_bool(request.args.get("deep"))- result = _doctor(deep=deep)+ result = _doctor(deep=deep, language=settings_service.load_config_or_default().language)return jsonify(result)