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
4 changes: 4 additions & 0 deletions app/agent_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2586,6 +2586,8 @@ async def _handle_chat_message(self, payload: Dict):
session_id = payload.get("session_id") or MAIN_SESSION_ID
session = self.session_manager.get(session_id)
if session is None:
if payload.get("strict_session"):
raise ValueError("The destination session is no longer available.")
logger.warning(
f"[CHAT] Message for unknown session {session_id} — delivering to main"
)
Expand Down Expand Up @@ -2719,6 +2721,8 @@ async def _handle_chat_message(self, payload: Dict):

except Exception as e:
logger.error(f"Error handling incoming message: {e}", exc_info=True)
if payload.get("strict_session"):
raise

async def _handle_external_event(self, payload: Dict) -> None:
"""
Expand Down
43 changes: 43 additions & 0 deletions app/data/action/reference_actions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Expand only explicitly attached reference sources, without changing them."""

from agent_core import action


@action(
name="read_reference",
description="Read more context from a session or agent_app explicitly referenced in this chat. Returns a bounded live page; use nextCursor to read older session messages. Does not run or modify the source.",
default=True,
action_sets=["core"],
parallelizable=True,
input_schema={
"kind": {
"type": "string",
"description": "session or agent_app",
"example": "session",
},
"target_id": {
"type": "string",
"description": "targetId from the reference context",
"example": "chat-123",
},
"cursor": {
"type": "string",
"description": "Optional nextCursor from an earlier page",
"example": "",
},
},
)
async def read_reference(input_data: dict) -> dict:
from app.references import ReferenceError, create_reference_service

session_id = input_data.get("_session_id")
if not session_id:
return {"error": "A destination session is required."}
try:
return await create_reference_service().read(
{"kind": input_data.get("kind"), "targetId": input_data.get("target_id")},
session_id,
input_data.get("cursor") or None,
)
except ReferenceError as exc:
return {"error": str(exc)}
132 changes: 132 additions & 0 deletions app/references/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# References

Users can attach sessions and Agent Apps through **+ → Reference…** or type
`@` in the composer and filter suggestions as they type. Selecting a suggestion
adds a removable chip; unselected `@text` remains ordinary text. Enter/Tab selects
a suggestion, arrows navigate, and Escape dismisses. Email addresses do not open
the picker. Both entry points use one catalog and pending-reference selection. Discovery lists
main/ordinary chats and apps; internal Agent App sessions are hidden to avoid
duplicate entries.

## Data flow

The client sends `references: [{kind, targetId}]` with the ordinary message
envelope. It never supplies authoritative reference content. `ReferenceService`
validates the destination and source identities and composes the two providers.
The browser's existing attachment submission path accepts references as well,
without routing the request to a different session or running an app.

The server persists `ReferenceSnapshot` objects in the additive nullable
`chat_messages.reference_snapshots` JSON column, echoes the same snapshots to the
browser, and includes attributed source data in the destination's normal trigger
payload. History loading and reconnection preserve the chips and captured preview.
Persistence is required before a reference message is acknowledged. Accepted
reference retries with the same destination/clientId reuse their original snapshot
and do not enqueue another turn; concurrent duplicates share an in-flight gate.
This does not add an atomic transaction across chat storage and the separate
trigger queue: a process crash between their writes retains the pre-existing
delivery limitation. Do not advertise exactly-once delivery across crashes.

Captured excerpts stay with the destination history. Renaming or deleting a source
does not rewrite those copies; clearing/deleting the destination removes them.
An unavailable source disables navigation and further live reads. Sources are
scoped to the current local CraftBot account; this feature does not introduce a
separate tenant/ACL system.

## Providers and expansion

- `SessionReferenceProvider` reads only visible user/agent transcript text from
the selected session. It excludes internal activity, stored reference excerpts,
attachment bytes and executable UI artifacts. Pages use acceptance row order,
a fixed high-water mark, and continuation offsets inside oversized messages.
Read `nextCursor` until it is null to retrieve earlier material; each message
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 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
read checks membership and current source existence again. Results are explicitly
live reads, separate from the original captured preview.

