Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,28 @@ header shows `[small]` so you always know which
mode is live. Compare the profiles on your own endpoint with the eval
harness: `python -m korvid.evals --profile small` (see below).

## Follow mode

Small models rarely volunteer the screen tools (`open_describe`,
`open_logs`) — they call the data-returning reads and answer in text
while the TUI sits idle. Agent follow mode mirrors each successful
cluster read from a chat turn on screen, using the same mapping as MCP
follow mode: `list_resources` navigates the view, `get_resource` /
`get_events` / `diagnose_pod` open the describe view, and `get_logs`
opens the live log pane.

Follow is **on by default**. Disable it in `config.yaml`:

```yaml
agent:
follow: false # default: true
```

or toggle it live with `:ai follow off` / `:ai follow on` (bare
`:ai follow` flips the state). Mirroring never interrupts what you are
doing: failed reads (e.g. a 404) move nothing, and a mirror is refused
while an approval dialog or a describe screen you are reading is open.

## Agent eval harness

`korvid.evals` measures how well a model diagnoses cluster faults through
Expand Down
4 changes: 4 additions & 0 deletions src/korvid/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -915,6 +915,10 @@ async def fetch(
helm=_build_helm(config),
telepresence=_build_telepresence(config),
probe_traffic_manager=_make_traffic_manager_probe(kube),
# Agent follow mirrors route through the same serialized proxy: the
# built-in agent and concurrent MCP UI calls must never interleave
# (log-pane swaps and describes are not overlap-safe).
agent_follow_bridge=ui_proxy,
proposal_store=proposal_store,
save_topbar=lambda expanded: save_topbar_state(DEFAULT_CONFIG_PATH, expanded=expanded),
)
Expand Down
72 changes: 15 additions & 57 deletions src/korvid/agent/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
selection, they degrade with context length far below their advertised
windows, and 1-2 in-context demonstrations improve their multi-step tool
use more than longer instruction lists do (ReAct). The `small` profile
gives them a surface they can actually handle; `full` reproduces the
pre-profile wiring byte-for-byte so the frontier experience is unchanged.
gives them a surface they can actually handle; `full` keeps the frontier
tool surface and budgets unchanged (its prompt wording, like `small`'s,
lives in korvid.agent.prompts and evolves with observed failures).
"""

from __future__ import annotations
Expand All @@ -17,7 +18,14 @@
from dataclasses import dataclass
from typing import Any

from korvid.agent.runtime import MAX_HISTORY_CHARS, SYSTEM_PROMPT, UI_DRIVE_PROMPT
from korvid.agent.prompts import (
SMALL_SYSTEM_PROMPT,
SMALL_TOOL_DESCRIPTIONS,
SMALL_UI_PROMPT,
SYSTEM_PROMPT,
Comment thread
hellices marked this conversation as resolved.
UI_DRIVE_PROMPT,
)
from korvid.agent.runtime import MAX_HISTORY_CHARS
from korvid.tools.registry import agent_tool_schemas

PROFILE_NAMES = ("full", "small")
Expand All @@ -40,59 +48,9 @@
#: not a suggestion.
SMALL_MAX_TOOL_CALLS_PER_ITERATION = 1

#: Short role statement, explicit grounding rules, and ONE worked example
#: (question -> tool call -> result -> grounded answer) instead of the
#: longer frontier instruction list.
SMALL_SYSTEM_PROMPT = (
"You are korvid's Kubernetes diagnostic agent, embedded in a live TUI. "
"Use tools to inspect cluster state and cite evidence from tool results. "
"Call one tool at a time and wait for its result before deciding the "
"next step. Never invent resource names: use only names from the screen "
"context or from tool results. "
"Worked example — user: why does pod checkout-1 in namespace shop keep "
'restarting? -> you call diagnose_pod with {"pod": "checkout-1", '
'"namespace": "shop"} -> the result shows lastState terminated '
"exit=137 (OOMKilled) -> you answer: checkout-1 is OOMKilled (exit "
"code 137); its container exceeds the memory limit, so raise the limit "
"or reduce usage."
)

#: The full UI_DRIVE_PROMPT advertises all five UI tools; the small profile
#: offers only the two evidence-showing ones, and the model must never be
#: told about capabilities it was not offered.
SMALL_UI_PROMPT = (
"You can also show evidence on the user's screen: open_logs (show a "
"pod's live logs) and open_describe (show a resource's manifest and "
"events). These change nothing in the cluster. Keep your text concise; "
"the screen carries the detail."
)

#: The two evidence-showing UI tools the small profile offers are encoded
#: in the registry's `small_agent` surface (korvid.tools.registry).

#: Concise description overrides for schemas that are verbose in the full
#: profile — every request retransmits the schemas, so on a 4k-token
#: serving context the wording is a real cost (EasyTool). The effect is
#: measurable per endpoint with the #69 harness (`--profile small`).
_SMALL_DESCRIPTIONS: dict[str, str] = {
"diagnose_pod": (
"One-call diagnosis of a broken pod: container states, exit codes, "
"restart counts, failing conditions, Warning events, node/PVC "
"context, and log excerpts. Prefer this first when a pod is failing."
),
"list_operators": (
"List OLM operator packages and installed subscriptions with their status. Read-only."
),
"helm_list_releases": (
"List installed Helm releases with revision, status, chart and app "
"version. Read-only; parsed from cluster Secrets."
),
"open_logs": "Open the live log pane for a pod on the user's screen.",
"resize_pod": (
"Request an in-place CPU/memory resize of a running pod (Kubernetes "
"1.35+). Runs only after the user approves it in the TUI dialog."
),
}
#: All prompt wording — the full/small role statements, UI-drive variants,
#: and the small profile's concise tool-description overrides — lives in
#: korvid.agent.prompts; this module owns budgets and surface selection.


@dataclass(frozen=True)
Expand Down Expand Up @@ -128,7 +86,7 @@ def _trim(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
trimmed = copy.deepcopy(tools)
for tool in trimmed:
function = tool["function"]
override = _SMALL_DESCRIPTIONS.get(function["name"])
override = SMALL_TOOL_DESCRIPTIONS.get(function["name"])
if override is not None:
function["description"] = override
return trimmed
Expand Down
163 changes: 163 additions & 0 deletions src/korvid/agent/prompts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
"""Every system-prompt string the agent sends, in one place.

