lobsta 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lobsta/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """lobsta: a small self-hosted Telegram assistant for any OpenAI-compatible model."""
2
+
3
+ __version__ = "0.3.0"
lobsta/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from lobsta.cli import main
2
+
3
+ raise SystemExit(main())
lobsta/access.py ADDED
@@ -0,0 +1,66 @@
1
+ """Who may use the bot: Telegram user IDs in <home>/allowed-users, added by pairing.
2
+
3
+ While nobody is allowed, a one-time code is kept in <home>/pairing-code (shown when lobsta
4
+ starts and by `lobsta doctor`). Sending "/pair CODE" from Telegram adds that account and
5
+ deletes the code. A paired user can create a new code with "/pair new". Five wrong attempts
6
+ replace the code.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import secrets
11
+ from pathlib import Path
12
+
13
+ ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # no 0/O, 1/I
14
+
15
+
16
+ class Access:
17
+ def __init__(self, home: Path):
18
+ self.allowed_file = home / "allowed-users"
19
+ self.code_file = home / "pairing-code"
20
+ self.failures = 0
21
+
22
+ @staticmethod
23
+ def _lines(path: Path) -> list[str]:
24
+ try:
25
+ return [s.strip() for s in path.read_text(encoding="utf-8").splitlines() if s.strip() and not s.startswith("#")]
26
+ except FileNotFoundError:
27
+ return []
28
+
29
+ def allowed(self) -> set[str]:
30
+ return set(self._lines(self.allowed_file))
31
+
32
+ def code(self) -> str | None:
33
+ return next(iter(self._lines(self.code_file)), None)
34
+
35
+ def new_code(self) -> str:
36
+ code = "".join(secrets.choice(ALPHABET) for _ in range(8))
37
+ self.code_file.write_text(f'# One-time pairing code: send "/pair {code}" to the bot. Deleted after use.\n{code}\n',
38
+ encoding="utf-8")
39
+ self.failures = 0
40
+ return code
41
+
42
+ def ensure_code(self) -> str | None:
43
+ """A pairing code if nobody is allowed yet."""
44
+ if self.allowed():
45
+ return None
46
+ return self.code() or self.new_code()
47
+
48
+ def pair(self, user_id: int | str, attempt: str | None) -> str:
49
+ """'paired' | 'already' | 'wrong' | 'none'"""
50
+ uid = str(user_id)
51
+ if uid in self.allowed():
52
+ return "already"
53
+ code = self.code()
54
+ if not code:
55
+ return "none"
56
+ if (attempt or "").strip().upper() != code:
57
+ self.failures += 1
58
+ if self.failures >= 5:
59
+ self.new_code()
60
+ return "wrong"
61
+ existing = self.allowed_file.read_text(encoding="utf-8") if self.allowed_file.exists() else \
62
+ "# Telegram user IDs allowed to use the bot, one per line (added by /pair).\n"
63
+ self.allowed_file.write_text(existing.rstrip("\n") + f"\n{uid}\n", encoding="utf-8")
64
+ self.code_file.unlink(missing_ok=True)
65
+ self.failures = 0
66
+ return "paired"
lobsta/agent.py ADDED
@@ -0,0 +1,285 @@
1
+ """The agent loop: send the conversation to the model, run the tools it asks for, repeat
2
+ until it answers in plain text (or max_steps is reached)."""
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import mimetypes
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Callable
11
+
12
+ from lobsta import llm, tools as toolbox
13
+ from lobsta.config import Config, Model
14
+ from lobsta.store import Conversation
15
+
16
+ # Deliberately short: small models follow ~100-word prompts better than long ones, and every
17
+ # rule here competes with the conversation for attention. Override with <home>/system.md.
18
+ SYSTEM_PROMPT = """You are lobsta, a personal assistant chatting with the user on Telegram. Today is {date}. You run on the model {model}.
19
+
20
+ {tool_notes}
21
+ - If you are unsure or a source fails, say so. Never invent facts, numbers or links.
22
+ - Be helpful, direct and concise; go into depth when asked. Reply in the user's language.
23
+ - Formatting: Telegram shows **bold**, *italic*, `code`, code blocks and [links](https://example.com). No tables or # headings."""
24
+
25
+ TOOL_NOTES = {
26
+ "web_search": "- Search the web for anything current or checkable, and cite sources as links. fetch reads a page in full.",
27
+ "calc": "- Calculate with calc, never in your head: percentages, interest, conversions, anything beyond single-digit arithmetic.",
28
+ "python": "- Calculate with python, never in your head: percentages, interest, conversions, anything beyond "
29
+ "single-digit arithmetic. Also use it "
30
+ "for data, files and charts: /workspace keeps this conversation's files, including ones the user sends. "
31
+ "send_file shares a file with the user.",
32
+ }
33
+
34
+ OLD_TOOL_RESULT = 2000 # characters kept from tool results of earlier turns
35
+ IMAGE_SIZE = 3000 # an image costs the model ~1,000 tokens, whatever its file size
36
+
37
+
38
+ def system_prompt(config: Config, model: Model, tools: dict) -> str:
39
+ custom = config.home / "system.md"
40
+ template = custom.read_text(encoding="utf-8") if custom.exists() else SYSTEM_PROMPT
41
+ notes = "\n".join(note for name, note in TOOL_NOTES.items() if name in tools)
42
+ return template.replace("{date}", time.strftime("%A, %d %B %Y")).replace("{model}", model.name).replace("{tool_notes}", notes)
43
+
44
+
45
+ def _image_part(conv: Conversation, part: dict, current: bool, vision: bool):
46
+ rel = part["path"]
47
+ if current and vision:
48
+ path = conv.dir / rel
49
+ kind = mimetypes.guess_type(path.name)[0] or "image/jpeg"
50
+ data = base64.b64encode(path.read_bytes()).decode()
51
+ return {"type": "image_url", "image_url": {"url": f"data:{kind};base64,{data}"}}
52
+ where = rel.removeprefix("workspace/")
53
+ note = "" if vision else " This model cannot see images; say so if the user asks about it."
54
+ return {"type": "text", "text": f"[image: /workspace/{where}]{note}"}
55
+
56
+
57
+ def _close_interrupted(msgs: list[dict]) -> list[dict]:
58
+ """Every tool call needs a result before the next non-tool message (a /stop or crash can
59
+ leave calls unanswered; servers reject such histories)."""
60
+ out, pending = [], []
61
+ for m in msgs:
62
+ if m["role"] == "tool":
63
+ pending = [p for p in pending if p != m.get("tool_call_id")]
64
+ elif pending:
65
+ out += [{"role": "tool", "tool_call_id": p, "content": "[interrupted]"} for p in pending]
66
+ pending = []
67
+ out.append(m)
68
+ if m["role"] == "assistant":
69
+ pending = [c["id"] for c in m.get("tool_calls") or []]
70
+ return out
71
+
72
+
73
+ def _size(m: dict) -> int:
74
+ """Roughly how much of the context a message takes, in characters (~3 per token). Text is
75
+ counted as written (not JSON-escaped, which inflates non-Latin scripts) and an image at a
76
+ fixed cost (its base64 data says nothing about its token count)."""
77
+ content = m.get("content") or ""
78
+ if isinstance(content, list):
79
+ n = sum(len(p.get("text", "")) if p.get("type") == "text" else IMAGE_SIZE for p in content)
80
+ else:
81
+ n = len(str(content))
82
+ n += len(m.get("reasoning_content") or "")
83
+ for call in m.get("tool_calls") or []:
84
+ fn = call.get("function") or {}
85
+ n += len(fn.get("name") or "") + len(fn.get("arguments") or "")
86
+ return n + 20
87
+
88
+
89
+ def _budget(model: Model) -> int:
90
+ """How much of the conversation the model gets, in characters: ~60% of its context (~3
91
+ characters per token), leaving room for tools, thinking and the answer."""
92
+ return int(model.context * 0.6 * 3)
93
+
94
+
95
+ def _summary(conv: Conversation) -> tuple[str, int]:
96
+ """The latest summary of earlier messages, and the index of the first message it doesn't cover."""
97
+ for m in reversed(conv.messages):
98
+ if m["role"] == "summary":
99
+ return m["content"], m["from"]
100
+ return "", 0
101
+
102
+
103
+ def _prepared(conv: Conversation, model: Model) -> list[dict]:
104
+ """The messages since the latest summary as the model sees them: the current turn's images
105
+ resolved, old tool output shortened, old reasoning dropped, interrupted tool calls closed."""
106
+ msgs = [m for m in conv.messages[_summary(conv)[1]:] if m["role"] != "summary"]
107
+ last_user = max((i for i, m in enumerate(msgs) if m["role"] == "user"), default=0)
108
+ out = []
109
+ for i, m in enumerate(msgs):
110
+ m = dict(m)
111
+ if m["role"] == "user" and isinstance(m.get("content"), list):
112
+ m["content"] = [_image_part(conv, p, i == last_user, model.vision) if p.get("type") == "image_file" else p
113
+ for p in m["content"]]
114
+ if i < last_user:
115
+ m.pop("reasoning_content", None)
116
+ if m["role"] == "tool" and len(m.get("content", "")) > OLD_TOOL_RESULT:
117
+ m["content"] = m["content"][:OLD_TOOL_RESULT] + "\n[... shortened ...]"
118
+ out.append(m)
119
+ return _close_interrupted(out)
120
+
121
+
122
+ def window(conv: Conversation, model: Model) -> list[dict]:
123
+ """The conversation as sent to the model. Compaction normally keeps it within the budget;
124
+ if it doesn't (a failed summary, one very long turn), the oldest turns are dropped and then
125
+ the current turn's oldest tool results shortened."""
126
+ out = _prepared(conv, model)
127
+ budget = _budget(model)
128
+ sizes = [_size(m) for m in out]
129
+ total, start = sum(sizes), 0
130
+ while total > budget:
131
+ nxt = next((j for j in range(start + 1, len(out)) if out[j]["role"] == "user"), None)
132
+ if nxt is None:
133
+ break
134
+ total -= sum(sizes[start:nxt])
135
+ start = nxt
136
+ out = out[start:]
137
+ for m in out:
138
+ if total <= budget:
139
+ break
140
+ if m["role"] == "tool" and len(m.get("content", "")) > OLD_TOOL_RESULT:
141
+ total -= len(m["content"]) - OLD_TOOL_RESULT
142
+ m["content"] = m["content"][:OLD_TOOL_RESULT] + "\n[... shortened ...]"
143
+ return out
144
+
145
+
146
+ def messages(config: Config, model: Model, conv: Conversation, tools: dict) -> list[dict]:
147
+ """The request's messages: system prompt (with the summary of earlier messages, if any) and
148
+ the conversation window."""
149
+ system = system_prompt(config, model, tools)
150
+ summary = _summary(conv)[0]
151
+ if summary:
152
+ system += f"\n\nSummary of the earlier part of this conversation:\n{summary}"
153
+ return [{"role": "system", "content": system}, *window(conv, model)]
154
+
155
+
156
+ SUMMARY_PROMPT = """Below is the earlier part of your conversation with the user. Write the summary you will continue the conversation from: who the user is and what they prefer, what they asked, what you found or decided (with the numbers, names and source links that matter), files in /workspace, and anything still open. Long messages are abbreviated in this transcript, marked "[rest omitted here]"; they were complete, so don't note them as cut off. Plain text, at most 400 words, in the conversation's language."""
157
+ KEEP_RECENT = 0.25 # share of the budget kept word for word when compacting: the latest turns
158
+
159
+
160
+ def _transcript(msgs: list[dict], limit: int) -> str:
161
+ """Messages as plain text for the summary request. If that is longer than limit, the
162
+ assistant's answers and tool results are shortened, never dropped: the user's own messages
163
+ carry what must be remembered."""
164
+ def short(s: str, n: int) -> str:
165
+ return s if len(s) <= n else s[:n] + " [rest omitted here]"
166
+
167
+ def text(m: dict, cap: int) -> str:
168
+ content = m.get("content") or ""
169
+ if isinstance(content, list):
170
+ content = " ".join(p.get("text", "") if p.get("type") == "text" else f"[image {p.get('path', '')}]"
171
+ for p in content)
172
+ if m["role"] == "user":
173
+ return f"User: {short(content, 4000)}"
174
+ if m["role"] == "tool":
175
+ return f"[tool result] {short(content, cap // 4)}"
176
+ calls = ", ".join(f"{c['function']['name']} {c['function'].get('arguments') or ''}"[:200]
177
+ for c in m.get("tool_calls") or [])
178
+ return f"Assistant: {short(content, cap)}" + (f" [used {calls}]" if calls else "")
179
+
180
+ for cap in (4000, 1500, 600, 200):
181
+ out = "\n\n".join(t for m in msgs if (t := text(m, cap)).strip() not in ("User:", "Assistant:", "[tool result]"))
182
+ if len(out) <= limit:
183
+ break
184
+ return out[-limit:] # only if the user's messages alone don't fit
185
+
186
+
187
+ def compact(model: Model, conv: Conversation, request_box: list, status: Callable[[str], None]) -> bool:
188
+ """When the conversation since the latest summary no longer fits the budget, summarize all
189
+ but its latest turns with the model; the summary is stored in the history (nothing is
190
+ deleted). A small context keeps a local model accurate and fast, and since this happens
191
+ once per budget's worth of conversation, the server can reuse its cache in between."""
192
+ budget = _budget(model)
193
+ if sum(_size(m) for m in _prepared(conv, model)) <= budget:
194
+ return False
195
+ old_summary, start = _summary(conv)
196
+ msgs = conv.messages
197
+ users = [i for i in range(start, len(msgs)) if msgs[i]["role"] == "user"]
198
+ if len(users) < 2:
199
+ return False # only the current turn: nothing earlier to summarize
200
+ keep, tail = users[-1], sum(_size(m) for m in msgs[users[-1]:] if m["role"] != "summary")
201
+ for a, b in zip(reversed(users[:-1]), reversed(users[1:])):
202
+ tail += sum(_size(m) for m in msgs[a:b] if m["role"] != "summary")
203
+ if tail > budget * KEEP_RECENT:
204
+ break
205
+ keep = a
206
+ older = [m for m in msgs[start:keep] if m["role"] != "summary"]
207
+ if not older:
208
+ return False
209
+ status("🗜 Summarizing the earlier conversation")
210
+ prompt = SUMMARY_PROMPT + (f"\n\nSummary of what came before:\n{old_summary}" if old_summary else "")
211
+ # no tools and a short answer: this request may use ~75% of the context (the rest: thinking)
212
+ prompt += "\n\nConversation:\n" + _transcript(older, int(model.context * 0.75 * 3))
213
+ request = llm.Request()
214
+ request_box[:] = [request]
215
+ try:
216
+ reply = llm.chat(model, [{"role": "user", "content": prompt}], [], request)
217
+ except llm.Cancelled:
218
+ raise
219
+ except llm.LLMError:
220
+ return False # the window's trimming still keeps the request within the context
221
+ text = (reply.get("content") or "").strip()
222
+ if not text:
223
+ return False
224
+ conv.append({"role": "summary", "content": text, "from": keep})
225
+ return True
226
+
227
+
228
+ def run(config: Config, model: Model, conv: Conversation, tools: dict, turn: toolbox.Turn,
229
+ request_box: list, status: Callable[[str], None]) -> str:
230
+ """Process the conversation's latest user message; returns the final answer text."""
231
+ schemas = [t.schema() for t in tools.values()]
232
+ compact(model, conv, request_box, status)
233
+ seen: dict[str, int] = {} # identical calls in this turn: small models can loop on them
234
+ for step in range(config.max_steps):
235
+ if turn.cancelled.is_set():
236
+ raise llm.Cancelled()
237
+ request = llm.Request()
238
+ request_box[:] = [request]
239
+ reply = llm.chat(model, messages(config, model, conv, tools), schemas, request)
240
+ calls = reply.get("tool_calls") or []
241
+ message = {"role": "assistant", "content": reply.get("content") or ""}
242
+ if reply.get("reasoning_content"):
243
+ message["reasoning_content"] = reply["reasoning_content"]
244
+ if calls:
245
+ message["tool_calls"] = [{"id": c.get("id") or f"call_{step}_{n}", "type": "function",
246
+ "function": {"name": c["function"]["name"], "arguments": c["function"].get("arguments") or "{}"}}
247
+ for n, c in enumerate(calls)]
248
+ conv.append(message)
249
+ if not calls:
250
+ return message["content"].strip()
251
+ for call in message["tool_calls"]:
252
+ if turn.cancelled.is_set():
253
+ raise llm.Cancelled()
254
+ name, raw = call["function"]["name"], call["function"]["arguments"]
255
+ tool = tools.get(name)
256
+ try:
257
+ label = tool.label(json.loads(raw)) if tool else ""
258
+ except Exception:
259
+ label = ""
260
+ key = f"{name}:{raw}"
261
+ seen[key] = seen.get(key, 0) + 1
262
+ if seen[key] > 1:
263
+ result = "Error: you already made this exact call in this turn; use its result, try something different, or answer."
264
+ else:
265
+ status(label or f"🔧 {name}")
266
+ result = toolbox.call(tools, name, raw, turn)
267
+ conv.append({"role": "tool", "tool_call_id": call["id"], "content": result})
268
+ conv.append({"role": "user", "content": "[system: step limit reached; summarize what you found so far]"})
269
+ request = llm.Request()
270
+ request_box[:] = [request]
271
+ reply = llm.chat(model, messages(config, model, conv, tools), [], request)
272
+ conv.append({"role": "assistant", "content": reply.get("content") or ""})
273
+ return (reply.get("content") or "").strip()
274
+
275
+
276
+ def save_upload(conv: Conversation, name: str, data: bytes) -> Path:
277
+ """Store a file the user sent in the workspace without overwriting; returns the path."""
278
+ safe = "".join(c if c.isalnum() or c in "._- " else "_" for c in Path(name).name).strip() or "file"
279
+ path = conv.workspace / safe
280
+ n = 1
281
+ while path.exists():
282
+ path = conv.workspace / f"{Path(safe).stem}-{n}{Path(safe).suffix}"
283
+ n += 1
284
+ path.write_bytes(data)
285
+ return path