Initial limits are eight unique references, 8 KiB per excerpt and 32 KiB combined;
live pages are capped at 24 KiB. Sources share the total budget fairly. The existing
token counter additionally bounds rendered context to at most 8,192 tokens or
one eighth of the configured model context window, whichever is smaller. Smaller
captures are re-read at their actual bound so continuation cursors remain correct.
Normal context-engine compaction still handles the rest of the receiving history.
These are context data, never system instructions or permission grants.

To add a source, implement the provider's small async `capture(target_id, limit,
cursor)` contract, register it in `create_reference_service`, and extend the TS
ReferenceInput kind/catalog/navigation mapping and i18n labels. Providers return
label, excerpt, truncated, and nextCursor. They own source-specific access and
extraction; storage, message submission and prompt rendering remain generic.
Keep uploads, remote indexing, subscriptions, and source mutations separate.

## Failure handling and UI

Validation/storage failures return a clientId-correlated `message_rejected` event.
The pending bubble becomes an error with Retry and Edit controls. Edit restores
the original text, references, attachments and reply quote to the composer, allowing
an unavailable source to be removed. Retry payloads are held in memory until the
server echo; rejected unsent payloads are not durable across a page reload.
Messages containing references plus slash-prefixed text are ordinary messages.
Reference-only submissions receive a server-generated display label.

The frontend uses the existing textarea rather than a rich-text editor: the selected
`@query` is consumed and represented by the same chip as a + selection. Source
filtering is synchronous local metadata search, not transcript full-text search.
The + picker opens on hover as a compact nested menu with search, grouped sources,
selection toggles, and Escape/outside-click dismissal. Selecting a source closes
both menus and returns focus to the composer. Keyboard users can open it
with the right arrow, and touch users can still tap the entry. Chips use short single-line
labels and source-type icons. Captured previews retain their focus-managed dialog;
autocomplete owns active keyboard events before slash commands, input history, and send.

## Validation

From the repository root:

```powershell
python -m pytest tests/references tests/test_chat_storage_sessions.py tests/test_browser_ui_buffers.py tests/test_chat_read_receipts.py -q
python -m ruff check app/references app/data/action/reference_actions.py app/usage/chat_storage.py app/ui_layer/components/types.py app/ui_layer/adapters/browser_adapter.py app/agent_base.py tests/references
```

From `app/ui_layer/browser/frontend`:

```powershell
.\node_modules\.bin\tsc.cmd --noEmit
npm run build
.\node_modules\.bin\playwright.cmd test --workers=2
```

The Playwright fixture mounts the real composer/store/message components with an
offline transport. Python submission tests exercise the real browser adapter and
SQLite persistence with a fake agent, including mixed attachments, missing sources,
storage failure, and concurrent retries. No model, user database, running app, or
external connector is required. The repository's ESLint command currently has no
configuration file; it cannot run until that existing tooling gap is resolved.

Validation on 26 October 2026 after the edge-case fixes: 73 focused backend tests,
all 76 browser tests, and 90 repeated reference browser tests passed. Type checking,
production build, byte-compilation, and lint/format checks on the changed Python
files passed. Whole-repository lint still reports two pre-existing F402 errors in
`app/credentials/vault.py`; that file is unchanged from the `dev` base.

Additional isolated stress runs passed 100 concurrent eight-source captures,
250 concurrent reads, complete paging through a 1.68 MB Unicode message, and 1,000
contenders for one submission gate. Real-WebSocket tests with the actual browser
adapter and SQLite (stub agent) passed reload, retry replay, deletion, expansion,
and reconnect checks. A 500-request duplicate burst produced one accepted message;
50 unique requests were accepted once each, and 100 invalid requests were rejected.
The rapid-input reproduction now passes without waiting for an animation frame;
forged oversized cursor positions return validation errors instead of OverflowError.

The + submenu still renders all matching rows: a synthetic 6,001-source catalog
opened in approximately 0.7 seconds, while filtered search updates took 8–14 ms.
This remains a scalability consideration, not part of the two edge-case fixes.
No live model or production-state validation was performed.
5 changes: 5 additions & 0 deletions app/references/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Read-only, message-scoped references to CraftBot resources."""

from .service import ReferenceError, ReferenceService, create_reference_service

__all__ = ["ReferenceError", "ReferenceService", "create_reference_service"]
Loading