Prompt text is policy (what the model is told), the runtime is mechanism
(how the loop executes); keeping all wording here means a prompt change
never touches loop code, and the full/small variants (issue #71) sit side
by side instead of split across modules.

Composition (`compose_system_prompt`) lives here too: which clause is
appended is decided by the *armed tool set*, so the write/no-write and
UI-drive wording stays next to the rules that select it.
"""

from __future__ import annotations

from typing import Any

from korvid.tools.executor import UI_TOOL_NAMES, WRITE_TOOL_NAMES

SYSTEM_PROMPT = (
"You are korvid's Kubernetes diagnostic agent, embedded in a live TUI the "
"user is looking at right now. You explore the cluster only through the "
"tools provided in this session: you have no shell, you cannot run "
"kubectl or any command yourself, and you know nothing about this "
"cluster beyond tool results and the screen context. "
"Explore before you conclude: list resources to discover what exists, "
"then inspect the specific objects you found. "
"Cite evidence from tool results and never guess resource state. "
"Never invent resource names or namespaces — use only names from tool "
"results or the screen context, and keep each name paired with the "
"namespace it was listed in. A 404/NotFound means the name or namespace "
"is wrong: re-list to find the right one instead of retrying the same "
"call."
)

# Appended when no write tools are armed (readonly mode or writes not wired):
# instead of a bare refusal the agent offers the exact kubectl command.
NO_WRITE_PROMPT = (
"You have no write tools in this session: when the user asks you to "
"modify cluster state (scale, edit, delete, restart, apply), say write "
"actions are not enabled and give the exact kubectl command they can run "
"themselves instead."
)

# Appended only when the approval-gated write tools are armed. The armed
# tool names are prepended dynamically in `compose_system_prompt` so the
# instruction never omits a conditionally registered tool (resize_pod) or
# advertises one that was not offered.
WRITE_PROMPT = (
"These never execute directly: each call opens an "
"approval dialog in the TUI, and the operation runs only if the user "
"approves it with a keystroke. State clearly what you are about to "
"request and why before calling a write tool, and report the outcome "
"(approved, denied, expired, or failed) afterwards. Never retry a denied "
"or expired request unless the user explicitly asks: an expired request "
"means nobody answered the dialog, and reissuing it would keep reopening "
"approval dialogs the user is not acting on."
)

# Appended only when the runtime is armed with the UI-control tools, so the
# model is never told about capabilities the provider was not offered.
UI_DRIVE_PROMPT = (
"You can also drive the TUI itself: navigate (switch the resource view), "
"set_filter (narrow the visible rows), open_logs (show a pod's live logs "
"on screen), open_describe (show a resource's manifest and events), and "
"drill_down (from a deployment into its replicaset history, from a "
"replicaset into its pods, or from a helm release into its revision "
"history — following ownership). "
"Prefer showing evidence on screen with these tools while you narrate — "
"for example, when you find a failing pod, open its logs or describe view "
"so the user sees exactly what you see. These screen tools change nothing "
"in the cluster. Keep your text concise; the screen carries the detail."
)

#: Short role statement, explicit grounding rules, and ONE worked example
#: (question -> tool call -> result -> grounded answer) instead of the
#: longer frontier instruction list (issue #71).
SMALL_SYSTEM_PROMPT = (
"You are korvid's Kubernetes exploration agent, embedded in a live TUI. "
"You act only through the provided tools: no shell, no kubectl, no "
"cluster knowledge outside tool results. "
"Call one tool at a time and wait for its result before deciding the "
"next step. Never invent resource names or namespaces: use a name and "
"namespace pair given by the user or the screen context, or discover "
"one with list_resources first. Its rows start with "
"'namespace/name' — split that into the separate namespace and name "
"fields; never paste the combined value into either field. "
"A 404/NotFound means the name or namespace is wrong — "
"re-list instead of retrying. Cite evidence from tool results. "
"Worked example — user: why does pod checkout-1 in namespace shop keep "
'restarting? -> you call diagnose_pod with {"pod": "checkout-1", '
'"namespace": "shop"} -> the result shows lastState terminated '
"exit=137 (OOMKilled) -> you answer: checkout-1 is OOMKilled (exit "
"code 137); its container exceeds the memory limit, so raise the limit "
"or reduce usage."
)

#: The full UI_DRIVE_PROMPT advertises all five UI tools; the small profile
#: offers only the two evidence-showing ones, and the model must never be
#: told about capabilities it was not offered.
SMALL_UI_PROMPT = (
"You can also show evidence on the user's screen: open_logs (show a "
"pod's live logs) and open_describe (show a resource's manifest and "
"events). These change nothing in the cluster. Keep your text concise; "
"the screen carries the detail."
)

#: Concise tool-description overrides for the small profile — every request
#: retransmits the schemas, so on a 4k-token serving context the wording is
#: a real cost (EasyTool). The effect is measurable per endpoint with the
#: #69 harness (`--profile small`).
SMALL_TOOL_DESCRIPTIONS: dict[str, str] = {
"diagnose_pod": (
"One-call diagnosis of a broken pod: container states, exit codes, "
"restart counts, failing conditions, Warning events, node/PVC "
"context, and log excerpts. Prefer this first when a pod is failing."
),
"list_operators": (
"List OLM operator packages and installed subscriptions with their status. Read-only."
),
"helm_list_releases": (
"List installed Helm releases with revision, status, chart and app "
"version. Read-only; parsed from cluster Secrets."
),
"open_logs": "Open the live log pane for a pod on the user's screen.",
"resize_pod": (
"Request an in-place CPU/memory resize of a running pod (Kubernetes "
"1.35+). Runs only after the user approves it in the TUI dialog."
),
}


def compose_system_prompt(
tools: list[dict[str, Any]],
cluster_context: str | None,
*,
system_prompt: str | None = None,
ui_prompt: str | None = None,
) -> str:
"""System prompt for the armed tool set and detected environment.

Shared by ``AgentRuntime.__init__`` and ``retarget`` so a runtime that
survives a `:ctx` switch describes the *new* cluster and tool set, not
the one it was built against. Capability profiles (issue #71) swap the
role statement and the UI-drive instruction via
`system_prompt`/`ui_prompt`; the write/no-write clause stays
conditional on what is actually armed, whichever profile.
"""
prompt = system_prompt if system_prompt is not None else SYSTEM_PROMPT
if cluster_context:
# Detected-environment note (e.g. cloud provider, issue #30):
# placed right after the role statement so provider-specific
# requests are grounded before any tool instructions.
prompt = f"{prompt} {cluster_context}"
armed = {t.get("function", {}).get("name") for t in tools}
if armed & UI_TOOL_NAMES:
prompt = f"{prompt} {ui_prompt if ui_prompt is not None else UI_DRIVE_PROMPT}"
armed_writes = sorted(armed & WRITE_TOOL_NAMES)
if armed_writes:
names = ", ".join(armed_writes)
prompt = f"{prompt} You can request cluster writes with {names}. {WRITE_PROMPT}"
else:
prompt = f"{prompt} {NO_WRITE_PROMPT}"
return prompt
Loading
Loading