diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index fe5748283..205aad3fb 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -52,6 +52,7 @@ {"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:22Z","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.16.32","title":"Telegram: stream LLM replies via sendMessageDraft","description":"Chat replies currently block for the whole LLM turn, then arrive as one message. The typing indicator masks the wait but shows no progress. go-telegram/bot exposes SendMessageDraft (see examples/streaming_draft) and ai-sdk's runtime.ChatStream already returns core.StreamResult with a TextStream \u003c-chan string, so both halves exist -- only the gateway seam is missing, since gateway.LLMResponder is func(ctx, Message) (string, error) and cannot emit partial output.","acceptance_criteria":"Gateway exposes an optional streaming responder; Router falls back to the blocking path when unset. Telegram adapter streams deltas into a draft, then finalises with a formatted SendMessage. Draft updates are throttled to respect Telegram rate limits. Streaming failure falls back to a normal send rather than losing the reply.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T18:52:20Z","created_by":"Sam Catlow","updated_at":"2026-07-26T18:52:30Z","started_at":"2026-07-26T18:52:30Z","dependencies":[{"issue_id":"archie-core-abg.16.32","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T04:52:20Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-50z","title":"Enforce typed plugin engine architecture rule","description":"Cement the repository invariant that a plugin engine is a typed capability family with an owning registry/manager and lifecycle semantics, never a generic daemon hook. Add one canonical architecture rule referenced by both AGENTS.md and CLAUDE.md, record it in Beads memory, and add an executable architecture test that prevents drift without touching the concurrently edited secret/config packages.","acceptance_criteria":"A canonical rule defines typed domain contract, owning registry/manager, lifecycle and health expectations, narrow host access, and trust boundaries; AGENTS.md and CLAUDE.md both surface the rule through their shared source; an architecture test fails for generic plugin-hook expansion or an engine interface without a family manager; focused tests and task check pass; fresh adversarial review has no surviving findings.","notes":"Complete. Red proof: architecture test failed on missing canonical rule. Green: internal/plugin tests pass; golangci-lint ./internal/plugin reports zero issues; gofumpt diff is empty. Fresh adversarial review initially found bypassable owner checks and ambiguous trust wording; remediated with signature-linked single-owner validation, negative fixtures (metadata-only, embedded-only, unrelated/split owners, pointer and collection wrappers), and precise trusted-in-process/out-of-process/container language. Final fresh review: zero surviving findings. Full task check was attempted but is currently blocked by concurrent unrelated migrations: gateway fakeTaskCreator still implements CreateTask(context.Context,string) while interface now wants SpawnRequest, and daemon EnqueueIssue callers omit the new eighth argument. No secret/config source was edited by this issue.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T05:00:36Z","created_by":"Sam Catlow","updated_at":"2026-07-26T05:14:06Z","started_at":"2026-07-26T05:00:43Z","closed_at":"2026-07-26T05:14:06Z","close_reason":"Strict plugin-engine invariant documented in canonical architecture and shared AGENTS/CLAUDE instructions, persisted in Beads memory, mechanically enforced with adversarial negative controls, and independently reviewed with zero findings.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.39","title":"MVP: migrate Hermes profiles, memory, skills, and session state","description":"The copied live Hermes instance contains root plus agile-lead, dev, and local-agent profiles with distinct models, gateways, memories, SOUL prompts, skills, sessions, and cron state. archie-core currently has forge identities but no profile-scoped gateway/tool/memory/workspace composition and no importer. Define the mapping into archie-core identities/profiles and build a one-time idempotent migration plus cutover rehearsal.","acceptance_criteria":"Document and implement the mapping for all copied profiles -- MAPPING DOCUMENTED (docs/prds/hermes-migration-dry-run.md), NOT YET IMPLEMENTED (blocked on abg.36). Import SOUL/USER/MEMORY/skills/session/cron without secrets -- NOT STARTED (design-blocked on abg.36, see report). Produce a dry-run report -- DONE. Rehearse dual-run/shadow validation and rollback-safe cutover checklist -- NOT STARTED.","notes":"Dry-run inventory + mapping report delivered: docs/prds/hermes-migration-dry-run.md. Surveyed .hermes-carina/ (live copy of the Hermes deployment) structurally only -- directory listings and non-secret YAML top-level keys, zero secret file contents read (.env/auth.json/mcp-tokens/ explicitly excluded and never opened). Found and catalogued 4 environments (main/agile-lead/dev/local-agent), their skill counts (34/20/25/17), main's 419 session keys (sessions/sessions.json), cron jobs.json presence. Proposed a mapping table: environment-\u003eIdentityConfig, SOUL.md-\u003enew persona system-prompt field (no existing archie-core field for this), memories/-\u003einternal/memory.Manager (needs format translator), skills/-\u003einternal/skill.Catalog (closest 1:1, needs tool-compat pass), sessions-\u003egateway.SessionStore (needs translator), cron/jobs.json-\u003eblocked, no archie-core cron subsystem exists yet (abg.24 territory). Documented explicit exclusion list for the eventual importer (secrets never copied). Documented why actual import tooling is blocked until abg.36 lands (no point importing SOUL/memory/skills into a runtime that doesn't consume them per-turn yet) -- this report is prep, not the importer itself.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:37:09Z","created_by":"Sam Catlow","updated_at":"2026-07-26T05:16:40Z","started_at":"2026-07-26T05:14:49Z","dependencies":[{"issue_id":"archie-core-abg.39","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:37:08Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.35","title":"Audit Hermes-to-archie-core MVP takeover gaps","description":"Compare the copied live Hermes state in .hermes-carina with archie-core's current runtime and backlog. Determine the minimum remaining work for archie-core to replace Hermes on carina, explicitly excluding the in-flight secret engine and provider/config work.","acceptance_criteria":"Document current capability parity, concrete blockers, minimum migration sequence, and non-MVP deferrals with file and issue evidence; do not modify implementation code.","notes":"Verdict: not cutover-ready. The copied live surface is root plus three profiles; connected Telegram/email/webhook gateways; 419 persisted session records across root state; one scheduled Gitea Monitor with Telegram delivery; enabled Linear/Gitea MCP; and actual use of terminal/file/patch/web/memory/session/delegation/process tools. Critical gaps: gateway chat is a one-step runtime.Chat call with no tools; email/webhook have nil responders; tool registry/MCP/memory are not wired end-to-end; rich gateway abstractions are parallel dead code; Telegram is instantiated with an empty allowlist; chat /spawn fabricates a forge issue and /approve,/cancel are absent; multi-identity is not composed or ownership-safe; no profile/state importer; cron/delivery/auth/webhook parity remain open. Filed abg.36 full gateway agent loop, abg.37 identity routing, abg.38 native chat tasks, abg.39 migration/cutover. Existing MVP dependencies: abg.17 stdio MCP completion, abg.22 authorization subset, abg.23 delivery, abg.24 scheduler, abg.27 webhook HMAC/filter/template/dedup subset. Focused gateway/channel/memory/tools/daemon/cmd tests passed when rerun with local socket access.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:28:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:37:51Z","started_at":"2026-07-26T04:28:19Z","closed_at":"2026-07-26T04:37:51Z","close_reason":"Completed read-only Hermes takeover audit; findings and MVP remediation issues recorded.","dependencies":[{"issue_id":"archie-core-abg.35","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:28:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 3bc745adf..e3bd33288 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -284,12 +284,17 @@ func run() int { // other messages are routed through the LLM with conversation // history from the session store. var llmResponder gateway.LLMResponder + var llmStream gateway.LLMStreamResponder if llm != nil { chatModel := cfg.Models["chat"] if chatModel == "" { chatModel = cfg.Models["builder"] } - llmResponder = func(ctx context.Context, msg gateway.Message) (string, error) { + // respond runs one chat turn. When onDelta is non-nil the reply + // is streamed and each fragment reported as it arrives; the + // assembled text is returned either way, so both the blocking + // and streaming responders share this single path. + respond := func(ctx context.Context, msg gateway.Message, onDelta func(string)) (string, error) { sessionKey := sessionKey(msg) _ = sessionStore.SaveMessage(ctx, sessionKey, msg) @@ -345,26 +350,51 @@ func run() int { if err != nil { return "", fmt.Errorf("build chat tools: %w", err) } - result, err := llm.Chat( - ctx, - chatModel, - options, - ) - if err != nil { - return "", fmt.Errorf("llm chat: %w", err) + var text string + if onDelta == nil { + result, err := llm.Chat(ctx, chatModel, options) + if err != nil { + return "", fmt.Errorf("llm chat: %w", err) + } + text = result.Text + } else { + stream, err := llm.ChatStream(ctx, chatModel, options) + if err != nil { + return "", fmt.Errorf("llm chat stream: %w", err) + } + var sb strings.Builder + for delta := range stream.TextStream { + sb.WriteString(delta) + onDelta(delta) + } + // FinishReason resolves only once the stream is drained, + // so a mid-stream provider failure surfaces here rather + // than being mistaken for a short but complete reply. + if _, err := stream.FinishReason(); err != nil { + return "", fmt.Errorf("llm chat stream: %w", err) + } + text = sb.String() } // Persist the response. _ = sessionStore.SaveMessage(ctx, sessionKey, gateway.Message{ From: cfg.BotUser, - Text: result.Text, + Text: text, }) - return result.Text, nil + return text, nil + } + + llmResponder = func(ctx context.Context, msg gateway.Message) (string, error) { + return respond(ctx, msg, nil) + } + llmStream = func(ctx context.Context, msg gateway.Message, onDelta func(string)) (string, error) { + return respond(ctx, msg, onDelta) } } router := gateway.NewRouter(st, llmResponder, "telegram") + router.LLMStream = llmStream configureTaskCommands(router, chatTasks, chatController, defaultChatIdentity) startGateways = append(startGateways, func() { go func() { diff --git a/go.mod b/go.mod index 6170b8113..f0731b66e 100644 --- a/go.mod +++ b/go.mod @@ -56,7 +56,7 @@ require ( require ( code.gitea.io/sdk/gitea v0.25.1 - github.com/go-telegram/bot v1.18.0 + github.com/go-telegram/bot v1.22.0 github.com/moby/moby/api v1.55.0 github.com/moby/moby/client v0.5.0 github.com/nats-io/nats-server/v2 v2.14.3 diff --git a/go.sum b/go.sum index af798104c..ab14060a6 100644 --- a/go.sum +++ b/go.sum @@ -39,6 +39,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-telegram/bot v1.18.0 h1:yQzv437DY42SYTPBY48RinAvwbmf1ox5QICskIYWCD8= github.com/go-telegram/bot v1.18.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM= +github.com/go-telegram/bot v1.22.0 h1:zK29OoTYMmR5emJrCtGa2SjaGleeZiUB/C1i7kc2lXE= +github.com/go-telegram/bot v1.22.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= diff --git a/internal/channels/telegram/draft.go b/internal/channels/telegram/draft.go new file mode 100644 index 000000000..4f8bf3625 --- /dev/null +++ b/internal/channels/telegram/draft.go @@ -0,0 +1,82 @@ +package telegram + +import ( + "context" + "strings" + "sync" + "time" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" +) + +// draftInterval is the minimum gap between draft updates. Telegram rate +// limits per-chat writes, and an LLM emits tokens far faster than any +// human reads, so deltas are coalesced into one update per tick rather +// than sent individually. +const draftInterval = 700 * time.Millisecond + +// draft streams a reply into a Telegram message draft (sendMessageDraft) +// so the user watches the answer being written instead of waiting on a +// silent "typing…" indicator. +// +// A draft is deliberately best-effort and self-contained: it never blocks +// the generating goroutine and never surfaces an error. The authoritative +// reply is always the final SendMessage the caller makes once the turn +// completes -- if every draft update failed, the user simply sees the +// finished message appear the way it did before streaming existed. +type draft struct { + g *Gateway + b *bot.Bot + chatID int64 + messageThreadID int + draftID int + + mu sync.Mutex + text strings.Builder + last time.Time +} + +// newDraft creates a draft bound to one chat/thread. The draft ID only has +// to be unique per streaming session. +func (g *Gateway) newDraft(b *bot.Bot, chatID int64, messageThreadID int) *draft { + return &draft{ + g: g, + b: b, + chatID: chatID, + messageThreadID: messageThreadID, + draftID: int(time.Now().UnixNano() & 0x7fffffff), + } +} + +// onDelta accumulates a fragment and pushes a throttled draft update. +// It satisfies the onDelta callback of gateway.Router.RouteStream. +func (d *draft) onDelta(delta string) { + if delta == "" { + return + } + + d.mu.Lock() + d.text.WriteString(delta) + if time.Since(d.last) < draftInterval { + d.mu.Unlock() + return + } + d.last = time.Now() + // A block cursor marks the reply as still being written. + body := d.text.String() + " ▌" + d.mu.Unlock() + + // Stream as a rich message so partial Markdown renders the same way + // the final reply will. Mid-stream text is frequently unbalanced (an + // unclosed ** or code fence); a failed draft update is logged and + // skipped, and the next tick -- or the final message -- corrects it. + if _, err := d.b.SendRichMessageDraft(context.Background(), &bot.SendRichMessageDraftParams{ + ChatID: d.chatID, + MessageThreadID: d.messageThreadID, + DraftID: d.draftID, + RichMessage: models.InputRichMessage{Markdown: body}, + }); err != nil { + d.g.log.Debug("send rich message draft failed", "error", err) + } +} diff --git a/internal/channels/telegram/format.go b/internal/channels/telegram/format.go deleted file mode 100644 index 7ae65f35c..000000000 --- a/internal/channels/telegram/format.go +++ /dev/null @@ -1,165 +0,0 @@ -package telegram - -import ( - "regexp" - "strings" -) - -// Telegram's Bot API accepts a small HTML subset for message formatting: -//
 
. It has no -// notion of headings, bullets, or tables. LLM replies, however, are plain -// Markdown -- so without conversion the raw syntax (**bold**, backticks, -// pipe tables) is shown to the user verbatim. -// -// markdownToHTML converts the Markdown subset an LLM realistically emits -// into that HTML subset. It is deliberately conservative: anything it -// cannot map is escaped and passed through as literal text rather than -// guessed at, and sendMessage falls back to an unformatted send if -// Telegram still rejects the result. - -var ( - // fencedBlockRe matches ```lang\n...\n``` code fences. - fencedBlockRe = regexp.MustCompile("(?s)```([A-Za-z0-9_+-]*)\\n?(.*?)```") - // inlineCodeRe matches `code` spans. - inlineCodeRe = regexp.MustCompile("`([^`\n]+)`") - // linkRe matches [text](url). - linkRe = regexp.MustCompile(`\[([^\]]+)\]\(([^)\s]+)\)`) - // boldRe matches **text** and __text__. - boldRe = regexp.MustCompile(`\*\*([^*\n]+)\*\*|__([^_\n]+)__`) - // italicRe matches *text* and _text_ (after bold has been consumed). - italicRe = regexp.MustCompile(`\*([^*\n]+)\*|(?:^|[\s(])_([^_\n]+)_`) - // strikeRe matches ~~text~~. - strikeRe = regexp.MustCompile(`~~([^~\n]+)~~`) - // headingRe matches leading #, ##, ... headings. - headingRe = regexp.MustCompile(`^\s{0,3}#{1,6}\s+(.*)$`) - // bulletRe matches -, * and + list markers. - bulletRe = regexp.MustCompile(`^(\s*)[-*+]\s+(.*)$`) - // tableSepRe matches a Markdown table separator row (|---|:--:|). - tableSepRe = regexp.MustCompile(`^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$`) - // hrRe matches a horizontal rule. RE2 has no backreferences, so each - // marker character gets its own alternative rather than \1. - hrRe = regexp.MustCompile(`^\s*(?:-\s*-\s*-[-\s]*|\*\s*\*\s*\*[*\s]*|_\s*_\s*_[_\s]*)$`) -) - -// markdownToHTML converts LLM Markdown to the Telegram HTML subset. -func markdownToHTML(md string) string { - // Code content must not be touched by any inline rule, so pull fenced - // and inline code out first and re-insert after everything else. - var code []string - stash := func(s string) string { - code = append(code, s) - // \x00 cannot appear in a Telegram message, so it is a safe - // placeholder sentinel. - return "\x00" + itoa(len(code)-1) + "\x00" - } - - md = fencedBlockRe.ReplaceAllStringFunc(md, func(m string) string { - sub := fencedBlockRe.FindStringSubmatch(m) - lang, body := sub[1], strings.TrimRight(sub[2], "\n") - open := "
"
-		if lang != "" {
-			open = `
`
-		}
-		close := "
" - if lang != "" { - close = "
" - } - return stash(open + escapeHTML(body) + close) - }) - md = inlineCodeRe.ReplaceAllStringFunc(md, func(m string) string { - body := inlineCodeRe.FindStringSubmatch(m)[1] - return stash("" + escapeHTML(body) + "") - }) - - lines := strings.Split(md, "\n") - out := make([]string, 0, len(lines)) - for i := 0; i < len(lines); i++ { - line := lines[i] - - // A table needs monospace to stay aligned, and Telegram has no - // table element -- emit the whole block inside
.
-		if isTableRow(line) && i+1 < len(lines) && tableSepRe.MatchString(lines[i+1]) {
-			var block []string
-			for i < len(lines) && (isTableRow(lines[i]) || tableSepRe.MatchString(lines[i])) {
-				block = append(block, strings.TrimSpace(lines[i]))
-				i++
-			}
-			i--
-			out = append(out, "
"+escapeHTML(strings.Join(block, "\n"))+"
") - continue - } - - if hrRe.MatchString(line) { - out = append(out, "──────────") - continue - } - if m := headingRe.FindStringSubmatch(line); m != nil { - out = append(out, ""+inline(m[1])+"") - continue - } - if m := bulletRe.FindStringSubmatch(line); m != nil { - out = append(out, m[1]+"• "+inline(m[2])) - continue - } - out = append(out, inline(line)) - } - - res := strings.Join(out, "\n") - - // Re-insert code, innermost placeholder first. - for i, c := range code { - res = strings.ReplaceAll(res, "\x00"+itoa(i)+"\x00", c) - } - return res -} - -// inline applies the span-level rules to one line of already code-stripped -// text, escaping it first so user text can never inject markup. -func inline(s string) string { - s = escapeHTML(s) - s = linkRe.ReplaceAllString(s, `
$1`) - s = boldRe.ReplaceAllString(s, "$1$2") - s = strikeRe.ReplaceAllString(s, "$1") - s = italicRe.ReplaceAllStringFunc(s, func(m string) string { - sub := italicRe.FindStringSubmatch(m) - body := sub[1] + sub[2] - // Preserve the leading boundary char consumed by the _ branch. - prefix := "" - if sub[1] == "" && len(m) > 0 && m[0] != '_' { - prefix = string(m[0]) - } - return prefix + "" + body + "" - }) - return s -} - -// isTableRow reports whether a line looks like a Markdown table row. -func isTableRow(s string) bool { - t := strings.TrimSpace(s) - return strings.Count(t, "|") >= 2 -} - -// escapeHTML escapes the three characters Telegram's HTML parser treats as -// markup. Order matters: & must be escaped first. -func escapeHTML(s string) string { - s = strings.ReplaceAll(s, "&", "&") - s = strings.ReplaceAll(s, "<", "<") - s = strings.ReplaceAll(s, ">", ">") - return s -} - -// itoa is a tiny strconv.Itoa to keep the placeholder path allocation-free -// of the strconv import for such a narrow use. -func itoa(i int) string { - if i == 0 { - return "0" - } - var b [20]byte - p := len(b) - for i > 0 { - p-- - b[p] = byte('0' + i%10) - i /= 10 - } - return string(b[p:]) -} diff --git a/internal/channels/telegram/format_test.go b/internal/channels/telegram/format_test.go deleted file mode 100644 index 46ecaafd3..000000000 --- a/internal/channels/telegram/format_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package telegram - -import "strings" - -import "testing" - -func TestMarkdownToHTML(t *testing.T) { - tests := []struct { - name string - in string - want string - }{ - {name: "plain text untouched", in: "hello there", want: "hello there"}, - {name: "bold", in: "here's what I **can** do", want: "here's what I can do"}, - {name: "underscore bold", in: "__strong__", want: "strong"}, - {name: "italic", in: "*emphasis*", want: "emphasis"}, - {name: "strikethrough", in: "~~gone~~", want: "gone"}, - {name: "inline code", in: "the `/commands` system", want: "the /commands system"}, - {name: "link", in: "[docs](https://x.test)", want: `docs`}, - {name: "heading becomes bold", in: "## Capabilities", want: "Capabilities"}, - {name: "bullet becomes dot", in: "- Answer questions", want: "• Answer questions"}, - { - name: "html in user text is escaped, not injected", - in: "use & co", - want: "use <script>alert(1)</script> & co", - }, - { - name: "markdown inside code is left alone", - in: "`**not bold**`", - want: "**not bold**", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := markdownToHTML(tt.in); got != tt.want { - t.Errorf("markdownToHTML(%q)\n got: %q\nwant: %q", tt.in, got, tt.want) - } - }) - } -} - -func TestMarkdownToHTMLFencedCode(t *testing.T) { - got := markdownToHTML("run:\n```go\nfmt.Println(1 < 2)\n```") - want := "run:\n" + `
fmt.Println(1 < 2)
` - if got != want { - t.Errorf("fenced code\n got: %q\nwant: %q", got, want) - } -} - -// Telegram has no table element, so a Markdown table must become a
-// block or it arrives as unreadable pipe soup. Regression for the real
-// LLM reply that prompted this.
-func TestMarkdownToHTMLTableBecomesPre(t *testing.T) {
-	in := "| Capability | Description |\n|---|---|\n| **Code** | Write, review |"
-	got := markdownToHTML(in)
-	if !strings.HasPrefix(got, "
") || !strings.HasSuffix(got, "
") { - t.Fatalf("table not wrapped in
: %q", got)
-	}
-	if strings.Contains(got, "") {
-		t.Errorf("table interior must stay literal, got %q", got)
-	}
-}
-
-// Every emitted tag must be one Telegram actually accepts.
-func TestMarkdownToHTMLEmitsOnlySupportedTags(t *testing.T) {
-	in := "# H\n\nsome **b** and *i* and `c`\n\n- item\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n```sh\nls\n```"
-	got := markdownToHTML(in)
-	for _, bad := range []string{"

", "

    ", "
  • ", "

    ", "", "", "
    "} { - if strings.Contains(got, bad) { - t.Errorf("emitted unsupported tag %s: %q", bad, got) - } - } -} diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 18226e673..e40c59d8c 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -194,20 +194,21 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { return } - // Routing a non-command message runs an LLM turn, which can take - // many seconds. Show a typing indicator for the whole wait so the - // chat doesn't look dead. + // An LLM turn takes many seconds. Stream it into a draft so the + // reply appears as it is written; the typing indicator covers the + // gap before the first token and any non-streaming path. stopTyping := g.startTyping(ctx, b, msg.Chat.ID, msg.MessageThreadID) + draft := g.newDraft(b, msg.Chat.ID, msg.MessageThreadID) // If it starts with / but wasn't matched by a registered // handler, it's unknown -- let the router handle it (which // will say "unrecognized"). - reply, err := router.Route(ctx, gateway.Message{ + reply, err := router.RouteStream(ctx, gateway.Message{ ChannelID: fmt.Sprintf("%d", msg.Chat.ID), ThreadID: threadIDString(msg.MessageThreadID), From: msg.From.Username, Text: msg.Text, - }) + }, draft.onDelta) stopTyping() if err != nil { g.log.Error("route failed", "error", err) @@ -308,27 +309,29 @@ func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, mes } } -// send delivers one message, rendering Markdown as Telegram HTML. +// send delivers one message as a rich message, letting Telegram render the +// Markdown an LLM already emits. // -// Splitting a long reply can cut an HTML tag in half, and a hand-written -// converter can always meet Markdown it maps wrongly; in both cases -// Telegram rejects the whole message with a parse error. Rather than lose -// the reply, fall back to sending the original unformatted text -- the user -// sees raw Markdown, which is what happened before formatting existed, but -// never silence. +// sendRichMessage takes Markdown natively and supports constructs the +// legacy parse modes cannot express at all -- notably tables, which LLM +// replies use freely. That removes the need to translate Markdown into the +// narrow HTML subset the older API accepted. +// +// Rich messages are a recent Bot API addition, so a rejection here is +// treated as "unsupported" rather than fatal: fall back to a plain send so +// the user still receives the reply, unformatted, instead of silence. func (g *Gateway) send(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text, errMsg string) { - params := &bot.SendMessageParams{ - ChatID: chatID, - Text: markdownToHTML(text), - ParseMode: models.ParseModeHTML, + rich := &bot.SendRichMessageParams{ + ChatID: chatID, + RichMessage: models.InputRichMessage{Markdown: text}, } if messageThreadID != 0 { - params.MessageThreadID = messageThreadID + rich.MessageThreadID = messageThreadID } - if _, err := b.SendMessage(ctx, params); err == nil { + if _, err := b.SendRichMessage(ctx, rich); err == nil { return } else { - g.log.Warn("formatted send failed, retrying unformatted", "error", err) + g.log.Warn("rich send failed, retrying unformatted", "error", err) } plain := &bot.SendMessageParams{ChatID: chatID, Text: text} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 8c3ea2d3e..a37b36286 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -53,6 +53,17 @@ type StatusReader interface { // router did not handle directly. type LLMResponder func(ctx context.Context, msg Message) (string, error) +// LLMStreamResponder is the streaming counterpart of LLMResponder. It +// reports the reply as it is generated by calling onDelta with each new +// text fragment, and returns the complete reply when the turn finishes. +// +// It is optional: a gateway that cannot render partial output, or a +// deployment whose provider does not stream, simply leaves it nil and the +// Router falls back to the blocking LLMResponder. onDelta may be called +// from the generating goroutine and must not block for long -- adapters +// should throttle their own network writes rather than stall the stream. +type LLMStreamResponder func(ctx context.Context, msg Message, onDelta func(string)) (string, error) + // ModelManager provides access to available models and allows switching the // active LLM model. The daemon supplies an implementation backed by its // runtime provider catalog. When nil on a Router, /model and /models @@ -114,6 +125,10 @@ type Router struct { Tasks TaskCreator // nil = /spawn not configured Controller TaskController // nil = /approve and /cancel not configured LLM LLMResponder // nil = LLM not wired yet + // LLMStream is the optional streaming responder. When set, adapters + // that can render partial output (see RouteStream) show the reply as + // it generates; when nil, everything falls back to LLM. + LLMStream LLMStreamResponder // Identity is the archie identity this router belongs to (empty in // single-identity deployments). Propagated into SpawnRequest and // used to scope /approve and /cancel authorization -- a task @@ -159,6 +174,40 @@ func (r *Router) Route(ctx context.Context, msg Message) (string, error) { } } +// RouteStream is Route for adapters that can render a reply progressively. +// onDelta receives each new fragment of an LLM reply as it is generated; +// the complete reply is returned as usual. +// +// Only free-text messages stream. Gateway-local commands (/status, /model, +// …) answer from local state in a single step, so they return through the +// normal path with no delta callbacks. When no streaming responder is +// configured, RouteStream is exactly Route -- callers get the whole reply +// at the end and simply never see a delta, so an adapter can always call +// RouteStream without checking first. +func (r *Router) RouteStream(ctx context.Context, msg Message, onDelta func(string)) (string, error) { + if r.LLMStream == nil || onDelta == nil { + return r.Route(ctx, msg) + } + cmd, _ := parseCmd(strings.TrimSpace(msg.Text), r.gatewayName) + if isLocalCommand(cmd) { + return r.Route(ctx, msg) + } + // Unrecognised "/foo" is not a local command: Route sends it to the + // LLM, so it streams like any other free text. + return r.LLMStream(ctx, msg, onDelta) +} + +// isLocalCommand reports whether cmd is answered from local state by +// Route rather than handed to the LLM. Keep in sync with Route's switch. +func isLocalCommand(cmd string) bool { + switch cmd { + case "/status", "/models", "/model", "/spawn", "/approve", "/cancel": + return true + default: + return false + } +} + // parseCmd extracts the command name from text, stripping an optional // @gateway mention from the command token, and returns the command and // its first argument. diff --git a/internal/gateway/gateway_stream_test.go b/internal/gateway/gateway_stream_test.go new file mode 100644 index 000000000..83398590d --- /dev/null +++ b/internal/gateway/gateway_stream_test.go @@ -0,0 +1,86 @@ +package gateway + +import ( + "context" + "strings" + "testing" +) + +// RouteStream must degrade to Route when no streaming responder is set, so +// adapters can always call it without first checking for support. +func TestRouteStreamFallsBackWhenNoStreamResponder(t *testing.T) { + r := NewRouter(nil, func(context.Context, Message) (string, error) { + return "blocking reply", nil + }, "telegram") + + var deltas []string + got, err := r.RouteStream(context.Background(), Message{Text: "hello"}, func(d string) { + deltas = append(deltas, d) + }) + if err != nil { + t.Fatalf("RouteStream: %v", err) + } + if got != "blocking reply" { + t.Errorf("reply = %q, want %q", got, "blocking reply") + } + if len(deltas) != 0 { + t.Errorf("expected no deltas without a stream responder, got %v", deltas) + } +} + +func TestRouteStreamStreamsFreeText(t *testing.T) { + r := NewRouter(nil, nil, "telegram") + r.LLMStream = func(_ context.Context, _ Message, onDelta func(string)) (string, error) { + for _, d := range []string{"a", "b", "c"} { + onDelta(d) + } + return "abc", nil + } + + var sb strings.Builder + got, err := r.RouteStream(context.Background(), Message{Text: "hello"}, func(d string) { + sb.WriteString(d) + }) + if err != nil { + t.Fatalf("RouteStream: %v", err) + } + if got != "abc" || sb.String() != "abc" { + t.Errorf("reply=%q deltas=%q, want both %q", got, sb.String(), "abc") + } +} + +// Local commands answer from local state in one step, so they must not be +// sent to the streaming responder. +func TestRouteStreamDoesNotStreamLocalCommands(t *testing.T) { + r := NewRouter(nil, nil, "telegram") + streamed := false + r.LLMStream = func(context.Context, Message, func(string)) (string, error) { + streamed = true + return "", nil + } + + if _, err := r.RouteStream(context.Background(), Message{Text: "/status"}, func(string) {}); err != nil { + t.Fatalf("RouteStream: %v", err) + } + if streamed { + t.Error("/status must not be routed to the streaming responder") + } +} + +// An unrecognised slash command is handed to the LLM by Route, so it should +// stream like any other free text. +func TestRouteStreamStreamsUnknownCommand(t *testing.T) { + r := NewRouter(nil, nil, "telegram") + streamed := false + r.LLMStream = func(context.Context, Message, func(string)) (string, error) { + streamed = true + return "ok", nil + } + + if _, err := r.RouteStream(context.Background(), Message{Text: "/commands"}, func(string) {}); err != nil { + t.Fatalf("RouteStream: %v", err) + } + if !streamed { + t.Error("unknown /commands should stream, since Route sends it to the LLM") + } +}