Files
splinter/tests/fake_telegram.py
T
lotherk 181b2c0638 ask: the model can put a question to the operator, in every front end
The `ask` tool asks and the answer -- or "nobody answered" -- becomes the
observation. Read class: it changes nothing on the machine, and the authority
is the operator, not a gate.

Front ends: the chat draws a dialog (options to pick, typed words still count),
the protocol carries it as an `ask` event and an `answer` command, MCP returns
it from splinter_say and resumes with splinter_answer, the Telegram gateway
sends it as a message and takes the next message from an allowed user.

What the review of the WIP found, and what this fixes:

- -p hung for the full 900 s ask wait: sp_engine_prompt installed engine_ask,
  but nobody polls events on the synchronous path. cfg.ask now stays NULL
  there, so the tool answers at once with "nobody can be asked here".
  Measured: 3 s instead of 900 s (was rc=124 after 20 s).
- splinter_say over MCP hung the same way, because tool_say only looked at
  st.waiting. It now looks at st.asking and returns the question; the client
  timed out at 15 s before, and the turn was lost.
- protocol.c read the question buffer uninitialized when sp_engine_ask
  returned 0.
- turn_ask answered nothing when the window could not be opened, which parked
  the turn for the full wait.
- pick_run computed the list height without the question's rows, so the
  highlighted row scrolled out of the window (reproduced: after nine Downs no
  ">" row was on the screen). pick_draw and pick_run now share pick_listtop().
- the Telegram gateway was dead for this tool: it runs its turns on a copy of
  e->base, where ask was never set, so the model was told "nobody can be
  asked" while the operator sat in the chat. New tg_ask, verified against a
  running daemon and covered in test_gateway.sh.
- tests/test_ask_ui.sh was untracked and not in make check, so it never ran.

A2A keeps no ask channel on purpose: there an approval pauses the task into
INPUT_REQUIRED, and the ask signature cannot express a pause -- saying
"nobody can be asked" is the honest answer there.

Tests: make check green (327 s), including the new test_ask_mcp.sh and
test_ask_ui.sh, both wired into make check. test_ask_mcp.sh was verified to
fail against the unfixed code (client times out, no result written).
make check-asan: 46 binaries clean. make check-tsan: 46 binaries, no races.
2026-11-24 07:57:35 +00:00

276 lines
14 KiB
Python

