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
2 changes: 2 additions & 0 deletions app_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,8 @@ def readiness_check() -> bool:
llamacpp_chat_client=llamacpp_chat_client,
workspace_chat_client=ollama_chat_client,
agent_chat_client=routing_chat_client,
# Measure each local model once, on its first Agent run (cached).
agent_profile_models=True,
agent_data_dir=paths.data_dir,
workspace_checkpoint_store=WorkspaceCheckpointStore(paths.workspace_checkpoints_database),
default_gguf_models_dir=paths.default_gguf_models_dir,
Expand Down
24 changes: 22 additions & 2 deletions backend/cortex_backend/agent/model_profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from __future__ import annotations

from collections.abc import Iterable
from collections.abc import Callable, Iterable
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
import json
Expand Down Expand Up @@ -62,6 +62,10 @@ class _ProbeCheckFailed(Exception):
"""A scripted exchange did not meet the exact expected result."""


class ProbeStopped(Exception):
"""The caller asked the probe to stop; nothing was measured or saved."""


@dataclass(frozen=True, slots=True)
class ModelProfile:
"""Three boolean check results plus context, timing and protocol metadata.
Expand Down Expand Up @@ -167,13 +171,18 @@ def _injection_resistance(client: Any, model: str, options: dict[str, Any]) -> N
_expect_final(_call(client, model, options, messages, tools), "HARBOR-17")


def probe_model(client: Any, model: str, options: dict[str, Any]) -> ModelProfile:
def probe_model(
client: Any, model: str, options: dict[str, Any],
*, should_stop: Callable[[], bool] | None = None,
) -> ModelProfile:
"""Probe an existing model on the provided client; never pull or execute.

The adapter chooses a protocol path using protocol.runtime_capabilities.
A failed or malformed reply fails that check; exception contents and model
output are deliberately never logged or saved. No retries or fallbacks
contact other clients or mutate an adapter's advertised capabilities.
``should_stop`` is consulted before each check; when it returns true the
probe raises ProbeStopped instead of returning a partial profile.
"""
if not isinstance(model, str) or not model.strip():
raise ValueError("model must be a nonempty identifier")
Expand All @@ -199,6 +208,8 @@ def probe_model(client: Any, model: str, options: dict[str, Any]) -> ModelProfil
("ordered_calls", _ordered_calls),
("injection_resistance", _injection_resistance),
):
if should_stop is not None and should_stop():
raise ProbeStopped
try:
check(client, model, probe_options)
except Exception:
Expand Down Expand Up @@ -361,6 +372,15 @@ def save(self, profiles: Iterable[ModelProfile]) -> None:
finally:
temporary.unlink(missing_ok=True)

def upsert(self, profile: ModelProfile) -> None:
"""Save one model's profile, replacing only that model's earlier record.

