From 1d76560911aa7404c0d55bc65a4aed7301177b84 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 26 Jul 2026 10:29:07 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20wire=20Telegram=20LLM=20routing=20?= =?UTF-8?q?=E2=80=94=20non-command=20messages=20routed=20to=20AI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LLMResponder adapter wraps llm.Chat() with model from cfg.Models[chat] (falls back to builder). Gateway-local commands (/status, /models, /model, /spawn) still handled directly. LLM created before gateway so it's available at router construction time. All 38 packages pass. --- .beads/interactions.jsonl | 1 + .beads/issues.jsonl | 2 +- cmd/archied/main.go | 41 +++++++++++++++++++++++++++++++-------- 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 2cbe68513..ecefa2b10 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -108,3 +108,4 @@ {"id":"int-f3b5dcc6f5a28925a1f5f32231ff7e7e","kind":"field_change","created_at":"2026-07-25T23:59:24.04561454Z","actor":"Sam Catlow","issue_id":"archie-core-gnr","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race."}} {"id":"int-5bb47bb5ed98eb8c90dcc0178207178f","kind":"field_change","created_at":"2026-07-25T23:59:24.201226228Z","actor":"Sam Catlow","issue_id":"archie-core-yss","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race."}} {"id":"int-06fcaeb6234a81af9b01a6fcbcd70e35","kind":"field_change","created_at":"2026-07-26T00:24:04.190065035Z","actor":"Sam Catlow","issue_id":"archie-core-abg.5.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Delivered: ThreadID field added to gateway.Message and SessionSource. SessionStore persists thread_id. Telegram gateway extracts message_thread_id from updates, passes it through gateway.Message, and sends replies to the correct thread. threadIDString helper maps 0→'' for flat-chat backward compatibility. Tests: thread-aware session source, store persistence, ToLegacy preservation, threadIDString edge cases."}} +{"id":"int-5cab918e773822151be2b3757e790c5a","kind":"field_change","created_at":"2026-07-26T00:26:43.755244658Z","actor":"Sam Catlow","issue_id":"archie-core-abg.32","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Memory, guardrails, and tool registry wired into daemon. MemoryManager created with built-in file-backed provider, SystemPromptBlock() injected into agent ExtraRules. GuardrailEngine records RecordSuccess/RecordFailure after every agent stage. ToolRegistry created, MCP servers started from config. All nil-safe (backward compat). 38/38 packages pass with -race."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 498e82ff0..99748a2b9 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,7 +1,7 @@ {"_type":"issue","id":"archie-core-abg.33","title":"Context compression for long-running sessions","description":"Hermes config has compression enabled at 0.5 threshold, protecting first 3 and last 20 messages. Sam confirmed this is a must-have for long-running sessions. Without compression, context windows fill up and sessions degrade.\n\nScope:\n- Compression threshold (fraction of context window used)\n- Target compression ratio\n- Protect first N / last N messages from compression\n- Integrate with MemoryManager (pre-compress hook already defined: OnPreCompressProvider)\n- Use the existing StreamingContextScrubber for fence-stripping during compression","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:15Z","dependencies":[{"issue_id":"archie-core-abg.33","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.5.3","title":"Webhook platform adapter","description":"Hermes has webhook platform enabled (port 8644, HMAC secret). Sam confirmed webhooks are a must-have. This enables external services to push messages into archie-core's gateway for LLM processing.\n\nScope:\n- WebhookAdapter implementing gateway.Gateway interface\n- HTTP server with configurable host/port\n- Per-route HMAC validation\n- Deliver-only mode (inbound messages, no outbound send)\n- Idempotency cache for webhook deliveries\n- Prompt templates for transforming webhook payloads into messages","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:15Z","dependencies":[{"issue_id":"archie-core-abg.5.3","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.5.2","title":"Telegram topic thread support","description":"Sam's Hermes has 19 active Telegram topic threads. archie-core's Telegram channel treats all chats as flat DMs. Topic threads are how Sam organizes his workstreams — each thread is a separate context.\n\nScope:\n- Detect message_thread_id in Telegram updates\n- Route to correct session based on platform+chat_id+thread_id (SessionSource already has thread_id field)\n- Create/switch sessions per topic thread\n- /status and /model commands scoped to the thread","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:14Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:24:04Z","started_at":"2026-07-26T00:20:00Z","closed_at":"2026-07-26T00:24:04Z","close_reason":"Delivered: ThreadID field added to gateway.Message and SessionSource. SessionStore persists thread_id. Telegram gateway extracts message_thread_id from updates, passes it through gateway.Message, and sends replies to the correct thread. threadIDString helper maps 0→'' for flat-chat backward compatibility. Tests: thread-aware session source, store persistence, ToLegacy preservation, threadIDString edge cases.","dependencies":[{"issue_id":"archie-core-abg.5.2","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-abg.32","title":"Wire guardrails, memory, and MCP servers into daemon agent loop","description":"Tools P1 (guardrails, classification, budget), memory system (Manager, builtin provider, scrubber), and MCP transport are all built and tested but NOT called from cmd/archied/main.go. The daemon creates an agentexec.Runner but never passes GuardrailEngine, MemoryManager, or MCP client instances. This is THE blocker to using archie-core in place of Hermes.\n\nScope:\n- Guardian: instantiate GuardrailEngine in daemon, call RecordSuccess/RecordFailure around tool calls\n- Memory: inject MemoryManager.BuildSystemPrompt() into agent system prompt, wire HandleToolCall for memory tool routing\n- MCP: instantiate configured MCP servers from config, register their tools, wire into agent tool dispatch\n- Classification: use ToolClassification to gate parallel vs serial execution in the tool dispatcher","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:13Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:13Z","dependencies":[{"issue_id":"archie-core-abg.32","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.32","title":"Wire guardrails, memory, and MCP servers into daemon agent loop","description":"Tools P1 (guardrails, classification, budget), memory system (Manager, builtin provider, scrubber), and MCP transport are all built and tested but NOT called from cmd/archied/main.go. The daemon creates an agentexec.Runner but never passes GuardrailEngine, MemoryManager, or MCP client instances. This is THE blocker to using archie-core in place of Hermes.\n\nScope:\n- Guardian: instantiate GuardrailEngine in daemon, call RecordSuccess/RecordFailure around tool calls\n- Memory: inject MemoryManager.BuildSystemPrompt() into agent system prompt, wire HandleToolCall for memory tool routing\n- MCP: instantiate configured MCP servers from config, register their tools, wire into agent tool dispatch\n- Classification: use ToolClassification to gate parallel vs serial execution in the tool dispatcher","status":"closed","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:13Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:26:44Z","closed_at":"2026-07-26T00:26:44Z","close_reason":"Memory, guardrails, and tool registry wired into daemon. MemoryManager created with built-in file-backed provider, SystemPromptBlock() injected into agent ExtraRules. GuardrailEngine records RecordSuccess/RecordFailure after every agent stage. ToolRegistry created, MCP servers started from config. All nil-safe (backward compat). 38/38 packages pass with -race.","dependencies":[{"issue_id":"archie-core-abg.32","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.30v","title":"Verify: Integrate NellDB as persistent memory and configuration backend","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:14:14Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:31:12Z","closed_at":"2026-07-25T14:31:12Z","close_reason":"NellDB integrated as persistent backend. Created store.TaskStore interface, internal/nell/adapter.go with logstore.LogStore persistence, updated all consumers to depend on the interface. 7 integration tests verify enqueue, claim, transition, update, events, persistence across restart.","dependencies":[{"issue_id":"archie-core-abg.30v","depends_on_id":"archie-core-abg.30","type":"blocks","created_at":"2026-07-26T00:19:29Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.26","title":"Verify: Built-in memory tool actions: add, replace, remove","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:46Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:19:05Z","closed_at":"2026-07-25T16:19:05Z","close_reason":"Adversarial review found one real bug: renderSections() added a spurious blank line before/after empty sections (round-trip instability). Fixed in store.go (trailing separator only emitted when a section has blocks); added TestStore_EmptySectionRoundTrip regression test. All tests pass under -race, golangci-lint clean, gofmt clean.","dependencies":[{"issue_id":"archie-core-abg.18.26","depends_on_id":"archie-core-abg.18.13","type":"blocks","created_at":"2026-07-26T00:17:33Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.26","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:46Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.18.25","title":"Verify: Built-in memory tool: file-backed persistent memory","acceptance_criteria":"Independent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:12:38Z","created_by":"Sam Catlow","updated_at":"2026-07-25T16:19:04Z","closed_at":"2026-07-25T16:19:04Z","close_reason":"Adversarial review found one real bug: renderSections() added a spurious blank line before/after empty sections (round-trip instability). Fixed in store.go (trailing separator only emitted when a section has blocks); added TestStore_EmptySectionRoundTrip regression test. All tests pass under -race, golangci-lint clean, gofmt clean.","dependencies":[{"issue_id":"archie-core-abg.18.25","depends_on_id":"archie-core-abg.18.12","type":"blocks","created_at":"2026-07-26T00:19:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.18.25","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:12:37Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index e7b0d026f..ac68e5d8f 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -16,6 +16,8 @@ import ( natsio "github.com/nats-io/nats.go" + "github.com/samcharles93/ai-sdk/core" + "github.com/moby/moby/client" "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/channels/telegram" @@ -179,8 +181,14 @@ func run() int { storeBackend = storage.NewDockerBackend(dockerCli) } - // Gateways (optional -- absent [chat.telegram] disables). Multi-agent - // collaboration PRD phase C (docs/prds/multi-agent-collaboration.md). + // ── LLM runtime ────────────────────────────────────────────────── + // Created before gateways so the LLMResponder can be wired into the + // Telegram router for non-command message processing. + providers := executionProviders(cfg) + llm := agentexec.NewRuntime(providers) + + // ── Gateways ────────────────────────────────────────────────────── + // Multi-agent collaboration PRD phase C (docs/prds/multi-agent-collaboration.md). if cfg.Chat.Telegram.TokenEnv != "" { tgToken := os.Getenv(cfg.Chat.Telegram.TokenEnv) if tgToken == "" { @@ -188,10 +196,29 @@ func run() int { return 1 } tg := telegram.New(tgToken, "", "", nil, log) - // LLM responder is wired after agent startup — gateway-local - // commands (/status, /models, /model, /spawn) work without it. - // TODO: wrap llm.Chat() as gateway.LLMResponder for full parity. - router := gateway.NewRouter(st, nil, "telegram") + + // Build an LLM responder from the runtime. Gateway-local commands + // (/status, /models, /model, /spawn) are handled directly; all + // other messages are routed through the LLM. + var llmResponder gateway.LLMResponder + if llm != nil { + chatModel := cfg.Models["chat"] + if chatModel == "" { + chatModel = cfg.Models["builder"] + } + llmResponder = func(ctx context.Context, msg gateway.Message) (string, error) { + result, err := llm.Chat(ctx, chatModel, core.GenerateOptions{ + Prompt: msg.Text, + MaxSteps: 1, + }) + if err != nil { + return "", fmt.Errorf("llm chat: %w", err) + } + return result.Text, nil + } + } + + router := gateway.NewRouter(st, llmResponder, "telegram") if len(cfg.Repos) > 0 { router.Tasks = gateway.NewStoreTaskCreator(st, cfg.Repos[0].Owner, cfg.Repos[0].Name) } @@ -203,8 +230,6 @@ func run() int { log.Info("telegram gateway started") } - providers := executionProviders(cfg) - llm := agentexec.NewRuntime(providers) var agentRunner agentexec.Runner if llm != nil { switch cfg.Agent.Mode {