feat: ai sessions + Telegram-friendly replies (--system, markdown strip)

pos ai gemini: --session gives ask/chat persistent memory
(~/.local/share/linux_post_install/ai/<name>.json, capped 40 turns),
new 'sessions' subcommand to list/clear; --system injects a Gemini
systemInstruction on every turn without storing it in the session file.
Telegram listener keeps one session per chat (telegram-<chat_id>), clears
on 'ai /reset', passes a Telegram-voice system prompt (emojis welcome),
and strips markdown from replies before sendMessage since messages are
sent as plain text. Docs: howto/ai.md flags/sessions/bridge behavior.
This commit is contained in:
Your Name
2026-08-09 15:32:39 +00:00
parent 1832a88c71
commit 310367f3b2
6 changed files with 191 additions and 30 deletions
+2
View File
@@ -16,6 +16,8 @@ summary (newest last).
## Done
- **2026-08-09** — `pos ai gemini` sessions + Telegram-friendly replies. `--session <name>` gives `ask`/`chat` persistent memory (`~/.local/share/linux_post_install/ai/<name>.json`, capped at 40 turns, pruning keeps the first user turn as scene); new `sessions` subcommand (list / `reset <name>`). Telegram listener now keeps one session per chat (`telegram-<chat_id>`) with `ai /reset` to clear. New `--system "<text>"` flag injects a Gemini `systemInstruction` (via `jq` merge) sent every turn but never stored in the session file; the listener passes a Telegram-voice prompt ("reply like a friendly Telegram chat, use emojis") and strips markdown (`**`, `*`, backticks, `#`, links, lists, blockquotes) from replies before `sendMessage`, since messages go out as plain text. Docs: howto/ai.md (flags, sessions, bridge memory/formatting), `make gen && make check` green.
- **2026-08-09** — Fixed `pos config` secret-value corruption: `cfg_read_secret`'s cursor-advance `echo` went to stdout and, since the function is called via `$(...)`, a leading `\n` ended up inside every secret value → the env file got `AI_GEMINI_API_KEY="\n<key>"`, unreadable by `cfg_value`/`load_config` (menu showed `(not set)`, `pos ai gemini` demanded a key). The newline now goes to the terminal (`echo >&2`). Defense in depth: `cfg_write`/`write_config_key` strip CR and truncate multi-line pastes (warn), `cfg_value` and the ai/telegram `load_config`s strip CR on read. Verified on a real PTY (piped tests couldn't reproduce — non-TTY stdin skips the echo path).
- **2026-08-09** — `ai` category — `pos ai gemini` (ask/chat/models) via Google Gemini REST API. `ask` prints only the answer (pipe/script/Telegram-friendly), `chat` is a multi-turn REPL (q/quit/Ctrl+C, `/reset`, empty input re-prompts), `models` lists generateContent-capable ids and flags the default; `--model` override; default `gemini-2.5-flash`. Config scope `ai` (`AI_GEMINI_API_KEY` secret + `AI_GEMINI_MODEL`) in `~/.config/linux_post_install/ai.env`, edited via `pos config ai`; `config/ai.env` template installed no-clobber by postinstall; `ai-gemini` added to `INTERACTIVE_CMDS`. Telegram listener now answers non-command messages starting with `ai ` via `pos ai gemini ask` (owner chat only; error replies carry the `pos config ai` hint) — future intents (reminders) slot in as more case arms in `handle_message`. Docs: POS.md `ai` section + listener bridge, howto/ai.md, HOWTO/README index rows, `bin/pos` usage example.
+4 -4
View File
@@ -58,7 +58,7 @@ Linux_post_install/
├── bin/ # CLI tools — installed to /usr/local/bin/
│ ├── pos # Main dispatcher — smart arg matching to pos-* scripts
<!-- GEN:START tree -->
│ ├── pos-ai-gemini # Chat with Google Gemini (ask, chat, models)
│ ├── pos-ai-gemini # Chat with Google Gemini (ask, chat, models, sessions)
│ ├── pos-communication-telegram-listener # Telegram bot listener: map /command → bash, run them on chat messages
│ ├── pos-communication-telegram-sender # Send Telegram messages/files/links/stickers via Bot API (send, test)
│ ├── pos-config # Interactive editor for the tools' runtime config (reads # POS_CONFIG: registry)
@@ -253,7 +253,7 @@ All non-interactive `pos` commands log output to `~/.local/share/linux_post_inst
| Category | Command | Script | Description |
|----------|---------|--------|-------------|
<!-- GEN:START dispatch -->
| ai | gemini | `pos-ai-gemini` | Chat with Google Gemini (ask, chat, models) |
| ai | gemini | `pos-ai-gemini` | Chat with Google Gemini (ask, chat, models, sessions) |
| communication | telegram-listener | `pos-communication-telegram-listener` | Telegram bot listener: map /command → bash, run them on chat messages |
| communication | telegram-sender | `pos-communication-telegram-sender` | Send Telegram messages/files/links/stickers via Bot API (send, test) |
| | config | `pos-config` | Interactive editor for the tools' runtime config (reads # POS_CONFIG: registry) |
@@ -560,8 +560,8 @@ Use conventional prefixes: `feat:`, `fix:`, `docs:`, `refactor:`, `chore:`
| `features/autostart.sh` | 14 | Boot-time feature (moved from `bin/`, flag-gated service) |
<!-- GEN:START filetable -->
| `bin/pos` | 277 | CLI dispatcher with smart arg matching + logging + category help |
| `bin/pos-ai-gemini` | 198 | Chat with Google Gemini (ask, chat, models) |
| `bin/pos-communication-telegram-listener` | 526 | Telegram bot listener: map /command → bash, run them on chat messages |
| `bin/pos-ai-gemini` | 311 | Chat with Google Gemini (ask, chat, models, sessions) |
| `bin/pos-communication-telegram-listener` | 559 | Telegram bot listener: map /command → bash, run them on chat messages |
| `bin/pos-communication-telegram-sender` | 221 | Send Telegram messages/files/links/stickers via Bot API (send, test) |
| `bin/pos-config` | 80 | Interactive editor for the tools' runtime config (reads # POS_CONFIG: registry) |
| `bin/pos-docker-compose` | 366 | Docker Compose service manager (ls/up/down/restart/logs/update/config) |
+13
View File
@@ -6,8 +6,13 @@ Tools: `gemini` (`ask`, `chat`, `models`).
| Tool | What it does |
|------|--------------|
| `pos ai gemini ask "<prompt>"` | One-shot answer to stdout (scriptable) |
| `pos ai gemini ask --session <name> "…"` | Same, but remembers prior turns |
| `pos ai gemini chat` | Interactive multi-turn conversation |
| `pos ai gemini models` | List available model ids |
| `pos ai gemini sessions` | List/clear persistent sessions (`reset <name>`) |
Shared flags: `--model <id>` overrides the model; `--system "<text>"` adds a
system instruction to every turn (kept out of the session file).
---
@@ -50,6 +55,14 @@ Set a different model per message:
you: ai --model gemini-2.5-flash explain a Raft consensus log
```
### Telegram memory & formatting
Each chat has its own persistent session (`telegram-<chat id>`), so the model
remembers the conversation; `ai /reset` clears it. The listener passes a system
prompt telling the model it is answering in a Telegram chat — so it uses emojis
and stays lively — and strips markdown (`**x**`, backticks, `#`, links…) from
the reply before sending it, since messages go out as plain text.
## Recipes
- **Answer from a file:** `pos ai gemini ask "$(cat notes.txt)"`
+132 -19
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
# POS: ai gemini — Chat with Google Gemini (ask, chat, models)
# POS_SUBCMDS: ask chat models
# POS_FLAGS: --model
# POS: ai gemini — Chat with Google Gemini (ask, chat, models, sessions)
# POS_SUBCMDS: ask chat models sessions
# POS_FLAGS: --model --session --system
# POS_CONFIG: ai | ai.env | AI_GEMINI_API_KEY=secret:API key from aistudio.google.com | AI_GEMINI_MODEL=:Model id (default gemini-2.5-flash)
source "$(dirname "$0")/../lib/common.sh" 2>/dev/null || source "$(dirname "$0")/common.sh"
@@ -10,22 +10,35 @@ source "$(dirname "$0")/../lib/common.sh" 2>/dev/null || source "$(dirname "$0")
CONFIG_FILE="$HOME/.config/linux_post_install/ai.env"
API="https://generativelanguage.googleapis.com/v1beta"
DEFAULT_MODEL="gemini-2.5-flash"
SESSION_DIR="$HOME/.local/share/linux_post_install/ai"
SESSION=""
SYSTEM_PROMPT=""
MAX_SESSION_TURNS=40
usage() {
cat <<EOF
Usage: pos ai gemini <subcommand> [--model <id>]
Usage: pos ai gemini <subcommand> [--model <id>] [--session <name>] [--system <text>]
Chat with Google Gemini via the REST API (generativelanguage.googleapis.com).
Subcommands:
ask "<prompt>" One-shot answer; prints ONLY the answer text to stdout
(pipe/script/Telegram-friendly). The prompt may also be
piped in via stdin when no argument is given.
piped in via stdin when no argument is given. With
--session, previous turns are sent as context.
chat Interactive multi-turn conversation.
models List models that support generateContent.
sessions List persistent sessions / clear one:
'sessions' and 'sessions reset <name>'.
Options:
--model <id> Override the model for this invocation.
--session <name> Persistent memory: ask/chat remember prior turns in
~/.local/share/linux_post_install/ai/<name>.json
(capped at $MAX_SESSION_TURNS turns). ask without
--session stays one-shot.
--system <text> System instruction sent with every turn (kept out of the
session file), e.g. "Reply like a friendly Telegram chat".
-h|--help This help.
Config: $CONFIG_FILE (edit with 'pos config ai')
@@ -38,6 +51,10 @@ Examples:
pos ai gemini chat
pos ai gemini models
pos ai gemini ask --model gemini-2.5-flash "hi"
pos ai gemini ask --session work "my name is joe"
pos ai gemini ask --session work "what is my name?" # remembers
pos ai gemini sessions
pos ai gemini sessions reset work
EOF
exit 0
}
@@ -74,24 +91,69 @@ resolve_model() {
fi
}
# One generateContent call. $1 = model, $2 = contents JSON array.
# ── Persistent session memory ───────────────────────────────────
# History lives as a Gemini "contents" JSON document per session name under
# SESSION_DIR. Names are sanitized to [A-Za-z0-9_-]; ask/chat only touch the
# session layer when --session is given (otherwise they stay stateless).
session_file() {
local name="${1:-$SESSION}"
name="${name//[^A-Za-z0-9_-]/_}"
printf '%s/%s.json' "$SESSION_DIR" "$name"
}
session_load() {
[ -n "$SESSION" ] || { printf '{"contents":[]}'; return 0; }
local f
f="$(session_file)"
if [ -s "$f" ] && jq -e '.contents' "$f" >/dev/null 2>&1; then
cat "$f"
else
printf '{"contents":[]}'
fi
}
session_save() {
[ -n "$SESSION" ] || return 0
local f tmp
f="$(session_file)"
mkdir -p "$SESSION_DIR"
tmp="$(mktemp)"
printf '%s\n' "$1" >"$tmp"
mv "$tmp" "$f"
chmod 600 "$f"
}
# Append a turn and prune to the last MAX_SESSION_TURNS entries. stdout = JSON.
session_push() {
local contents="$1" role="$2" text="$3"
printf '%s' "$contents" | jq -c --arg r "$role" --arg t "$text" \
'.contents += [{role:$r, parts:[{text:$t}]}] | .contents |= .[-'"$MAX_SESSION_TURNS"':]'
}
# One generateContent call. $1 = model, $2 = contents JSON, $3 = optional
# system instruction (added as systemInstruction, not stored in the session).
# stdout = the answer text on success; an error message on failure (exit 1).
gemini_generate() {
local model="$1" contents="$2"
local resp code body errmsg
local model="$1" contents="$2" system="${3:-}" body
body="$contents"
if [ -n "$system" ]; then
body="$(printf '%s' "$contents" | jq -c --arg s "$system" \
'. + {systemInstruction:{role:"system",parts:[{text:$s}]}}')"
fi
local resp code body_out errmsg
resp="$(curl -sS -m 60 -X POST "${API}/models/${model}:generateContent" \
-H "x-goog-api-key: ${AI_GEMINI_API_KEY}" \
-H "Content-Type: application/json" \
--write-out $'\n%{http_code}' \
--data "$contents")" || { echo "request failed (curl exit $?)" >&2; return 1; }
--data "$body")" || { echo "request failed (curl exit $?)" >&2; return 1; }
code="${resp##*$'\n'}"
body="${resp%$'\n'*}"
body_out="${resp%$'\n'*}"
if [ "$code" != "200" ]; then
errmsg="$(printf '%s' "$body" | jq -r '.error.message // empty' 2>/dev/null || true)"
errmsg="$(printf '%s' "$body_out" | jq -r '.error.message // empty' 2>/dev/null || true)"
echo "API error $code${errmsg:+: $errmsg}" >&2
return 1
fi
printf '%s' "$body" | jq -r '[.candidates[0].content.parts[]?.text] | join("")'
printf '%s' "$body_out" | jq -r '[.candidates[0].content.parts[]?.text] | join("")'
}
cmd_ask() {
@@ -103,10 +165,19 @@ cmd_ask() {
fi
[ -n "$prompt" ] || err "No prompt given — usage: pos ai gemini ask \"<prompt>\""
require_key
contents="$(jq -nc --arg t "$prompt" '{contents:[{role:"user",parts:[{text:$t}]}]}')"
if ! out="$(gemini_generate "$(resolve_model)" "$contents" 2>&1)"; then
if [ -n "$SESSION" ]; then
contents="$(session_load)"
contents="$(session_push "$contents" user "$prompt")"
else
contents="$(jq -nc --arg t "$prompt" '{contents:[{role:"user",parts:[{text:$t}]}]}')"
fi
if ! out="$(gemini_generate "$(resolve_model)" "$contents" "$SYSTEM_PROMPT" 2>&1)"; then
err "$out"
fi
if [ -n "$SESSION" ]; then
contents="$(session_push "$contents" model "$out")"
session_save "$contents"
fi
printf '%s\n' "$out"
}
@@ -115,7 +186,12 @@ cmd_chat() {
local model contents text answer
model="$(resolve_model)"
require_key
contents='{"contents":[]}'
if [ -n "$SESSION" ]; then
contents="$(session_load)"
printf 'session: %s (resumed %s prior turns)\n' "$SESSION" "$(printf '%s' "$contents" | jq -r '.contents | length')"
else
contents='{"contents":[]}'
fi
trap 'echo; echo "bye"; exit 0' INT
echo "Gemini · ${model} — type a message; q=quit, /reset=clear history"
while true; do
@@ -124,20 +200,50 @@ cmd_chat() {
case "$text" in
"" ) continue ;;
q|Q|quit|exit) echo; echo "bye"; return 0 ;;
/reset) contents='{"contents":[]}'; echo "[history cleared]"; continue ;;
/reset)
contents='{"contents":[]}'
[ -n "$SESSION" ] && session_save "$contents"
echo "[history cleared]"
continue ;;
esac
contents="$(printf '%s' "$contents" | jq -c --arg t "$text" '.contents += [{role:"user",parts:[{text:$t}]}]')"
if ! answer="$(gemini_generate "$model" "$contents" 2>&1)"; then
contents="$(session_push "$contents" user "$text")"
if ! answer="$(gemini_generate "$model" "$contents" "$SYSTEM_PROMPT" 2>&1)"; then
warn "AI error: $answer"
continue
fi
contents="$(printf '%s' "$contents" | jq -c --arg t "$answer" '.contents += [{role:"model",parts:[{text:$t}]}]')"
contents="$(session_push "$contents" model "$answer")"
[ -n "$SESSION" ] && session_save "$contents"
printf '\n%s\n\n' "$answer"
done
echo
return 0
}
cmd_sessions() {
local action="${1:-list}" name f n
case "$action" in
list|"")
[ -d "$SESSION_DIR" ] || { echo "no sessions"; return 0; }
local found=0
for f in "$SESSION_DIR"/*.json; do
[ -f "$f" ] || continue
found=1
n="$(jq -r '.contents | length' "$f" 2>/dev/null || echo 0)"
printf ' %-32s %s turns\n' "$(basename "$f" .json)" "${n:-0}"
done
[ "$found" -eq 1 ] || echo "no sessions"
;;
reset)
[ $# -ge 2 ] || err "usage: pos ai gemini sessions reset <name>"
name="$2"
if rm -f "$(session_file "$name")"; then
ok "session '$name' cleared"
fi
;;
*) err "Unknown sessions subcommand '$action' (list | reset <name>)" ;;
esac
}
cmd_models() {
[ $# -eq 0 ] || err "Unexpected argument for models: $*"
local model resp code body m
@@ -178,6 +284,12 @@ while [ $# -gt 0 ]; do
--model)
[ $# -ge 2 ] || err "--model needs a value"
MODEL_OVERRIDE="$2"; shift 2 ;;
--session)
[ $# -ge 2 ] || err "--session needs a value"
SESSION="$2"; shift 2 ;;
--system)
[ $# -ge 2 ] || err "--system needs a value"
SYSTEM_PROMPT="$2"; shift 2 ;;
-*) err "Unknown option '$1' (see --help)" ;;
*)
if [ -z "$cmd" ]; then
@@ -194,5 +306,6 @@ case "${cmd:-}" in
ask) cmd_ask "${args[@]}" ;;
chat) cmd_chat "${args[@]}" ;;
models) cmd_models "${args[@]}" ;;
sessions) cmd_sessions "${args[@]}" ;;
*) err "Unknown ai gemini subcommand '$cmd' (see --help)" ;;
esac
+38 -5
View File
@@ -10,6 +10,10 @@ API="https://api.telegram.org"
SERVICE="pos-telegram-listener.service"
USER_SYSTEMD_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
# System prompt for the "ai " bridge: replies are posted straight into the
# chat, so ask for concise, emoji-friendly Telegram-style answers.
AI_SYSTEM="You are a friendly assistant chatting in a Telegram chat. Keep replies concise, use emojis and light formatting to make them lively, and never claim to send messages yourself."
err() { echo "ERROR: $*" >&2; exit 1; }
log() { echo "[+] $*"; }
warn() { echo "[!] $*" >&2; }
@@ -429,6 +433,24 @@ reply() {
|| warn "reply failed (rc ${rc:-?})"
}
# Strip common markdown so AI output reads cleanly in a plain-text
# Telegram message (no parse_mode is used).
strip_markdown() {
local t="$1"
t="$(printf '%s' "$t" | sed -E \
-e 's/!\[[^]]*\]\([^)]*\)//g' \
-e 's/\[([^]]*)\]\([^)]*\)/\1/g' \
-e 's/\*\*([^*]*)\*\*/\1/g' \
-e 's/\*([^*]*)\*/\1/g' \
-e 's/__([^_]*)__/\1/g' \
-e 's/`([^`]*)`/\1/g' \
-e 's/^[[:space:]]*#{1,6}[[:space:]]+//' \
-e 's/^[[:space:]]*>[[:space:]]?//' \
-e 's/^[[:space:]]*([-*+]|[0-9]+\.)[[:space:]]+/• /')"
t="$(printf '%s' "$t" | sed -E '/^[[:space:]]*([-*_][[:space:]]*){3,}[[:space:]]*$/d')"
printf '%s' "$t"
}
handle_message() {
local text="$1" msg_id="$2" value output rc quiet=0
case "$text" in
@@ -437,14 +459,25 @@ handle_message() {
return ;;
esac
# AI bridge: non-command text starting with "ai " (case-insensitive) is
# forwarded to Gemini; the model's answer is replied verbatim. Future
# non-command intents (e.g. reminders) slot in as more case arms here.
# forwarded to Gemini; the model's answer is replied verbatim. Each chat
# gets its own persistent memory session ("telegram-<chat_id>"); the exact
# prompt "ai /reset" clears it. Future non-command intents (e.g. reminders)
# slot in as more case arms here.
if [[ "$text" != /* && "$text" =~ ^[Aa][Ii][[:space:]](.*)$ ]]; then
local prompt="${BASH_REMATCH[1]}" answer
local prompt="${BASH_REMATCH[1]}" answer session
[ -n "$prompt" ] || { reply "Usage: ai <prompt> — e.g. 'ai what is Nvidia'" "$msg_id"; return; }
session="telegram-${TELEGRAM_CHAT_ID}"
if [[ "$prompt" =~ ^/?reset[[:space:]]*$ ]]; then
if pos ai gemini sessions reset "$session" >/dev/null 2>&1; then
reply "Memory cleared." "$msg_id"
else
reply "AI error: could not clear memory" "$msg_id"
fi
return
fi
log "ai: $prompt"
if answer="$(timeout 120 pos ai gemini ask "$prompt" 2>&1)"; then
reply "$answer" "$msg_id"
if answer="$(timeout 120 pos ai gemini ask --session "$session" --system "$AI_SYSTEM" "$prompt" 2>&1)"; then
reply "$(strip_markdown "$answer")" "$msg_id"
else
[ -n "$answer" ] || answer="timed out after 120s"
reply "AI error: $answer" "$msg_id"
+2 -2
View File
@@ -3,7 +3,7 @@
# Install: source this file in ~/.bashrc or place in /etc/bash_completion.d/
# GEN:START posflags
declare -A _pos_flags
_pos_flags[ai-gemini]="--model"
_pos_flags[ai-gemini]="--model --session --system"
_pos_flags[communication-telegram-listener]="--enable --disable --status --sync-commands --run"
_pos_flags[communication-telegram-sender]="--type --caption --parse-mode --no-preview --token --chat-id --markdown"
_pos_flags[entertainment-send]="--print --markdown"
@@ -14,7 +14,7 @@ _pos_flags[usb-server]="--ls --ls-shared --share --unshare --auto-share --callba
# GEN:END posflags
# GEN:START possubcmds
declare -A _pos_subcmds
_pos_subcmds[ai-gemini]="ask chat models"
_pos_subcmds[ai-gemini]="ask chat models sessions"
_pos_subcmds[communication-telegram-sender]="send test"
_pos_subcmds[docker-compose]="ls installed up down restart logs update config"
_pos_subcmds[docker-vbox]="create enter stop start rm ls"