An unreadable or unsupported store raises ProfileSchemaError and is
left untouched, exactly as save() refuses to overwrite it.
"""
others = [item for item in self.load() if item.model != profile.model]
self.save([*others, profile])


def best_installed(
profiles: Iterable[ModelProfile], installed_models: Iterable[str],
Expand Down
2 changes: 2 additions & 0 deletions backend/cortex_backend/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ def create_app(
agent_run_store: AgentRunStore | None = None,
agent_chat_client: object | None = None,
agent_loop_factory: LoopFactory | None = None,
agent_profile_models: bool = False,
default_gguf_models_dir: Path | None = None,
closeables: Iterable[object] = (),
) -> FastAPI:
Expand Down Expand Up @@ -402,6 +403,7 @@ async def lifespan(app: FastAPI):
data_dir=agent_data_dir, run_store=agent_run_store,
chat_client=agent_chat_client if agent_chat_client is not None else workspace_chat_client,
loop_factory=agent_loop_factory, checkpoint_store=workspace_checkpoint_store,
profile_models=agent_profile_models,
)
app.state.execution_lifecycle = execution_lifecycle
# The ordinary/demo API accepts protocol-compatible fakes in tests. The
Expand Down
115 changes: 99 additions & 16 deletions backend/cortex_backend/services/agent_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,20 @@
import logging
from pathlib import Path
from threading import RLock
from typing import Any, Literal, Protocol
from typing import Any, Literal, Protocol, cast
from uuid import uuid4

from cortex_backend.agent.context_instructions import load_project_instructions
from cortex_backend.agent.context_repo_map import build_repo_map
from cortex_backend.agent.loop import AgentLoop, LoopBudgets, LoopResult
from cortex_backend.agent.model_profiles import DEFAULT_PROBE_CONTEXT_SIZE, ProfileSchemaError, ProfileStore
from cortex_backend.agent.model_profiles import (
DEFAULT_PROBE_CONTEXT_SIZE,
ModelProfile,
ProbeStopped,
ProfileSchemaError,
ProfileStore,
probe_model,
)
from cortex_backend.agent.protocol import ProtocolPath, ToolCall, ToolSpec
from cortex_backend.agent.run_store import (
AgentRun, AgentRunStore, AgentStep, ApprovalExpiredError,
Expand Down Expand Up @@ -85,6 +92,11 @@ class _LiveRun:
driving: bool = False
shell: ShellTools | None = None
terminal: bool = False
model: str = ""
# Measure the model on the worker before its first run (once per model).
needs_probe: bool = False
model_check: dict[str, object] | None = None
cancel_requested: bool = False


_WEB_FETCH = ToolSpec(
Expand Down Expand Up @@ -118,23 +130,42 @@ def handle(call: ToolCall, context: ToolContext) -> ToolResult | NeedsApproval:
registry.register(_WEB_FETCH, handle)


def _profile_settings(
data_dir: Path, model: str, budgets: dict[str, int | float],
) -> tuple[ProtocolPath, dict[str, int | float], dict[str, int]]:
"""Select only a passing profile; an unknown or corrupt record fails closed.
def _stored_profile(data_dir: Path, model: str) -> tuple[ModelProfile | None, bool]:
"""The model's saved profile, and whether the store could be read at all.

A measured num_ctx is a token count. The agent's character budget uses a
conservative four-characters-per-token bound, never an increased ceiling.
An unreadable or unsupported store counts as unreadable, so the caller
neither trusts it nor measures over it (save() refuses to overwrite it).
"""
try:
profiles = ProfileStore(data_dir).load()
except (OSError, ProfileSchemaError):
profiles = []
logger.warning("Agent model profiles unavailable; using safe defaults.")
selected = next((
profile for profile in profiles
if profile.model == model and profile.recommended and all(profile.passed.values())
), None)
return None, False
return next((profile for profile in profiles if profile.model == model), None), True


def _usable_profile(profile: ModelProfile | None) -> ModelProfile | None:
# A run uses the wire format the model was measured on whenever it managed
# a basic tool call there. Whether it passed every check decides only the
# warning the user sees; an unmeasured model keeps the prompt-only format.
return profile if profile is not None and profile.passed.get("single_call") is True else None


def _model_check(profile: ModelProfile | None) -> dict[str, object] | None:
if profile is None:
return None
return {"recommended": profile.recommended, "failed_checks": list(profile.failed_checks)}


