diff --git a/docs/doctor-overview.md b/docs/doctor-overview.md index f17d8de..f0ad2c5 100644 --- a/docs/doctor-overview.md +++ b/docs/doctor-overview.md @@ -116,9 +116,10 @@ to Holmes. Doctor exposes only the Bash tool to the local model, to reduce tool-selection errors; Bash still has host-level access. This compatibility layer does not establish that a model's proposed actions are correct; repair mode still allows host-level Bash commands. If the initial model answer is prose and no tool has run, the adapter makes one -additional request for an initial read-only Bash check. It translates the reply -only if the tool name and arguments satisfy the supplied schema; it does not -invent a call from the prose. It does not force a tool after tool history exists. +additional request with a shorter prompt. It forwards the reply only if it is +one schema-valid Bash call containing a single read-only `kubectl get` command. +It does not invent a call from the prose or force a tool after tool history +exists. Subsequent Holmes actions retain the permissions described above. For native K3s on the Orange Pi, `doctor opi5` collects the K3s service state, data and runtime mount identities, USB ext4 candidates and recent storage diff --git a/scripts/ollama-tool-proxy.py b/scripts/ollama-tool-proxy.py index acb6603..b68a66f 100644 --- a/scripts/ollama-tool-proxy.py +++ b/scripts/ollama-tool-proxy.py @@ -3,6 +3,8 @@ import importlib.util import json import os +import re +import shlex from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path import sys @@ -44,23 +46,55 @@ def translate(result, tools): return result +def safe_initial_call(message, tools): + calls = message.get("tool_calls") + if not isinstance(calls, list) or len(calls) != 1: + return False + function = calls[0].get("function") or {} + try: + args = json.loads(function.get("arguments", ""), object_pairs_hook=adapter.unique_object) + validated = adapter.convert(json.dumps({"name": function.get("name"), "arguments": args}), tools) + command = args["command"] + if not isinstance(command, str) or re.search(r"[;&|`$><\n\r]", command): + return False + words = shlex.split(command) + if not words or words[0] != "kubectl" or words.count("get") != 1: + return False + if any(not re.fullmatch(r"[A-Za-z0-9_./:=,\-]+", word) for word in words): + return False + if any(word.startswith(("--raw", "--watch", "--server", "--token")) for word in words): + return False + return validated is not None + except (ValueError, TypeError, KeyError, AttributeError): + return False + + def complete(request, bash_mode): """Retry an initial prose-only answer once; never fabricate a tool call.""" result = translate(query_ollama(request), request.get("tools", [])) message = result["choices"][0]["message"] messages = request.get("messages", []) + print("initial_response", "tool_call=" + str(bool(message.get("tool_calls"))), + "tools=" + str(len(request.get("tools") or [])), + "prior_tool=" + str(any(isinstance(m, dict) and (m.get("role") == "tool" or bool(m.get("tool_calls"))) for m in messages)), + flush=True) if (bash_mode and request.get("tools") and not message.get("tool_calls") and isinstance(message.get("content"), str) and message["content"].strip() and not any(isinstance(m, dict) and (m.get("role") == "tool" or m.get("tool_calls")) for m in messages)): retry = dict(request) - retry["messages"] = messages + [message, {"role": "user", "content": + users = [m for m in messages if isinstance(m, dict) and m.get("role") == "user" and isinstance(m.get("content"), str)] + if not users: + return result + retry["messages"] = [{"role": "system", "content": "Use the bash tool to perform one read-only Kubernetes check."}, users[-1], {"role": "user", "content": "Start the investigation now by calling the bash tool for one simple read-only kubectl get check. " "Use kubectl -n NAMESPACE get RESOURCE NAME when the resource is namespaced; " "kubectl ns is not a command. Use one command only, with no pipes, shell operators or SSH. " "Return only a JSON object with name bash and arguments containing command and suggested_prefixes. " "Do not modify resources in this first check."}] retried = translate(query_ollama(retry), request["tools"]) - if retried["choices"][0]["message"].get("tool_calls"): + accepted = safe_initial_call(retried["choices"][0]["message"], request["tools"]) + print("initial_retry", "tool_call=" + str(bool(retried["choices"][0]["message"].get("tool_calls"))), "accepted=" + str(accepted), flush=True) + if accepted: return retried return result diff --git a/tests/jeannie/test_ollama_tool_call_adapter.py b/tests/jeannie/test_ollama_tool_call_adapter.py index 5a93652..23b593c 100644 --- a/tests/jeannie/test_ollama_tool_call_adapter.py +++ b/tests/jeannie/test_ollama_tool_call_adapter.py @@ -62,3 +62,13 @@ class ToolAdapterTests(unittest.TestCase): with patch.object(PROXY, "query_ollama", return_value=plan) as query: PROXY.complete(request, True) self.assertEqual(query.call_count, 1) + + def test_retry_cannot_turn_a_plan_into_a_mutating_command(self): + tools = [{"type": "function", "function": {"name": "bash", "parameters": { + "type": "object", "properties": {"command": {"type": "string"}, + "suggested_prefixes": {"type": "array", "items": {"type": "string"}}}, + "required": ["command", "suggested_prefixes"]}}}] + for command in ("kubectl delete pod n8n", "kubectl get pods; rm -rf /", "kubectl get --raw=/api/v1/secrets"): + message = {"tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({ + "command": command, "suggested_prefixes": ["kubectl"]})}}]} + self.assertFalse(PROXY.safe_initial_call(message, tools))