FEAT: Implement Telegram Gateway and Channel-Aware Chat

This commit is contained in:
2026-04-11 15:34:51 -04:00
parent b2acd9c702
commit 8ba3532067
13 changed files with 381 additions and 30 deletions

View File

@@ -66,6 +66,8 @@ Interfaces for conversational event handling and UI integration. Source of truth
(or (and (member (getf proposed-action :type) '(:request :REQUEST))
(or (and (member target '(:emacs :EMACS))
(member action '(:insert-at-end :INSERT-AT-END)))
(and (member target '(:telegram :TELEGRAM))
(or (getf payload :chat-id) (getf proposed-action :chat-id)))
(and (member target '(:shell :SHELL))
(or (getf payload :cmd) (getf proposed-action :cmd)))
(member target '(:tool :TOOL))))
@@ -83,19 +85,26 @@ The Chat skill acts as the conversational UI. Because the ~org-agent~ kernel eva
"Generates a conversational response, stripping system errors from context."
(let* ((payload (getf context :payload))
(raw-text (getf payload :text))
(channel (or (getf payload :channel) :emacs))
(chat-id (getf payload :chat-id))
;; Context Purge: Remove system errors and hallucinations from the history
(clean-text (cl-ppcre:regex-replace-all "(?i)Unknown request|System Error.*|Thinking\\.\\.\\." raw-text ""))
(trimmed-text (if (> (length clean-text) 1000)
(subseq clean-text (- (length clean-text) 1000))
clean-text)))
(ask-neuro trimmed-text :system-prompt "ACTUATOR IDENTITY: You are the pure Lisp actuator for the org-agent kernel.
clean-text))
(reply-instruction
(case channel
(:telegram (format nil "- To reply via Telegram: (:type :REQUEST :target :telegram :chat-id \"~a\" :text \"<Response>\")" chat-id))
(t "- To reply via Emacs: (:type :REQUEST :target :emacs :action :insert-at-end :buffer \"*org-agent-chat*\" :text \"* <Response>\")"))))
(ask-neuro trimmed-text :system-prompt (concatenate 'string
"ACTUATOR IDENTITY: You are the pure Lisp actuator for the org-agent kernel.
MANDATE: Output EXACTLY ONE Common Lisp property list starting with (:type :REQUEST).
ZERO CONVERSATION: Do not explain. Do not use markdown.
STRICT RULE: Never output the strings 'Unknown request' or 'System Error'.
REQUIRED FORMATS:
- To reply: (:type :REQUEST :target :emacs :action :insert-at-end :buffer \"*org-agent-chat*\" :text \"* <Response>\")
- To use a tool: (:type :REQUEST :target :tool :action :call :tool \"<name>\" :args (...))")))
" reply-instruction "
- To use a tool: (:type :REQUEST :target :tool :action :call :tool \"<name>\" :args (...))"))))
#+end_src
* Registration

View File

@@ -96,11 +96,12 @@ This function is the secure getter for all system secrets. It prioritizes the Va
val
;; Fallback to environment
(let ((env-var (case provider
(:gemini "GEMINI_API_KEY")
((:gemini :gemini-api) "GEMINI_API_KEY")
(:openai "OPENAI_API_KEY")
(:anthropic "ANTHROPIC_API_KEY")
(:groq "GROQ_API_KEY")
(:openrouter "OPENROUTER_API_KEY")
(:telegram "TELEGRAM_BOT_TOKEN")
(t nil))))
(when (and env-var (eq type :api-key))
(uiop:getenv env-var))))))

View File

@@ -0,0 +1,138 @@
:PROPERTIES:
:ID: gateway-telegram-skill
:CREATED: [2026-04-11 Sat 15:50]
:END:
#+TITLE: SKILL: Telegram Gateway (Universal Literate Note)
#+STARTUP: content
#+FILETAGS: :gateway:telegram:io:psf:
#+DEPENDS_ON: id:credentials-vault-skill
* Overview
The *Telegram Gateway* provides bi-directional communication between the Sovereign and the Org-Agent via the Telegram Bot API. It features a non-blocking polling sensor and a high-integrity actuator for outbound messaging.
* Phase A: Demand (PRD)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Purpose
Enable mobile/remote access to the Org-Agent via a secure Telegram bot.
** 2. Success Criteria
- [ ] *Inbound:* Messages from authorized Telegram IDs are injected into the Kernel Bus.
- [ ] *Outbound:* The `:telegram` target correctly routes messages to the Bot API.
- [ ] *Persistence:* The polling offset is maintained to prevent duplicate processing.
* Phase B: Blueprint (PROTOCOL)
:PROPERTIES:
:STATUS: SIGNED
:END:
** 1. Architectural Intent
The gateway operates as an autonomous background service. It uses `dexador` for HTTP polling and `cl-json` for payload processing. Authentication is enforced via a whitelist of authorized `chat_id`s.
** 2. Semantic Interfaces
- `(:sensor :chat-message :channel :telegram ...)`
- `(:type :REQUEST :target :telegram :chat-id "..." :text "...")`
* Phase D: Build (Implementation)
** Package Context
#+begin_src lisp :tangle ../src/gateway-telegram.lisp
(in-package :org-agent)
#+end_src
** State & Config
#+begin_src lisp :tangle ../src/gateway-telegram.lisp
(defvar *telegram-last-update-id* 0)
(defvar *telegram-polling-thread* nil)
(defvar *telegram-authorized-chats* nil
"List of chat IDs allowed to interact with the bot. Hydrated from environment.")
(defun get-telegram-token () (vault-get-secret :telegram))
#+end_src
** Actuator: sendMessage
#+begin_src lisp :tangle ../src/gateway-telegram.lisp
(defun execute-telegram-action (action context)
"Sends a message back to Telegram."
(declare (ignore context))
(let* ((payload (getf action :payload))
(chat-id (or (getf payload :chat-id) (getf action :chat-id)))
(text (or (getf payload :text) (getf action :text)))
(token (get-telegram-token))
(url (format nil "https://api.telegram.org/bot~a/sendMessage" token)))
(when (and token chat-id text)
(kernel-log "TELEGRAM: Sending message to ~a..." chat-id)
(handler-case
(dex:post url
:headers '(("Content-Type" . "application/json"))
:content (cl-json:encode-json-to-string
`((chat_id . ,chat-id) (text . ,text))))
(error (c) (kernel-log "TELEGRAM ERROR: ~a" c))))))
#+end_src
** Sensor: getUpdates & Injection
#+begin_src lisp :tangle ../src/gateway-telegram.lisp
(defun telegram-process-updates ()
"Polls for new messages and injects them into the kernel."
(let* ((token (get-telegram-token))
(url (format nil "https://api.telegram.org/bot~a/getUpdates?offset=~a"
token (1+ *telegram-last-update-id*))))
(when token
(handler-case
(let* ((response (dex:get url))
(json (cl-json:decode-json-from-string response))
(updates (cdr (assoc :result json))))
(dolist (update updates)
(let* ((update-id (cdr (assoc :update--id update)))
(message (cdr (assoc :message update)))
(chat (cdr (assoc :chat message)))
(chat-id (cdr (assoc :id chat)))
(text (cdr (assoc :text message))))
(setf *telegram-last-update-id* update-id)
(when (and text chat-id)
(kernel-log "TELEGRAM: Received message from ~a" chat-id)
(inject-stimulus
(list :type :EVENT
:payload (list :sensor :chat-message
:channel :telegram
:chat-id (format nil "~a" chat-id)
:text text)))))))
(error (c) (kernel-log "TELEGRAM POLL ERROR: ~a" c))))))
#+end_src
** Background Polling Loop
#+begin_src lisp :tangle ../src/gateway-telegram.lisp
(defun start-telegram-gateway ()
"Initializes the Telegram background thread."
(unless (and *telegram-polling-thread* (bt:thread-alive-p *telegram-polling-thread*))
(setf *telegram-polling-thread*
(bt:make-thread
(lambda ()
(loop
(telegram-process-updates)
(sleep 3)))
:name "org-agent-telegram-gateway"))
(kernel-log "TELEGRAM: Gateway polling active.")))
(defun stop-telegram-gateway ()
(when (and *telegram-polling-thread* (bt:thread-alive-p *telegram-polling-thread*))
(bt:destroy-thread *telegram-polling-thread*)
(setf *telegram-polling-thread* nil)))
#+end_src
** Skill Definition & Registration
#+begin_src lisp :tangle ../src/gateway-telegram.lisp
(progn
(register-actuator :telegram #'execute-telegram-action)
(defskill :skill-gateway-telegram
:priority 150
:trigger (lambda (ctx) (declare (ignore ctx)) nil) ;; Passive, handles its own loop
:neuro nil
:symbolic (lambda (action ctx) (declare (ignore ctx)) action))
;; Initialize the background polling loop
(start-telegram-gateway))
#+end_src