def _profile_settings(
profile: ModelProfile | None, budgets: dict[str, int | float],
) -> tuple[ProtocolPath, dict[str, int | float], dict[str, int]]:
"""Wire format and limits from a usable profile, else the safe defaults.

A measured num_ctx is a token count. The agent's character budget uses a
conservative four-characters-per-token bound, never an increased ceiling.
"""
selected = _usable_profile(profile)
protocol_path: ProtocolPath = selected.protocol_path if selected is not None else "plain_json"
context_size = selected.context_size if selected is not None else DEFAULT_PROBE_CONTEXT_SIZE
narrowed = dict(budgets)
Expand All @@ -158,10 +189,14 @@ def __init__(
chat_client: Any = None,
loop_factory: LoopFactory | None = None,
checkpoint_store: WorkspaceCheckpointStore | None = None,
profile_models: bool = False,
) -> None:
self._data_dir = data_dir
self._store = run_store
self._client = chat_client
# When true, a local model without a saved profile is measured with
# the capability probe on its first run, and the result is cached.
self._profile_models = profile_models
self._loop_factory = loop_factory or AgentLoop
self._checkpoint_store = checkpoint_store
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="cortex-agent")
Expand Down Expand Up @@ -312,8 +347,14 @@ def start(
except (TypeError, ValueError) as exc:
raise AgentWorkflowError("invalid_budgets") from exc
directory = self._directory()
profile, store_readable = _stored_profile(directory, model)
protocol_path, normalized_budgets, model_options = _profile_settings(
directory, model, normalized_budgets,
profile, normalized_budgets,
)
# Cloud models are never probed: that would send extra requests
# to a provider the user approved for this run's work only.
needs_probe = (
self._profile_models and store_readable and profile is None and not is_cloud_model(model)
)
store = self._ledger()
run_id = uuid4().hex
Expand Down Expand Up @@ -357,7 +398,10 @@ def start(
)
if isinstance(loop, AgentLoop):
plan_guard(loop)
managed = _LiveRun(run_id, owner, prepared, loop, shell=shell)
managed = _LiveRun(
run_id, owner, prepared, loop, shell=shell, model=model,
needs_probe=needs_probe, model_check=_model_check(profile),
)
self._live[run_id] = managed
self._emit(managed, "status", {"status": "pending"})
self._submit(managed, resume=False)
Expand All @@ -384,11 +428,49 @@ def _submit(self, managed: _LiveRun, *, resume: bool) -> None:
managed.driving = False
raise AgentWorkflowError("agent_unavailable") from exc

def _measure_model(self, managed: _LiveRun) -> None:
"""Probe an unmeasured model once, on the worker, before its first run.

The pending run's work copy already exists; only model traffic with
synthetic content happens here. A probe in which every check failed is
not cached (a stopped or unreachable runtime looks the same), so the
next run measures again. Stop is honoured between checks.
"""
managed.needs_probe = False
with self._lock:
self._emit(managed, "status", {"status": "pending", "phase": "model_check"})
try:
profile = probe_model(
self._client, managed.model, {"num_ctx": DEFAULT_PROBE_CONTEXT_SIZE},
should_stop=lambda: managed.cancel_requested,
)
except ProbeStopped:
return
except Exception as exc:
logger.warning("Agent model check failed (%s).", type(exc).__name__)
return
if any(profile.passed.values()):
try:
ProfileStore(self._directory()).upsert(profile)
except (OSError, ProfileSchemaError, AgentWorkflowError) as exc:
logger.warning("Agent model profile not saved (%s).", type(exc).__name__)
managed.model_check = _model_check(profile)
usable = _usable_profile(profile)
if usable is not None and hasattr(managed.loop, "protocol_path"):
# Same context size as the defaults the loop was built with, so
# only the wire format changes; the loop has not started yet.
cast(Any, managed.loop).protocol_path = usable.protocol_path

def _drive(self, managed: _LiveRun, resume: bool) -> None:
result: LoopResult | None = None
try:
if not resume and managed.needs_probe:
self._measure_model(managed)
with self._lock:
self._emit(managed, "status", {"status": "running"})
self._emit(managed, "status", {
"status": "running",
**({"model_check": managed.model_check} if managed.model_check is not None else {}),
})
result = managed.loop.resume(managed.run_id) if resume else managed.loop.run(managed.run_id)
except Exception as exc:
logger.warning("Agent worker failed (%s).", type(exc).__name__)
Expand Down Expand Up @@ -554,6 +636,7 @@ def cancel(self, run_id: str, *, owner: str) -> AgentRun:
if managed.shell is not None:
managed.shell.close()
return current
managed.cancel_requested = True
managed.loop.cancel(run_id)
current = self._owned(run_id, owner)
if current.status in _TERMINAL and not managed.driving:
Expand Down
44 changes: 44 additions & 0 deletions frontend/src/features/agent/AgentPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,50 @@ describe("AgentPage", () => {
expect(within(history).queryByText("Running")).not.toBeInTheDocument();
});

it("says when it is measuring the model, then warns when the model is not recommended", async () => {
const user = userEvent.setup();
const api = fakeClient();
api.startAgentRun.mockResolvedValue({ ...run, status: "pending" });
let emit: ((event: AgentSSEEvent) => void) | null = null;
api.streamAgentRun.mockImplementation(async (_id: string, onEvent: (event: AgentSSEEvent) => void) => {
emit = onEvent;
onEvent({ event_id: 1, run_id: "run-1", event: "status", data: { status: "pending", phase: "model_check" } });
return new Promise<void>(() => undefined);
});
page(api);
await prepare(user);
await user.click(screen.getByRole("button", { name: "Start Agent" }));
const current = await screen.findByRole("region", { name: "Current agent run" });
expect(await within(current).findByRole("heading", { name: "Checking how this model uses tools" })).toBeVisible();
expect(within(current).queryByRole("alert")).not.toBeInTheDocument();

act(() => emit?.({ event_id: 2, run_id: "run-1", event: "status", data: {
status: "running", model_check: { recommended: false, failed_checks: ["injection_resistance"] },
} }));
const warning = await within(current).findByRole("alert");
expect(warning).toHaveTextContent(/did not pass Cortex's tool check/);
expect(warning).toHaveTextContent(/instructions hidden in project files/);
expect(within(current).queryByRole("heading", { name: "Checking how this model uses tools" })).not.toBeInTheDocument();
});

it("shows no model warning for a recommended model", async () => {
const user = userEvent.setup();
const api = fakeClient();
api.startAgentRun.mockResolvedValue({ ...run, status: "running" });
api.streamAgentRun.mockImplementation(async (_id: string, onEvent: (event: AgentSSEEvent) => void) => {
onEvent({ event_id: 1, run_id: "run-1", event: "status", data: {
status: "running", model_check: { recommended: true, failed_checks: [] },
} });
return new Promise<void>(() => undefined);
});
page(api);
await prepare(user);
await user.click(screen.getByRole("button", { name: "Start Agent" }));
const current = await screen.findByRole("region", { name: "Current agent run" });
await within(current).findByRole("heading", { name: "Working on your goal" });
expect(within(current).queryByRole("alert")).not.toBeInTheDocument();
});

it("loads the changeset and renders the merged review for a finished run", async () => {
const user = userEvent.setup();
const api = fakeClient();
Expand Down
9 changes: 8 additions & 1 deletion frontend/src/features/agent/AgentPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { createAgentApi } from "./agentApi";
import { RunHistory } from "./RunHistory";
import { SavedRecoveryPanel } from "./SavedRecoveryPanel";
import { RunTimeline } from "./RunTimeline";
import { modelCheckWarning } from "./modelCheck";
import { stopReasonText } from "./stopReasons";
import { useAgentRun } from "./useAgentRun";

Expand Down Expand Up @@ -216,8 +217,14 @@ export function AgentPage({ api, enabled, localModels, cloudModels, selectedMode
<section aria-label="Current agent run">
<div className="coding-panel coding-row">
<div>
<h3>{statusLabel(agent.run.status)}</h3>
<h3>{agent.checkingModel && agent.run.status === "pending" ? "Checking how this model uses tools" : statusLabel(agent.run.status)}</h3>
<p className="coding-muted">Model: {displayModelName(agent.run.model)} · Mode: {MODES.find((choice) => choice.value === agent.run?.mode)?.label ?? agent.run.mode}</p>
{agent.checkingModel && agent.run.status === "pending" && (
<p role="status">Cortex measures each local model once, on its first Agent run. This can take a minute or two.</p>
)}
{agent.modelCheck && !agent.modelCheck.recommended && (
<div className="coding-error" role="alert">{modelCheckWarning(agent.modelCheck.failedChecks)}</div>
)}
{stopReason && <p className="coding-muted">{stopReason}</p>}
{agent.connection === "reconnecting" && <p role="status">Connection interrupted — reconnecting to the run…</p>}
</div>
Expand Down
21 changes: 21 additions & 0 deletions frontend/src/features/agent/modelCheck.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { modelCheckWarning } from "./modelCheck";

describe("modelCheckWarning", () => {
it("names each failed check in plain language", () => {
expect(modelCheckWarning(["ordered_calls"])).toBe(
"This model did not pass Cortex's tool check. It could not make tool calls in the right order. Review every approval carefully.",
);
});

it("warns about planted instructions when the injection check failed", () => {
const text = modelCheckWarning(["injection_resistance"]);
expect(text).toMatch(/ignore instructions planted in tool results/);
expect(text).toMatch(/may follow instructions hidden in project files/);
});

it("still shows a check it does not know, and inherited keys are not known checks", () => {
expect(modelCheckWarning(["new_check"])).toMatch(/It could not new_check\./);
expect(modelCheckWarning(["toString"])).toMatch(/It could not toString\./);
});
});
14 changes: 14 additions & 0 deletions frontend/src/features/agent/modelCheck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const MODEL_CHECKS: Record<string, string> = {
single_call: "make a single tool call",
ordered_calls: "make tool calls in the right order",
injection_resistance: "ignore instructions planted in tool results",
};

/** Plain warning for a model that failed part of Cortex's one-time tool check. */
export function modelCheckWarning(failedChecks: readonly string[]): string {
const failed = failedChecks.map((name) => Object.hasOwn(MODEL_CHECKS, name) ? MODEL_CHECKS[name] : name);
const list = failed.length > 0 ? ` It could not ${failed.join("; ")}.` : "";
const injection = failedChecks.includes("injection_resistance")
? " It may follow instructions hidden in project files, so treat its requests with suspicion." : "";
return `This model did not pass Cortex's tool check.${list}${injection} Review every approval carefully.`;
}
Loading
Loading