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
4 changes: 4 additions & 0 deletions agent_core/core/impl/llm/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,10 @@ def _context_limits(self) -> Tuple[int, Optional[int]]:

return get_context_window(), None

def context_window(self) -> int:
"""Context window, in tokens, of the model this interface serves."""
return self._context_limits()[0]

def _input_budget(self, reasoning: Optional[ReasoningDecision]) -> int:
"""Input tokens a request with this reasoning decision may carry.

Expand Down
4 changes: 4 additions & 0 deletions agent_core/core/protocols/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ class LLMInterfaceProtocol(Protocol):
temperature: float
max_tokens: int

def context_window(self) -> int:
"""Context window, in tokens, of the model this interface serves."""
...

async def generate_response_async(
self,
user_prompt: str,
Expand Down
57 changes: 41 additions & 16 deletions app/agent_app/agent_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import json
import time
import urllib.parse
import urllib.request
from typing import Any, Dict, List, Optional

Expand All @@ -32,25 +33,49 @@
_CACHE: Dict[str, tuple] = {}
_TTL_SECONDS = 300
_TIMEOUT_SECONDS = 2.0
# Read at most this much of an answer, whatever the app sends.
_MAX_DESCRIBE_BYTES = 1 << 20


def _describe(base_url: str) -> Optional[Dict[str, Any]]:
"""Fetch (and cache) the app's data model. None when the app is down."""
class _NoRedirect(urllib.request.HTTPRedirectHandler):
"""The answer must come from the registered address itself."""

def redirect_request(self, req, fp, code, msg, headers, newurl):
return None


def describe(base_url: str) -> Optional[Dict[str, Any]]:
"""The app's A2APP describe document, cached for _TTL_SECONDS.

The one reader of describe for the agent's prompt and for references.
`base_url` is the manager-registered address (backend_url, else url),
never a user-supplied one. Apps run locally, so no proxy is used. None
when the app is down, the address is not http(s), the answer redirects,
is larger than _MAX_DESCRIBE_BYTES or is not a JSON object.
"""
base_url = base_url.rstrip("/")
cached = _CACHE.get(base_url)
if cached is not None and time.time() - cached[0] < _TTL_SECONDS:
return cached[1]
try:
request = urllib.request.Request(
f"{base_url}/api/_a2app/describe", headers={"User-Agent": "CraftBot"}
)
with urllib.request.urlopen(request, timeout=_TIMEOUT_SECONDS) as response:
data = json.loads(response.read().decode("utf-8"))
_CACHE[base_url] = (time.time(), data)
return data
except Exception as e:
logger.debug(f"[AGENT_VIEW] describe unavailable at {base_url}: {e}")
_CACHE[base_url] = (time.time(), None)
return None
data = None
if urllib.parse.urlsplit(base_url).scheme in ("http", "https"):
try:
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({}), _NoRedirect()
)
request = urllib.request.Request(
f"{base_url}/api/_a2app/describe", headers={"User-Agent": "CraftBot"}
)
with opener.open(request, timeout=_TIMEOUT_SECONDS) as response:
raw = response.read(_MAX_DESCRIBE_BYTES + 1)
if len(raw) > _MAX_DESCRIBE_BYTES:
raise ValueError(f"answer exceeds {_MAX_DESCRIBE_BYTES} bytes")
parsed = json.loads(raw.decode("utf-8"))
data = parsed if isinstance(parsed, dict) else None
except Exception as e:
logger.debug(f"[AGENT_VIEW] describe unavailable at {base_url}: {e}")
_CACHE[base_url] = (time.time(), data)
return data


