forked from enderofwings/NexusOS
feat: direct tool invocation via /tool_name(arg=val) + wire Curry as real tools
Adds synapse/slash_commands.py: a chat message that's nothing but /tool_name(arg=val, arg=val) dispatches straight through tools.dispatch(), skipping model selection, RAG/playbook context assembly, and the ask-policy approval round-trip entirely. A human typing this IS the approval - there's no one else to ask - so it's a deliberate, reviewed bypass of the approval step specifically, not of anything a tool validates internally (path boundaries, size caps, Curry's own sandbox checks all still run). Argument values parse via ast.literal_eval only: strings/numbers/bools/None/literal containers, no names, no calls, no attribute access - a malformed or hostile-looking argument fails to parse rather than executing anything. Wired into chat_stream_endpoint (main.py) as an early short-circuit, before any of the RAG/model-selection work that a slash-command doesn't need. Web needed no changes (it already forwards raw text unchanged); the TUI previously swallowed every leading "/" locally and never reached the backend with it, so tui_app.py's _handle_slash now falls through to _start_chat for anything shaped like a tool call while still handling its own local meta-commands (/help, /model, /new, ...) exactly as before. Also finally wires Curry in as ten real tools (curry_declare_constant, curry_get_constant/_latest, curry_list_constants, curry_retire_constant, curry_declare_function, curry_get_function, curry_list_functions, curry_call_function, curry_retire_function) - deferred from the vendoring pass. The five write/execute ones are ACTION tools in the same always-ask-regardless-of-global-policy floor as edit_source (ALWAYS_ASK_ACTION_TOOLS, generalized in tools.py from the old self_edit-only ALWAYS_ASK_TOOLS so future tool families share one place to register into). curry_call_function is gated as an action for the same reason run_snippet is: it executes code, even sandboxed. Fixed a real bug surfaced while wiring this up: curry_db is a long-lived singleton holding one sqlite3 connection (unlike NexusOS's own memory store, which opens/closes a fresh connection per call specifically to dodge this), and sqlite3 forbids using a connection from a different thread than created it. That's a non-issue in production (uvicorn's single event-loop thread), but Starlette's TestClient runs the ASGI app through an anyio portal thread, so it broke immediately under test. Fixed at the source (curry_core.py, Curry.__init__) with check_same_thread=False, documented as a second deliberate vendoring deviation alongside the PR #4 sandbox fix - there was never real concurrent access here, just an overly strict same-thread assertion tripping on a thread-identity change with only one logical caller. Verified: 244 backend tests pass (18 new for the parser + endpoint wiring + curry tool registration, 4 new for the TUI passthrough); the 12 pre-existing C/C++/Rust toolchain failures are unrelated and unchanged. Confirmed by hand over the real HTTP endpoint: successful dispatch, zero tool_request events (approval bypass working as designed), a format()-dunder exploit attempt still rejected by the vendored sandbox fix even through the new tool registration, malformed arguments rejected before ever reaching dispatch, and an unknown tool name rejected cleanly. Wheel rebuilt and content-checked (bin/check.sh's gate now also asserts slash_commands.py ships). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
+67
-4
@@ -209,6 +209,7 @@ from .memory.store import store, MemoryItem
|
||||
from .playbooks.store import playbook_store
|
||||
from .curry_store import curry_db # noqa: F401 - import triggers Curry's own preload at startup
|
||||
from .search import needs_web_search, web_search
|
||||
from . import slash_commands as _slash_commands
|
||||
|
||||
MEMORY_SERVICE = settings.memory_url
|
||||
|
||||
@@ -335,6 +336,47 @@ async def root():
|
||||
|
||||
# -------------------------
|
||||
# Chat (streaming)
|
||||
async def _slash_command_stream(
|
||||
slash: "_slash_commands.SlashCommand | _slash_commands.SlashCommandError",
|
||||
conversation_id: str,
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Dispatch a parsed slash-command and stream its result the same shape a
|
||||
normal reply streams in — a single content chunk, `event: done`, nothing
|
||||
else. No model call, no tool-loop, no approval round-trip: see
|
||||
slash_commands.py for why that's the deliberate design here."""
|
||||
if isinstance(slash, _slash_commands.SlashCommandError):
|
||||
yield f"event: error\ndata: {_json.dumps({'detail': slash.text})}\n\n"
|
||||
return
|
||||
|
||||
if slash.tool not in _tools.REGISTRY:
|
||||
yield (
|
||||
"event: error\ndata: "
|
||||
f"{_json.dumps({'detail': f'unknown tool: {slash.tool}'})}\n\n"
|
||||
)
|
||||
return
|
||||
|
||||
yield f"event: status\ndata: {_json.dumps({'tool': slash.tool})}\n\n"
|
||||
raw_result = await _tools.dispatch(slash.tool, slash.args)
|
||||
|
||||
# Tools that emit a fence (curry_*, edit_*, run_snippet) carry it as
|
||||
# `"fence"` in their JSON result — reuse it verbatim so the existing
|
||||
# nexus-run/nexus-edit renderers pick it up with no new frontend code.
|
||||
# Anything else is shown as pretty-printed JSON.
|
||||
content = raw_result
|
||||
try:
|
||||
parsed = _json.loads(raw_result)
|
||||
if isinstance(parsed, dict) and isinstance(parsed.get("fence"), str):
|
||||
content = parsed["fence"]
|
||||
else:
|
||||
content = _json.dumps(parsed, indent=2, ensure_ascii=False)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
store.add_message(conversation_id, "assistant", content)
|
||||
yield f"data: {_json.dumps(content)}\n\n"
|
||||
yield "event: done\ndata: {}\n\n"
|
||||
|
||||
|
||||
# -------------------------
|
||||
@app.post("/chat/stream")
|
||||
async def chat_stream_endpoint(payload: Dict[str, Any]):
|
||||
@@ -345,13 +387,37 @@ async def chat_stream_endpoint(payload: Dict[str, Any]):
|
||||
_chat_slot_held = True
|
||||
try:
|
||||
message = payload.get("message", "")
|
||||
conversation_id = payload.get("conversation_id") or str(_uuid.uuid4())
|
||||
|
||||
if not message:
|
||||
raise HTTPException(status_code=400, detail="Missing 'message'")
|
||||
|
||||
# Direct tool invocation: /tool_name(arg=val, ...). A human typing this
|
||||
# IS the approval, so it skips model selection, RAG/playbook context
|
||||
# assembly, and the ask-policy round-trip entirely — see
|
||||
# slash_commands.py for what it does and does not bypass.
|
||||
_slash = _slash_commands.parse_slash_command(message)
|
||||
if _slash is not None:
|
||||
store.create_conversation(conversation_id, "")
|
||||
store.add_message(conversation_id, "user", message)
|
||||
_slash_inner = _slash_command_stream(_slash, conversation_id)
|
||||
|
||||
async def _slash_guarded() -> AsyncGenerator[str, None]:
|
||||
try:
|
||||
async for _chunk in _slash_inner:
|
||||
yield _chunk
|
||||
finally:
|
||||
_CHAT_INFLIGHT.release()
|
||||
|
||||
_chat_slot_held = False
|
||||
return StreamingResponse(_slash_guarded(), media_type="text/event-stream")
|
||||
|
||||
app_settings = store.get_settings()
|
||||
# Model precedence: explicit request > active playbook's pinned model > auto-select.
|
||||
_active_pb = playbooks.get_main_playbook()
|
||||
_pb_model = _active_pb.model if (_active_pb and _active_pb.model) else ""
|
||||
model = payload.get("model") or _pb_model or await _auto_select_model(message)
|
||||
context = payload.get("context", {})
|
||||
conversation_id = payload.get("conversation_id") or str(_uuid.uuid4())
|
||||
history = payload.get("history", [])
|
||||
temperature = payload.get("temperature", app_settings.get("temperature"))
|
||||
num_ctx = payload.get("num_ctx", app_settings.get("num_ctx", 0))
|
||||
@@ -359,9 +425,6 @@ async def chat_stream_endpoint(payload: Dict[str, Any]):
|
||||
gpu_offload = payload.get("gpu_offload", app_settings.get("gpu_offload", -1))
|
||||
num_gpu = await get_ollama_manager().resolve_num_gpu(gpu_offload, model)
|
||||
|
||||
if not message:
|
||||
raise HTTPException(status_code=400, detail="Missing 'message'")
|
||||
|
||||
rendered_message = message # chat has no template vars; render_prompt is for the playbook path
|
||||
system_prompt = playbooks.get_system_prompt() or app_settings.get("system_prompt", "")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user