# fake Telegram Bot API + fake OpenAI streaming endpoint for tests.
# argv: port, file the model asks to write, log of sent messages, answer word.
#
# The first update asks for work; the model answers with a write tool call.
# When the gateway asks for approval with an inline keyboard, the fake sends:
# - a question (must be told to wait),
# - a callback from a stranger (must be ignored),
# - the real callback (yes/no), which resolves the approval.
import http.server, json, os, re, sys, threading, time
LOCK = threading.Lock()
INITIAL = sys.argv[5] if len(sys.argv) > 5 else "schreib die datei"
updates = [{"update_id": 1, "message": {"text": INITIAL,
"chat": {"id": 42}, "from": {"id": 7}}}]
next_uid = [2]
sent = []
TARGET = sys.argv[2]
ANSWER = sys.argv[4] if len(sys.argv) > 4 else "ok"
FAILS = [2] # "wiederholen": the first two calls answer HTTP 500
KAPUTT = [1] # "kaputt": the first request sends a tool call with broken JSON
def add_update(text, frm=7):
with LOCK:
updates.append({"update_id": next_uid[0], "message": {"text": text,
"chat": {"id": 42}, "from": {"id": frm}}})
next_uid[0] += 1
def add_callback(data, frm=7):
with LOCK:
updates.append({"update_id": next_uid[0], "callback_query": {
"id": "cb%d" % next_uid[0],
"from": {"id": frm},
"message": {"message_id": 100, "chat": {"id": 42}},
"data": data}})
next_uid[0] += 1
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def reply(self, obj, ctype="application/json"):
b = obj if isinstance(obj, bytes) else json.dumps(obj).encode()
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def body(self):
n = int(self.headers.get("Content-Length", 0))
return self.rfile.read(n)
def do_GET(self):
if "/models" in self.path:
# the OpenAI /v1/models route: /model probe reads this
return self.reply({"data": [{"id": "m"}, {"id": "other"}]})
if "/getUpdates" in self.path:
off = int(re.search(r"offset=(-?\d+)", self.path).group(1))
for _ in range(10):
with LOCK:
got = [u for u in updates if u["update_id"] >= off]
if got:
break
time.sleep(0.2)
return self.reply({"ok": True, "result": got})
self.reply({"ok": True, "result": []})
def do_POST(self):
raw = self.body()
ctype = self.headers.get("Content-Type", "")
if (("/sendPhoto" in self.path or "/sendDocument" in self.path) and
ctype.startswith("multipart/")):
kind = "photo-file" if "/sendPhoto" in self.path else "document-file"
cap = re.search(rb'name="caption"\r\n\r\n(.*?)\r\n', raw, re.S)
fn = re.search(rb'filename="([^"]*)"', raw)
with open(sys.argv[3], "a") as f:
f.write("%s: %s caption=%s\n" % (
kind,
fn.group(1).decode() if fn else "",
cap.group(1).decode() if cap else ""))
return self.reply({"ok": True, "result": {"message_id": 102}})
if "/setMyCommands" in self.path:
req = json.loads(raw)
with open(sys.argv[3], "a") as f:
for c in req.get("commands", []):
f.write("cmd: %s\n" % c.get("command", ""))
return self.reply({"ok": True, "result": True})
if ("/answerCallbackQuery" in self.path or
"/editMessageReplyMarkup" in self.path or
"/setChatMenuButton" in self.path or
"/sendChatAction" in self.path):
return self.reply({"ok": True, "result": True})
if "/sendPhoto" in self.path:
req = json.loads(raw)
with open(sys.argv[3], "a") as f:
f.write("photo: %s caption=%s\n" % (
req.get("photo", ""), req.get("caption", "")))
return self.reply({"ok": True, "result": {"message_id": 101}})
if "/sendMessage" in self.path:
req = json.loads(raw)
text = req.get("text", "")
markup = req.get("reply_markup")
with open(sys.argv[3], "a") as f:
f.write(text.replace("\n", " | ") + "\n")
if req.get("parse_mode"):
# the gateway renders markdown as HTML for Telegram
f.write("mode: %s\n" % req["parse_mode"])
if markup is not None:
f.write("markup: " + json.dumps(
markup, separators=(",", ":")) + "\n")
# /menu: the inline keyboard arrives; press Status. The status
# text itself starts with "Status (", so this does not loop.
if text.startswith("Menü"):
add_callback("status")
# /model: the menu arrives, press the second provider (the tests
# run with SPLINTER_LOCALE=de)
if "Waehle ein Modell" in text:
add_callback("model:far")
if text.startswith("Modell: other (Provider far"):
# only once the switch is confirmed: sent together with the
# button, the turn could be read before the button was
add_update("hallo")
# /connect: one answer per question
if "Neuer Provider" in text:
add_update("testprov")
elif "Endpoint?" in text:
# the fake is its own OpenAI endpoint, so the test turn in
# /connect has somewhere to go
add_update("http://127.0.0.1:%s/v1/chat/completions"
% sys.argv[1])
elif "Welches Modell" in text:
add_update("llama3")
elif "Umgebungsvariable" in text:
add_update("-")
# /model probe: the menu of served models arrives, press the first
cb = [b.get("callback_data", "") for row in (markup or {}).get(
"inline_keyboard", []) for b in row]
if any(c.startswith("mm:") for c in cb):
add_callback("mm:0")
m = re.match(r"Frage (\d+)/", text)
if m:
add_update("antwort-%s" % m.group(1))
# the `ask` tool: the question arrives with its answer hint. Match
# on the question, not on the hint -- the hint is translated and
# this fake runs under SPLINTER_LOCALE=de in the gateway test.
if "Which colour should the login page be?" in text:
add_update(ANSWER)
m = re.match(r"Zustimmung (\d+):", text)
if m:
add_update("was machst du?") # must be told to wait
add_callback("ack:%s:yes" % m.group(1), frm=99) # stranger
add_callback("ack:%s:%s" % (
m.group(1), "yes" if ANSWER == "ok" else "no"))
return self.reply({"ok": True, "result": {"message_id": 100}})
req = json.loads(raw)
has_tool = any(m.get("role") == "tool" for m in req.get("messages", []))
system = " ".join((m.get("content") or "") for m in
req.get("messages", []) if m.get("role") == "system")
last_user = ""
for m in reversed(req.get("messages", [])):
if m.get("role") == "user":
last_user = m.get("content") or ""
break
answer = "ok"
if "wiederholen" in last_user and FAILS[0] > 0:
# a provider that is briefly broken: the harness must retry and
# put the reason in the transcript, not in the input line
FAILS[0] -= 1
self.send_response(500)
self.send_header("Content-Length", "0")
self.end_headers()
return
if "INTERVIEW_COMPLETE" in system:
# the model-driven interview: a summary and the marker; the
# gateway strips it and writes USER.txt
answer = "Testprofil: mag C99.\nINTERVIEW_COMPLETE"
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "wiederholen" in last_user:
answer = "antwort nach dem retry"
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "single word ok" in last_user:
# /connect's test turn
answer = "ok"
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "codebild" in last_user:
# an image inside code is text, not a photo
answer = "`![x](https://example.org/x.png)`\n"
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "lokales bild" in last_user:
p = os.path.join(os.path.dirname(sys.argv[3]), "pic.png")
with open(p, "wb") as f:
f.write(b"\x89PNG\r\n\x1a\n" + b"rest")
answer = "Siehe:\n\n![Lokal](%s)\n" % p
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "kein bild" in last_user:
p = os.path.join(os.path.dirname(sys.argv[3]), "notimg.txt")
with open(p, "w") as f:
f.write("nur text")
answer = "Datei:\n\n![Kein Bild](%s)\n" % p
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "viele zeilen" in last_user:
answer = "".join("Zeile %03d\n" % i for i in range(1, 121))
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "frag den operator" in last_user:
# the `ask` tool: a question with options on the first request,
# then the answer the tool returned is echoed back as the answer
if has_tool:
last = [m for m in req.get("messages", [])
if m.get("role") == "tool"]
got = last[-1].get("content", "") if last else ""
answer = "antwort war: " + str(got)
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
else:
chunks = [{"choices": [{"delta": {"tool_calls": [{
"index": 0, "id": "c1", "type": "function",
"function": {"name": "ask", "arguments": json.dumps({
"question": "Which colour should the login page be?",
"options": ["green", "blue"]})}}]}}]}]
elif "bild" in last_user:
answer = "Hier:\n\n![Ein Bild](https://example.org/b.png)\n\nEnde\n"
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "markdown" in last_user:
answer = "**fett** und `code`\n"
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "tabelle" in last_user:
# a markdown table: the chat must draw columns, not pipes
answer = "| a | b |\n|---|---|\n| 1 | 22 |\n"
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "kaputt" in last_user and KAPUTT[0] > 0:
# a model that sends a tool call whose arguments are not JSON:
# the turn must correct it, and the operator must see that it
# is retrying instead of looking at a silent chat. Only the
# first request is broken; the correction note is not "kaputt",
# so the second one falls through to the normal tool call.
KAPUTT[0] -= 1
chunks = [{"choices": [{"delta": {"tool_calls": [{"index": 0,
"id": "c1", "type": "function", "function": {
"name": "run", "arguments": "{\"command\":"}}]}}]},
{"choices": [{"delta": {}, "finish_reason": "tool_calls"}]}]
elif has_tool:
chunks = [{"choices": [{"delta": {"content": "fertig"}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
else:
args = json.dumps({"path": TARGET, "content": "vom gateway\n"})
chunks = [{"choices": [{"delta": {"tool_calls": [{"index": 0, "id": "c1",
"type": "function", "function": {"name": "write", "arguments": args}}]}}]},
{"choices": [{"delta": {}, "finish_reason": "tool_calls"}]}]
if not req.get("stream"):
# the non-streaming flavour, e.g. provider tests from /connect
return self.reply({"choices": [{"index": 0, "message": {
"role": "assistant", "content": answer},
"finish_reason": "stop"}]})
# the meter: context, cache share and tok/s in the status bar
chunks.append({"choices": [], "usage": {"prompt_tokens": 1290,
"completion_tokens": 50,
"prompt_tokens_details": {"cached_tokens": 800}}})
b = "".join("data: " + json.dumps(c) + "\n\n" for c in chunks) + "data: [DONE]\n\n"
self.reply(b.encode(), "text/event-stream")
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()