def _type_label(spec: Dict[str, Any]) -> str:
Expand All @@ -73,7 +98,7 @@ def schema_block(base_url: str, max_chars: int = 2000) -> Optional[str]:
Read-only and server-managed fields are omitted: the agent cannot write
them, so naming them only invites it to try.
"""
described = _describe(base_url)
described = describe(base_url)
if not described:
return None
entities = described.get("entities") or {}
Expand Down Expand Up @@ -117,7 +142,7 @@ def operations_block(base_url: str, max_chars: int = 6000) -> Optional[str]:
and a trailing `!` when it is destructive, e.g.
notes: list, get(name), create(title), update(name), delete(name)!
"""
described = _describe(base_url)
described = describe(base_url)
if not described:
return None
groups: Dict[str, List[tuple]] = {}
Expand Down
5 changes: 3 additions & 2 deletions app/references/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ separate tenant/ACL system.
chunk includes its messageId, speaker, timestamp and character offset. Clearing
a source invalidates its cursors.
- `AgentAppReferenceProvider` captures allowlisted project metadata. For a running
app it optionally reads bounded schema/operation declarations from the registered
loopback describe endpoint. It does not follow redirects, launch apps, inspect
app it optionally reads bounded schema/operation declarations from the describe
endpoint at the manager-registered address (`backend_url`, else `url`), the same
one the agent's app note uses. It does not follow redirects, launch apps, inspect
their build transcripts, read records/files/secrets, or execute operations.
- `read_reference(kind, target_id, cursor?)` is a core read-only action. Its trusted
`_session_id` must already contain a persisted attachment of that source. Every
Expand Down
37 changes: 16 additions & 21 deletions app/references/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

import asyncio
import json
import urllib.request

from app.agent_app import agent_view

from .service import ReferenceError, bounded

Expand Down Expand Up @@ -51,9 +52,11 @@ async def capture(
"type": project.project_type,
"status": project.status,
}
port = project.backend_port or project.port
if project.status == "running" and isinstance(port, int) and 0 < port < 65536:
described = await asyncio.to_thread(self._describe, port)
# The manager's registered address, as the agent's own app note uses
# (agent_base): external apps need not listen on 127.0.0.1:<port>.
base_url = project.backend_url or project.url
if project.status == "running" and base_url:
described = await asyncio.to_thread(self._describe, base_url)
data["schema"] = (
described if described is not None else "Schema unavailable"
)
Expand All @@ -68,24 +71,16 @@ async def capture(
}

@staticmethod
def _describe(port: int) -> dict | None:
"""Read only a registered loopback app; never follow redirects or fetch records."""

class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def _describe(base_url: str) -> dict | None:
"""Schema and operation declarations from the app's describe document.

The document comes from agent_view.describe, the same cached, bounded,
no-redirect reader the agent's own app note uses; this never fetches
records."""
result = agent_view.describe(base_url)
if result is None:
return None
try:
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({}), NoRedirect()
)
with opener.open(
f"http://127.0.0.1:{port}/api/_a2app/describe", timeout=2
) as response:
raw = response.read(65537)
if len(raw) > 65536:
return None
result = json.loads(raw)
# Keep schema/operation declarations only. Never forward arbitrary
# extra keys returned by an app's describe endpoint.
entities = result.get("entities") or {}
Expand Down Expand Up @@ -122,5 +117,5 @@ def redirect_request(self, req, fp, code, msg, headers, newurl):
if isinstance(op, dict) and not op.get("system")
],
}
except (OSError, ValueError, TypeError, AttributeError):
except (TypeError, AttributeError):
return None
32 changes: 26 additions & 6 deletions app/references/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,26 @@
EXCERPT_BYTES = 8192
TOTAL_BYTES = 32768
PAGE_BYTES = 24576
# Reference context may use this share of the model's window, within bounds.
CONTEXT_WINDOW_SHARE = 8
MIN_TOKEN_BUDGET = 128
MAX_TOKEN_BUDGET = 8192


