Files
splinter/tests/fake_telegram.py
T
lotherk af2001bfee ui, model, cost and idle timeouts
- lcm: the sidebar widget and /status segment show the context, the number of
  compactions, messages and bytes of the last cut, and how many old tool
  outputs were trimmed. The counters are the compactor's own, not an estimate.
- cost: a provider-reported USD cost (usage.cost/cost_usd) is carried through
  sse/openai, the agent and the engine. /cost reports it with the cache share
  and splits judged from plain turns; the notes say that an upstream judge is
  not visible in the provider's usage. The status plugin and junction prefer
  the reported number over list-price arithmetic.
- curses: the running turn's seconds moved from the input line to the status
  bar. Notes and errors are transcript rows below the cause, never text in the
  input line or the status bar; a failed backend request is a status row and is
  retried by the agent. The steer prompt is only "steer> " and what was typed.
- model: /model probe works in the chat. The picker lists the configuration at
  once, then asks the endpoint the session is on what it serves and adds those
  models, so a router's whole menu is selectable. provider/model selectors now
  apply the right provider instead of becoming a model name. The choice is
  written to <session>.model and restored when that session is reopened; /new
  carries the current model into the new session.
- sidebar: plugin titles are bold and underlined (this curses has no italic
  attribute), with a rule between the plugin blocks.
- run/cli: a command timeout is an idle window. Every chunk on stdout or
  stderr resets it, and the process is asked with waitpid(WNOHANG) whether it
  is still there before the window is extended. A long build that keeps
  reporting progress is no longer killed for being long; a silent hang is.
- config: ';' separates settings on one line, so
  plugin lcm { keep = 6; tool_trim = 8192 } parses as two keys.
- tests: lcm widget/status counters, one-line config blocks, session model
  restore and /model probe, cli idle timeout with a talkative and a silent
  command, run output reset, and the UI status/retry rows.

make check: all tests passed.
2026-11-17 23:21:56 +00:00

238 lines
11 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
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
"/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")
# /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))
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 "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 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()