Skip to content

Self-hosted AI workspace.

Python

Merge remote-tracking branch 'origin/dev' into test-main-dev-merge-20260615

pewdiepie-archdaemond31674e7ffed
diff --cc src/agent_loop.py
index acb35e7b1,cd49f3e9d..f600ac598
--- a/src/agent_loop.py
+++ b/src/agent_loop.py
@@@ -1291,11 -1258,11 +1323,14 @@@ def _build_system_prompt
if _doc_message:
merged.insert(last_user_idx, _doc_message)
last_user_idx += 1 # the document message is now at last_user_idx
+ if _email_message:
+ merged.insert(last_user_idx, _email_message)
+ last_user_idx += 1
if _skills_message:
merged.insert(last_user_idx, _skills_message)
+ last_user_idx += 1
+ if _datetime_message:
+ merged.insert(last_user_idx, _datetime_message)
return merged, mcp_schemas
@@@ -2009,29 -2025,7 +2100,8 @@@ async def stream_agent_loop
compact=_is_api_model,
owner=owner,
suppress_local_context=guide_only,
+ active_email=active_email,
)
- if workspace and not guide_only:
- # PREPEND (not append) so it dominates the large base prompt — appended
- # at the end, small models ignored it and asked the user for code. The
- # folder IS the project; the agent must explore it, not ask.
- _ws_note = (
- f"## ACTIVE WORKSPACE — READ FIRST\n"
- f"The user is working in this folder: {workspace}\n"
- f"It IS the project. bash/python run with cwd set here and "
- f"read_file/write_file are confined to it (paths outside are rejected).\n"
- f"When the user says \"the code\" / \"this project\" / \"the workspace\" "
- f"or asks to review/find/edit something WITHOUT a path, they mean THIS "
- f"folder. Do NOT ask the user for code or a path, and do NOT read a file "
- f"literally named \"workspace\". ALWAYS start by exploring it yourself: "
- f"run `bash` → `git ls-files` (or `ls -R`) to see the files, then "
- f"read_file the relevant ones by path RELATIVE to the workspace."
- )
- if messages and messages[0].get("role") == "system":
- messages[0]["content"] = _ws_note + "\n\n" + (messages[0].get("content") or "")
- else:
- messages.insert(0, {"role": "system", "content": _ws_note})
- logger.info("[workspace] active for this turn: %s", workspace)
if plan_mode and not guide_only:
# Steer the model to investigate-then-propose. Hard tool gating handles
# every write path except shell; this directive is what keeps the
diff --cc src/office_doc.py
index 3176e8d93,000000000..37b45a637
mode 100644,000000..100644
--- a/src/office_doc.py
+++ b/src/office_doc.py
@@@ -1,73 -1,0 +1,73 @@@
+"""Auto-create a Document row from an Office attachment.
+
+When a .docx (and friends) lands in chat, the full extracted text is stored
+as a Document so the agent can page through it with `manage_documents
+action=read offset=…` even after the inline chat payload was capped. Mirrors
+the PDF auto-doc pattern in `src.pdf_form_doc`.
+"""
+
+import logging
+import uuid
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+
+def create_office_document(
+ session_id: str,
+ upload_id: str,
+ title: str,
+ body_text: Optional[str] = None,
+) -> Optional[str]:
+ """Create a markdown Document for an Office attachment and set it active.
+
+ Returns the new doc_id, or None on failure / empty body. The full
+ extracted body lives in `current_content`, so the agent can fetch
+ arbitrary windows via `manage_documents action=read` even when the
+ inline chat copy was truncated.
+ """
+ from src.database import (
+ SessionLocal,
+ Document,
+ DocumentVersion,
+ Session as DbSession,
+ )
- from src.tool_implementations import set_active_document
++ from src.agent_tools.document_tools import set_active_document
+
+ if not body_text or not body_text.strip():
+ return None
+
+ db = SessionLocal()
+ try:
+ doc_id = str(uuid.uuid4())
+ ver_id = str(uuid.uuid4())
+ sess = db.query(DbSession).filter(DbSession.id == session_id).first()
+ doc = Document(
+ id=doc_id,
+ session_id=session_id,
+ title=title,
+ language="markdown",
+ current_content=body_text,
+ version_count=1,
+ is_active=True,
+ owner=sess.owner if sess else None,
+ )
+ ver = DocumentVersion(
+ id=ver_id,
+ document_id=doc_id,
+ version_number=1,
+ content=body_text,
+ summary="Imported from Office attachment",
+ source="upload",
+ )
+ db.add(doc)
+ db.add(ver)
+ db.commit()
+ set_active_document(doc_id)
+ return doc_id
+ except Exception as e:
+ db.rollback()
+ logger.error("Failed to create office document: %s", e)
+ return None
+ finally:
+ db.close()
diff --cc src/tool_implementations.py
index e4de5a27a,dee18c626..ae7246ec6
--- a/src/tool_implementations.py
+++ b/src/tool_implementations.py
@@@ -18,552 -18,41 +18,75 @@@ from core.constants import internal_api
logger = logging.getLogger(__name__)
+# ---------------------------------------------------------------------------
- # Argument parsing
++# Active email state
+# ---------------------------------------------------------------------------
+
- def _parse_tool_args(content):
- """Parse a tool-call argument blob.
-
- Accepts either a JSON string or an already-decoded dict. Unwraps the
- common `{"body": {...}}` envelope that smaller models emit when they
- read tool descriptions like "Body is JSON: {...}" literally — they
- pass `body` as a field name rather than treating it as a noun.
-
- Returns a dict on success, raises ValueError on bad JSON.
- """
- if isinstance(content, str):
- try:
- args = json.loads(content) if content.strip() else {}
- except (json.JSONDecodeError, TypeError) as e:
- raise ValueError(str(e))
- elif isinstance(content, dict):
- args = content
- else:
- args = {}
- # Unwrap {"body": {...}} envelope — but only if `body` is the sole key
- # and points at a dict. We don't want to clobber a legitimate `body`
- # field on tools where it's a real arg (e.g. send_email body text).
- if (
- isinstance(args, dict)
- and len(args) == 1
- and "body" in args
- and isinstance(args["body"], dict)
- and "action" in args["body"] # extra safety: only unwrap if the inner dict looks like a tool call
- ):
- args = args["body"]
- return args
-
-
- # ---------------------------------------------------------------------------
- # Active document state
- # ---------------------------------------------------------------------------
-
- _active_document_id: Optional[str] = None
- _active_model: Optional[str] = None
+# When the user has an email reader window open, the frontend tells the
- # backend about it on each chat submit. We stash it here so email tools
- # (reply_to_email, read_email, mark_email) can resolve "this email" / "the
- # open one" without the agent guessing a UID. Cleared between requests by
- # chat_routes after the agent loop returns.
++# backend about it on each chat submit. Email tools can resolve "this email"
++# without guessing a UID. Cleared between requests by chat_routes.
+_active_email_ref: Optional[Dict[str, str]] = None
+
+
+def set_active_email(uid: Optional[str], folder: Optional[str] = None, account: Optional[str] = None,
+ subject: Optional[str] = None, sender: Optional[str] = None) -> None:
+ """Stash the email currently open in the UI. None clears it."""
+ global _active_email_ref
+ if not uid:
+ _active_email_ref = None
+ return
+ _active_email_ref = {
+ "uid": str(uid),
+ "folder": str(folder or "INBOX"),
+ "account": str(account or ""),
+ "subject": str(subject or ""),
+ "from": str(sender or ""),
+ }
+
+
+def get_active_email() -> Optional[Dict[str, str]]:
+ return _active_email_ref
+
+
+def clear_active_email() -> None:
+ global _active_email_ref
+ _active_email_ref = None
+
-
- def set_active_document(doc_id: Optional[str]):
- """Set the active document ID for document tool execution."""
- global _active_document_id
- _active_document_id = doc_id
-
-
- def set_active_model(model: Optional[str]):
- """Set the current model name for version summaries."""
- global _active_model
- _active_model = model
-
-
- def get_active_document():
- return _active_document_id
-
-
- def clear_active_document(doc_id: Optional[str] = None) -> bool:
- """Clear the in-memory active-document pointer.
-
- With ``doc_id`` given, only clears when it matches the current pointer, so a
- different active document is left untouched. Returns True if it was cleared.
-
- Called when a document is detached from its session or deleted (its tab is
- closed): without this, the stale pointer makes the last-resort doc-injection
- path re-surface a closed document in a later, unrelated chat — even one whose
- session no longer matches — because an unlinked doc has session_id NULL (#1160).
- """
- global _active_document_id
- if doc_id is None or _active_document_id == doc_id:
- _active_document_id = None
- return True
- return False
-
-
- def _owned_document_query(query, Document, owner: Optional[str]):
- if owner is None:
- # A bare Python `False` is not a valid SQL expression — SQLAlchemy 1.4
- # deprecates it and 2.0 raises ArgumentError. Use the SQL `false()`
- # literal to return zero rows for an unscoped (owner-less) query.
- from sqlalchemy import false
- return query.filter(false())
- return query.filter(Document.owner == owner)
-
-
- def _get_owned_document(db, Document, doc_id: str, owner: Optional[str], active_only: bool = False):
- q = db.query(Document).filter(Document.id == doc_id)
- if active_only:
- q = q.filter(Document.is_active == True)
- q = _owned_document_query(q, Document, owner)
- return q.first()
-
-
- def _most_recent_owned_document(db, Document, owner: Optional[str], active_only: bool = False):
- q = db.query(Document)
- if active_only:
- q = q.filter(Document.is_active == True)
- q = _owned_document_query(q, Document, owner)
- return q.order_by(Document.updated_at.desc()).first()
-
-
# ---------------------------------------------------------------------------
- # Document tools — create/update/edit/suggest living documents
+ # Argument parsing
# ---------------------------------------------------------------------------
- def _sniff_doc_language(text: str) -> str:
- """Best-effort detect a document's language from its content when the model
- didn't specify one. Defaults to 'markdown' (prose). Recognizes the common
- markup/code types the editor supports so e.g. an SVG isn't saved as markdown."""
- import json as _json, re as _re2
- s = (text or "").strip()
- if not s:
- return "markdown"
- head = s[:600]
- hl = head.lower()
- if _looks_like_email_document(s):
- return "email"
- # Markup (unambiguous)
- if "<svg" in hl:
- return "svg"
- if hl.startswith("<?xml"):
- return "xml"
- if (hl.startswith("<!doctype html") or hl.startswith("<html")
- or _re2.search(r"<(div|body|head|p|span|table|button|h[1-6]|ul|ol|li|img)\b", hl)):
- return "html"
- # JSON
- if s[0] in "{[":
- try:
- _json.loads(s)
- return "json"
- except Exception:
- pass
- # Shebang
- first = s.split("\n", 1)[0].strip().lower()
- if first.startswith("#!"):
- return "python" if "python" in first else "bash"
- # Code by strong leading signals (line-anchored so prose with stray words won't match)
- if _re2.search(r"(?m)^\s*(def \w|class \w|import \w|from \w[\w.]* import )", s):
- return "python"
- if _re2.search(r"(?m)^\s*(function \w|const \w|let \w|export |import .* from )", s):
- return "javascript"
- if _re2.search(r"(?mi)^\s*(select .* from |create table |insert into |update \w)", s):
- return "sql"
- if _re2.search(r"(?m)^[.#]?[\w-]+\s*\{[^{}]*:[^{}]*;", s):
- return "css"
- return "markdown"
-
-
- def _looks_like_email_document(text: str = "", title: str = "") -> bool:
- import re as _re
- title_l = (title or "").strip().lower()
- if title_l in {"new email", "new mail", "new message"}:
- return True
- s = (text or "").lstrip()
- if "\n---\n" in s and _re.search(r"(?im)^To:\s*", s) and _re.search(r"(?im)^Subject:\s*", s):
- return True
- return bool(_re.search(r"(?im)^To:\s*", s) and _re.search(r"(?im)^Subject:\s*", s))
-
-
- def _coerce_email_document_content(existing: str, incoming: str) -> str:
- """Keep email docs in the To/Subject/---/body shape even if a model writes
- only the body or dumps header labels without the separator."""
- import re as _re
- old = existing or ""
- new = (incoming or "").strip()
- if "\n---\n" in new:
- return new
- header = old.split("\n---\n", 1)[0] if "\n---\n" in old else "To: \nSubject: "
- if _looks_like_email_document(new):
- lines = new.splitlines()
- last_header_idx = -1
- header_re = _re.compile(r"^(To|Cc|Bcc|Subject|In-Reply-To|References|X-Source-UID|X-Source-Folder|X-Attachments):", _re.I)
- for i, line in enumerate(lines):
- if header_re.match(line.strip()):
- last_header_idx = i
- body_lines = lines[last_header_idx + 1:] if last_header_idx >= 0 else lines
- while body_lines and not body_lines[0].strip():
- body_lines.pop(0)
- body = "\n".join(body_lines).strip()
- else:
- body = new
- return header.rstrip() + "\n---\n" + body
-
-
- async def do_create_document(content_block: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
- """Create a new document. Supports two formats:
- 1) Line-based: line 1 = title, line 2 (optional) = language, rest = content
- 2) XML-like tags: <title>...</title><language>...</language><content>...</content>
- Some models mix them — strip any XML-style tags and fall back to line parsing."""
- import uuid, re as _re
- from src.database import SessionLocal, Document, DocumentVersion, Session as DbSession
-
- raw = content_block or ""
-
- # Known languages the editor understands (match the <select> in HTML)
- _KNOWN_LANGS = {
- "python", "javascript", "typescript", "html", "css", "markdown", "json",
- "yaml", "bash", "sql", "rust", "go", "java", "c", "cpp", "xml", "toml",
- "ini", "ruby", "php", "csv", "email", "text", "plain", "svg",
- }
-
- # Try XML tag extraction first
- title = None
- language = None
- content = None
- mt = _re.search(r"<title>\s*(.*?)\s*</title>", raw, _re.DOTALL | _re.IGNORECASE)
- ml = _re.search(r"<language>\s*(.*?)\s*</language>", raw, _re.DOTALL | _re.IGNORECASE)
- mc = _re.search(r"<content>\s*(.*?)\s*</content>", raw, _re.DOTALL | _re.IGNORECASE)
- if mt or mc:
- title = mt.group(1).strip() if mt else None
- language = ml.group(1).strip().lower() if ml else None
- content = mc.group(1) if mc else None
-
- # Fall back to line-based parsing. First strip any stray XML-ish tags.
- if title is None or content is None:
- cleaned = _re.sub(r"</?(?:title|language|content)>", "", raw)
- lines = cleaned.strip().split("\n")
- if title is None:
- title = lines[0].strip() if lines else "Untitled"
- lines = lines[1:]
- # Only consume second line as language if it looks like a valid short lang token
- if language is None and lines:
- candidate = lines[0].strip().lower()
- if candidate and len(candidate) < 20 and " " not in candidate and candidate in _KNOWN_LANGS:
- language = candidate
- lines = lines[1:]
- if content is None:
- content = "\n".join(lines)
-
- # Validate language: must be in known set, else default based on content
- if language and language not in _KNOWN_LANGS:
- language = None
- if not language:
- # No explicit language — sniff it from the content so an SVG / HTML / JSON
- # / code document isn't silently saved as markdown. Prose → markdown.
- language = _sniff_doc_language(content)
- if _looks_like_email_document(content, title):
- language = "email"
-
- if not title:
- title = "Untitled"
-
- if not session_id:
- return {"error": "No session context for document creation"}
+ def _parse_tool_args(content):
+ """Parse a tool-call argument blob.
- db = SessionLocal()
- try:
- doc_id = str(uuid.uuid4())
- ver_id = str(uuid.uuid4())
-
- # Inherit ownership from the chat session so the doc survives that
- # session later being deleted (session_id → NULL).
- _sess = db.query(DbSession).filter(DbSession.id == session_id).first()
- if owner is not None and (not _sess or _sess.owner != owner):
- return {"error": "Cannot create document in another user's session"}
- _owner = _sess.owner if _sess else None
-
- doc = Document(
- id=doc_id,
- session_id=session_id,
- title=title,
- language=language,
- current_content=content,
- version_count=1,
- is_active=True,
- owner=_owner,
- )
- ver = DocumentVersion(
- id=ver_id,
- document_id=doc_id,
- version_number=1,
- content=content,
- summary=f"Created by {_active_model or 'AI'}",
- source="ai",
- )
- db.add(doc)
- db.add(ver)
- db.commit()
+ Accepts either a JSON string or an already-decoded dict. Unwraps the
+ common `{"body": {...}}` envelope that smaller models emit when they
+ read tool descriptions like "Body is JSON: {...}" literally — they
+ pass `body` as a field name rather than treating it as a noun.
- set_active_document(doc_id)
+ Returns a dict on success, raises ValueError on bad JSON.
+ """
+ if isinstance(content, str):
try:
- from src.event_bus import fire_event
- fire_event("document_created", _owner)
- except Exception:
- logger.debug("document_created event dispatch failed", exc_info=True)
-
- return {
- "action": "create",
- "doc_id": doc_id,
- "title": title,
- "language": language,
- "content": content,
- "version": 1,
- }
- except Exception as e:
- db.rollback()
- return {"error": f"Failed to create document: {e}"}
- finally:
- db.close()
-
-
- async def do_update_document(content: str, doc_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
- """Update an existing document. Content = full new document text."""
- import uuid
- from src.database import SessionLocal, Document, DocumentVersion
-
- target_id = doc_id or _active_document_id
-
- db = SessionLocal()
- try:
- doc = None
- if target_id:
- doc = _get_owned_document(db, Document, target_id, owner)
- if not doc:
- doc = _most_recent_owned_document(db, Document, owner)
- if doc:
- target_id = doc.id
- set_active_document(target_id)
- logger.info(f"update_document: fell back to most recent doc id={target_id}")
- if not doc:
- return {"error": "No documents exist to update"}
-
- is_email_doc = doc.language == "email" or _looks_like_email_document(doc.current_content or "", doc.title or "")
- new_content = _coerce_email_document_content(doc.current_content or "", content) if is_email_doc else content.strip()
- if is_email_doc:
- doc.language = "email"
-
- new_ver = doc.version_count + 1
- ver = DocumentVersion(
- id=str(uuid.uuid4()),
- document_id=target_id,
- version_number=new_ver,
- content=new_content,
- summary=f"Updated by {_active_model or 'AI'}",
- source="ai",
- )
- doc.current_content = new_content
- doc.version_count = new_ver
- db.add(ver)
- db.commit()
-
- return {
- "action": "update",
- "doc_id": target_id,
- "title": doc.title,
- "language": doc.language,
- "content": new_content,
- "version": new_ver,
- }
- except Exception as e:
- db.rollback()
- return {"error": f"Failed to update document: {e}"}
- finally:
- db.close()
-
-
- def parse_edit_blocks(content: str) -> list:
- """Parse <<<FIND>>>...<<<REPLACE>>>...<<<END>>> blocks."""
- edits = []
- pattern = r'<<<FIND>>>\n(.*?)\n<<<REPLACE>>>\n(.*?)\n<<<END>>>'
- for m in re.finditer(pattern, content, re.DOTALL):
- edits.append({"find": m.group(1), "replace": m.group(2)})
- return edits
-
-
- async def do_edit_document(content: str, doc_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
- """Apply targeted FIND/REPLACE edits to an existing document."""
- import uuid
- from src.database import SessionLocal, Document, DocumentVersion
-
- target_id = doc_id or _active_document_id
-
- edits = parse_edit_blocks(content)
- if not edits:
- return {"error": "No valid <<<FIND>>>...<<<REPLACE>>>...<<<END>>> blocks found"}
-
- db = SessionLocal()
- try:
- doc = None
- if target_id:
- doc = _get_owned_document(db, Document, target_id, owner)
- if not doc:
- # Fallback: most recently updated document. Avoids "no active doc" errors
- # after server restart or when the agent loses track of which doc to edit.
- doc = _most_recent_owned_document(db, Document, owner)
- if doc:
- target_id = doc.id
- set_active_document(target_id)
- logger.info(f"edit_document: fell back to most recent doc id={target_id} title={doc.title!r}")
- if not doc:
- return {"error": "No documents exist to edit"}
-
- updated_content = doc.current_content
- applied = 0
- skipped = 0
- for edit in edits:
- _find = edit["find"]
- if _find in updated_content:
- updated_content = updated_content.replace(_find, edit["replace"], 1)
- applied += 1
- else:
- # Defensive: the active-doc context shows a "N\t" line-number
- # gutter for reference. Weaker models sometimes copy that prefix
- # into FIND. If the exact match failed, retry with a leading
- # "<digits><tab>" stripped from each FIND line — but only use it
- # when that stripped form actually matches, so we never corrupt a
- # legitimately tab-prefixed document.
- _stripped = "\n".join(re.sub(r"^\d+\t", "", _l) for _l in _find.split("\n"))
- if _stripped != _find and _stripped in updated_content:
- updated_content = updated_content.replace(_stripped, edit["replace"], 1)
- applied += 1
- logger.info("edit_document: matched after stripping line-number gutter from FIND")
- else:
- logger.warning(f"edit_document: FIND text not found, skipping: {_find[:80]!r}")
- skipped += 1
-
- if applied == 0:
- return {"error": f"No edits applied — none of the FIND blocks matched the document content (skipped {skipped})"}
-
- new_ver = doc.version_count + 1
- ver = DocumentVersion(
- id=str(uuid.uuid4()),
- document_id=target_id,
- version_number=new_ver,
- content=updated_content,
- summary=f"Edited by {_active_model or 'AI'} ({applied} edit(s))",
- source="ai",
- )
- doc.current_content = updated_content
- doc.version_count = new_ver
- db.add(ver)
- db.commit()
-
- return {
- "action": "edit",
- "doc_id": target_id,
- "title": doc.title,
- "language": doc.language,
- "content": updated_content,
- "version": new_ver,
- "applied": applied,
- "skipped": skipped,
- }
- except Exception as e:
- db.rollback()
- return {"error": f"Failed to edit document: {e}"}
- finally:
- db.close()
-
-
- def parse_suggest_blocks(content: str) -> list:
- """Parse <<<FIND>>>...<<<SUGGEST>>>...<<<REASON>>>...<<<END>>> blocks."""
- suggestions = []
- _skip_phrases = ["no change", "clear", "fine as", "looks good", "no improvement", "keep as"]
- pattern = r'<<<FIND>>>\n(.*?)\n<<<SUGGEST>>>\n(.*?)\n<<<REASON>>>\n(.*?)\n<<<END>>>'
- for m in re.finditer(pattern, content, re.DOTALL):
- find_text = m.group(1)
- replace_text = m.group(2)
- reason = m.group(3).strip()
- # Skip no-op suggestions where find == replace or reason says no change
- if find_text.strip() == replace_text.strip():
- continue
- if any(phrase in reason.lower() for phrase in _skip_phrases):
- continue
- suggestions.append({
- "id": f"sugg-{len(suggestions)+1}",
- "find": find_text,
- "replace": replace_text,
- "reason": reason,
- })
- return suggestions
-
-
- async def do_suggest_document(content: str, doc_id: str = None, owner: Optional[str] = None) -> Dict:
- """Create inline suggestions for the active document WITHOUT modifying it."""
- from src.database import SessionLocal, Document
-
- target_id = doc_id or _active_document_id
- if not target_id:
- return {"error": "No active document to suggest on"}
-
- suggestions = parse_suggest_blocks(content)
- if not suggestions:
- return {"error": "No valid <<<FIND>>>...<<<SUGGEST>>>...<<<REASON>>>...<<<END>>> blocks found"}
-
- db = SessionLocal()
- try:
- doc = _get_owned_document(db, Document, target_id, owner)
- if not doc:
- return {"error": f"Document {target_id} not found"}
-
- # Validate that FIND text exists in document
- valid = []
- for s in suggestions:
- if s["find"] in doc.current_content:
- valid.append(s)
- else:
- logger.warning(f"suggest_document: FIND text not found, skipping: {s['find'][:80]!r}")
-
- if not valid:
- return {"error": "No suggestions matched the document content"}
-
- return {
- "action": "suggest",
- "doc_id": target_id,
- "suggestions": valid,
- "count": len(valid),
- }
- finally:
- db.close()
-
+ args = json.loads(content) if content.strip() else {}
+ except (json.JSONDecodeError, TypeError) as e:
+ raise ValueError(str(e))
+ elif isinstance(content, dict):
+ args = content
+ else:
+ args = {}
+ # Unwrap {"body": {...}} envelope — but only if `body` is the sole key
+ # and points at a dict. We don't want to clobber a legitimate `body`
+ # field on tools where it's a real arg (e.g. send_email body text).
+ if (
+ isinstance(args, dict)
+ and len(args) == 1
+ and "body" in args
+ and isinstance(args["body"], dict)
+ and "action" in args["body"] # extra safety: only unwrap if the inner dict looks like a tool call
+ ):
+ args = args["body"]
+ return args
# ---------------------------------------------------------------------------
# Search chats
diff --cc static/index.html
index d064804e6,08047f9aa..89b0ebb34
--- a/static/index.html
+++ b/static/index.html
@@@ -2157,13 -2108,33 +2170,14 @@@
<option value="https://opencode.ai/zen/v1" data-logo="opencode">OpenCode Zen</option>
<option value="https://opencode.ai/zen/go/v1" data-logo="opencode">OpenCode Go</option>
<option value="https://api.z.ai/api/coding/paas/v4" data-logo="zhipu">Z.AI Coding Plan</option>
+ <option value="https://integrate.api.nvidia.com/v1" data-logo="nvidia">NVIDIA</option>
</select>
- <!-- API key row stays in DOM, hidden until Key button is
- clicked. Mirrors the Local section pattern: most users
- paste a key via the provider preset flow rather than
- typing it free-form, so the row only appears on demand. -->
- <div class="admin-model-form-row" id="adm-epApiKey-row" style="display:none;">
- <input id="adm-epApiKey" type="password" placeholder="API key" autocomplete="off" style="flex:1">
- </div>
- <div class="admin-model-form-row" style="margin-top:-4px;">
- <select id="adm-epKind" style="padding:5px;width:82px;">
- <option value="proxy">Proxy</option>
- <option value="api">API</option>
- </select>
- <label style="display:inline-flex;align-items:center;gap:4px;font-size:11px;opacity:0.6;flex-shrink:0;">Type:<select id="adm-epType" style="padding:5px;width:80px;flex-shrink:0;">
- <option value="llm" selected>LLM</option>
- <option value="image">Image</option>
- </select></label>
- <span style="flex:1"></span>
- <button class="admin-btn-sm" id="adm-epApiKeyBtn" title="Show / hide the API key field" aria-expanded="false" aria-controls="adm-epApiKey-row" style="opacity:0.75;display:inline-flex;align-items:center;gap:4px;">
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-9.6 9.6"/><circle cx="7.5" cy="15.5" r="5.5"/><path d="M15.5 7.5l3 3"/></svg>API
- </button>
- <button class="admin-btn-sm" id="adm-epApiTestBtn" style="min-width:55px;text-align:center;display:inline-flex;align-items:center;justify-content:center;gap:4px;">
- <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>Test
- </button>
- <button class="admin-btn-sm hidden" id="adm-epApiCancelTestBtn" style="width:62px;text-align:center;">Cancel</button>
- <button class="admin-btn-add" id="adm-epAddBtn" style="min-width:55px;text-align:center;display:inline-flex;align-items:center;justify-content:center;gap:4px;">
+ <div class="admin-model-form-row" id="adm-epApiKey-row">
+ <div style="position:relative;flex:1;display:flex;align-items:center;">
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="position:absolute;left:9px;top:50%;transform:translateY(-50%);opacity:0.55;pointer-events:none;"><path d="M21 2l-9.6 9.6"/><circle cx="7.5" cy="15.5" r="5.5"/><path d="M15.5 7.5l3 3"/></svg>
+ <input id="adm-epApiKey" type="password" placeholder="API key, e.g. sk-proj-AbCdEf…" autocomplete="off" style="flex:1;padding-left:28px;height:32px;box-sizing:border-box;">
+ </div>
+ <button class="admin-btn-add" id="adm-epAddBtn" style="height:32px;min-width:55px;text-align:center;display:inline-flex;align-items:center;justify-content:center;gap:4px;flex-shrink:0;box-sizing:border-box;">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>Add
</button>
</div>
diff --cc static/js/research/panel.js
index dd561abfc,7aac5435e..3abf75fb1
--- a/static/js/research/panel.js
+++ b/static/js/research/panel.js
@@@ -365,16 -346,24 +365,23 @@@ function _buildPanelHTML()
</div>
<div class="modal-body research-pane-body" data-no-swipe-dismiss>
<div class="research-new-job">
- <div style="display:flex;align-items:baseline;gap:8px;margin-bottom:2px;">
- <h2 style="margin:0;padding:0;line-height:1;">Research <span id="research-stats" class="memory-count" style="font-size:0.6em;opacity:0.6;font-weight:normal"></span></h2>
+ <div style="display:flex;align-items:center;gap:8px;margin-bottom:2px;">
+ <h2 style="margin:0;padding:0;line-height:1;display:inline-flex;align-items:center;gap:6px;"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--accent, var(--red))" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;"><path d="M6 18h8"/><path d="M3 22h18"/><path d="M14 22a7 7 0 1 0 0-14h-1"/><path d="M9 14h2"/><path d="M9 12a2 2 0 0 1-2-2V6h4v4a2 2 0 0 1-2 2Z"/><path d="M12 6V3a1 1 0 0 0-1-1H9a1 1 0 0 0-1 1v3"/></svg>Research <span id="research-stats" class="memory-count" style="font-size:0.6em;opacity:0.6;font-weight:normal;position:relative;top:4px;"></span></h2>
</div>
- <p class="memory-desc doclib-desc" style="margin-top:6px;display:flex;align-items:center;gap:6px;">
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;opacity:0.8;"><path d="M6 18h8"/><path d="M3 22h18"/><path d="M14 22a7 7 0 1 0 0-14h-1"/><path d="M9 14h2"/><path d="M9 12a2 2 0 0 1-2-2V6h4v4a2 2 0 0 1-2 2Z"/><path d="M12 6V3a1 1 0 0 0-1-1H9a1 1 0 0 0-1 1v3"/></svg>
+ <p class="memory-desc doclib-desc" style="margin-top:2px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
<span>Multi-step web research with an LLM-in-the-loop agent</span>
+ <span id="research-no-past-hint" style="display:none;font-size:11px;opacity:0.7;position:relative;top:-4px;">— past runs in <button type="button" class="research-library-link" style="background:none;border:none;padding:0;font:inherit;color:var(--accent, var(--red));cursor:pointer;text-decoration:underline;">Library, Research</button></span>
</p>
- <div id="research-no-past-hint" class="memory-desc doclib-desc" style="display:none;margin-top:-2px;font-size:11px;opacity:0.7;">All past research found in <button type="button" class="research-library-link">Library, Research</button></div>
- <textarea id="research-query" class="research-query" placeholder="e.g. Trace Odysseus's ten-year journey home from Troy — every island, monster, and detour, and what each one cost him." rows="4"></textarea>
+ <textarea id="research-query" class="research-query" placeholder="${_pickResearchHint()}" rows="4"></textarea>
+ <div class="research-category-row" id="research-category-row">
+ <button class="research-cat active" data-cat="" title="LLM auto-detects the best format">Auto</button>
+ <button class="research-cat" data-cat="product">Product</button>
+ <button class="research-cat" data-cat="comparison">Compare</button>
+ <button class="research-cat" data-cat="howto">How-to</button>
+ <button class="research-cat" data-cat="factcheck">Fact-check</button>
+ </div>
<button id="research-settings-toggle" class="research-settings-toggle${chevronCls}">
- Settings<span class="research-settings-chevron">${_chevronIcon}</span>
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;opacity:0.85;flex-shrink:0;"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>Settings<span class="research-settings-chevron">${_chevronIcon}</span>
</button>
<div id="research-settings-body" class="research-settings-row"${settingsHidden}>
<label class="research-setting">