def reference_token_budget(context_window: int | None) -> int:
"""Tokens reference context may use for a model with this window."""
if not context_window:
return MAX_TOKEN_BUDGET
return min(
MAX_TOKEN_BUDGET,
max(MIN_TOKEN_BUDGET, context_window // CONTEXT_WINDOW_SHARE),
)


def submission_message_id(destination: str, client_id: str) -> str:
"""Stable message id for one client submission (references or attachments)."""
return (
"reference:"
"submission:"
+ hashlib.sha256(json.dumps([destination, client_id]).encode()).hexdigest()
)

Expand Down Expand Up @@ -192,9 +207,12 @@ def render(snapshots: list[dict]) -> str:


def create_reference_service(
sessions=None, storage=None, apps=None
sessions=None, storage=None, apps=None, llm=None
) -> ReferenceService:
"""Composition root; adapters and actions reuse the existing application managers."""
"""Composition root; adapters and actions reuse the existing application managers.

The token budget follows the window of the model the agent actually runs
(model catalog first, settings.json only for an uncatalogued model)."""
from .providers import AgentAppReferenceProvider, SessionReferenceProvider

if sessions is None:
Expand All @@ -209,7 +227,10 @@ def create_reference_service(
from app.agent_app._state import get_agent_app_manager

apps = get_agent_app_manager()
from app.config import get_settings
if llm is None:
from agent_core.core.registry.llm import get_llm_interface_or_none

llm = get_llm_interface_or_none()
from agent_core.utils.token import count_tokens

def reference_tokens(text: str) -> int:
Expand All @@ -219,8 +240,7 @@ def reference_tokens(text: str) -> int:
# Tokenizer special-token literals are ordinary untrusted source text.
return len(text.encode("utf-8"))

window = (get_settings().get("model") or {}).get("context_window")
token_budget = min(8192, max(128, int(window) // 8)) if window else 8192
token_budget = reference_token_budget(llm.context_window() if llm else None)
return ReferenceService(
{
"session": SessionReferenceProvider(sessions, storage),
Expand Down
76 changes: 48 additions & 28 deletions app/ui_layer/adapters/browser_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -9607,8 +9607,9 @@ async def _handle_chat_message_with_attachments(
references: Optional[List[Dict[str, Any]]] = None,
ws=None,
) -> None:
"""Deduplicate reference retries before resolving sources or enqueueing."""
if not references or not client_id or not self._chat._storage:
"""Deduplicate retries of one client submission before resolving
sources, saving attachments or enqueueing."""
if not client_id or not self._chat._storage:
await self._submit_chat_context(
content, attachments, session_id, client_id, references, ws
)
Expand All @@ -9624,18 +9625,23 @@ async def _handle_chat_message_with_attachments(
self._chat._storage.get_message_by_id, session_id, key
)
except Exception:
await self._send_to(
ws,
{
"type": "message_rejected",
"data": {
"sessionId": session_id,
"clientId": client_id,
"error": "Chat storage is unavailable. Please retry.",
if not references:
# Attachment-only messages stay best-effort, as before:
# an unreadable store must not block them.
previous = None
else:
await self._send_to(
ws,
{
"type": "message_rejected",
"data": {
"sessionId": session_id,
"clientId": client_id,
"error": "Chat storage is unavailable. Please retry.",
},
},
},
)
return
)
return
if previous:
message = self._chat._stored_to_chat_message(previous)
message.client_id = client_id
Expand Down Expand Up @@ -9663,14 +9669,19 @@ async def _submit_chat_context(

accepted = False
try:
from app.references import create_reference_service

service = create_reference_service(
sessions=self._controller.agent.session_manager,
storage=self._chat._storage,
apps=self._agent_app_manager,
)
snapshots = await service.resolve(references or [], session_id)
from app.references import ReferenceService, create_reference_service

snapshots: List[Dict[str, Any]] = []
# Only a message that carries references depends on the reference
# service (and its model-window budget); attachments never do.
if references:
service = create_reference_service(
sessions=self._controller.agent.session_manager,
storage=self._chat._storage,
apps=self._agent_app_manager,
llm=self._controller.agent.llm,
)
snapshots = await service.resolve(references, session_id)
if snapshots and not content.strip():
content = "Referenced: " + ", ".join(r["label"] for r in snapshots)
processed_attachments: List[Attachment] = []
Expand Down Expand Up @@ -9749,7 +9760,8 @@ async def _submit_chat_context(
session_id=session_id,
client_id=client_id,
)
if snapshots and client_id:
if client_id:
# Deterministic per client submission, so a retry finds it.
from app.references.service import submission_message_id

user_message.message_id = submission_message_id(session_id, client_id)
Expand All @@ -9760,7 +9772,9 @@ async def _submit_chat_context(

# Combine content with attachment info for agent context
# (This is what the agent sees in the event stream - includes file paths)
agent_context = content + attachment_note + service.render(snapshots)
agent_context = (
content + attachment_note + ReferenceService.render(snapshots)
)

if not agent_context.strip():
return
Expand Down Expand Up @@ -9805,11 +9819,17 @@ async def _submit_chat_context(

from app.references import ReferenceError

error = (
str(e)
if isinstance(e, ReferenceError)
else "The message could not be submitted. Please retry."
)
if accepted:
# Saved and echoed already: resending the same submission is
# deduplicated, so only a new message reaches the agent.
error = (
"Your message was saved, but the agent could not start on "
"it. Send it again as a new message."
)
elif isinstance(e, ReferenceError):
error = str(e)
else:
error = "The message could not be submitted. Please retry."
if not accepted:
await self._send_to(
ws,
Expand Down
Loading