feat(gateway): ship model controls, shell tools, and release tracking
This commit is contained in:
1 parent
3cab289b41
commit
ec8534dfe2
34 files changed
+2335
-166
No files matched your search
+8
-3
@@ -53,10 +53,13 @@
|
||||
{"_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-ubl","title":"Durable scheduled agent tasks backed by Archie's task queue","description":"Add first-class one-shot, interval, and cron scheduling for Telegram agents. The scheduler decides when work is due but never executes an LLM or shell inline: it atomically enqueues a normal durable Archie task under the originating identity, and existing workers execute it with the usual tool, sandbox, lifecycle, and observability policies. Expose typed agent tools and Telegram management surfaces for create/list/status/pause/resume/delete/run-now, with delivery back to the originating chat.","acceptance_criteria":"Schedules support one-shot timestamps, fixed intervals, and cron expressions with explicit timezone. Definitions and execution history survive daemon restarts. Due firing uses an atomic lease/idempotency key so concurrent daemons and crash recovery do not duplicate a scheduled occurrence. Scheduler callbacks only enqueue normal tasks; they never run agents or shell commands inline. Each schedule records owner identity, origin chat/thread, prompt/task payload, enabled capability policy, overlap policy, next run, last result, and delivery state. Authorized users can create/list/status/pause/resume/delete/run-now from chat and equivalent typed agent tools. Missed-run, long-running overlap, clock/DST, cancellation, queue failure, execution failure, and delivery failure semantics are explicit and tested with a fake clock. Cron-spawned tasks cannot recursively create schedules unless explicitly authorized. Library selection is documented and does not replace Archie's durable queue semantics.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T20:05:57Z","created_by":"Sam Catlow","updated_at":"2026-07-26T20:05:57Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-4sr","title":"Gateway: unknown slash commands must not reach the LLM","description":"Unknown slash commands currently fall through to free-text LLM chat, causing fabricated command behavior such as /memories claims and false statements about files or model identity. Make slash command recognition deterministic and answer unknown commands locally with guidance to /help, while preserving free-text chat and supported Telegram bootstrap commands.","acceptance_criteria":"Any unrecognized leading slash command is answered locally and never invokes or streams from the LLM. The reply identifies the command as unknown and points to /help. Recognized commands and ordinary free text retain existing behavior. Telegram /start has an explicit deterministic behavior. Tests cover unknown commands with arguments and @gateway mentions, streaming routing, /start, and LLM non-invocation.","status":"in_progress","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:55:37Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:55:41Z","started_at":"2026-07-26T19:55:41Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-1d4","title":"Telegram: provider selector filters model choices","description":"Add an authorized native /provider inline selector. The selected provider scopes /model so only configured model references belonging to that provider are shown; e.g. openrouter/openai/gpt-5.6 must not appear under provider openai. Selecting a provider establishes a valid active model for that provider when necessary, and /status reports active provider and model.","acceptance_criteria":"/provider displays configured providers as an inline keyboard and marks the active provider. Authorized callbacks switch provider; unauthorized, malformed, stale, and duplicate callbacks fail safely. /model shows only models whose first reference segment matches the selected provider and uses unambiguous labels. Switching provider leaves the chat responder on a valid model from that provider. /status includes active provider and full model reference. Menu/help/executable parity and concurrent access are tested.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:55:36Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:55:40Z","started_at":"2026-07-26T19:55:40Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.44","title":"Firecracker substrate for sandboxed MCP code tools","description":"Replace the interim daemon-container code MCP execution path with a real Firecracker boundary. Extend or extract the gorev POC to support a long-lived bidirectional guest process, explicit workspace import/export, per-turn filesystem checkpoints, lifecycle/health, and concurrent-instance-safe networking. Then adapt the MCP provider launcher without changing the chat/tool contract.","acceptance_criteria":"MCP server code and tool execution occur inside a Firecracker VM; the guest cannot access daemon-host files outside the imported workspace; changes export deterministically; pre-change checkpoints support /restore; lifecycle cleanup survives crashes; tests prove the configured provider cannot silently fall back to host execution.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T19:31:13Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:31:13Z","dependencies":[{"issue_id":"archie-core-abg.17.44","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-27T05:31:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.38","title":"Telegram: interactive /model selector","description":"When /model is invoked without an argument, present Telegram-native interactive controls rather than only plain text usage. Use the pinned go-telegram/bot SDK inline keyboard and callback query APIs; preserve /model provider/model for typed selection and enforce the existing sender allowlist on callbacks.","acceptance_criteria":"An allowlisted user invoking /model receives an inline keyboard of configured models with the active model marked; tapping a model switches it through gateway.ModelManager, acknowledges the callback, and updates the message; unauthorized or malformed callbacks cannot switch models; empty model catalogs degrade safely.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T19:29:39Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:29:39Z","dependencies":[{"issue_id":"archie-core-abg.16.38","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:29:38Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.37","title":"Telegram: comprehensive truthful /help output","description":"The live /help response lists only /status and /help and still says LLM chat is not wired, despite the gateway supporting model, task, restart, and free-text chat paths. Replace the stale hardcoded copy with a complete, maintainable command guide that matches the registered menu and actual router behavior.","acceptance_criteria":"/help describes every published command with accurate usage, includes free-text chat behavior, no longer claims chat is unwired, and a regression test fails if the published command menu and help surface drift.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:29:38Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:29:46Z","started_at":"2026-07-26T19:29:46Z","dependencies":[{"issue_id":"archie-core-abg.16.37","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:29:38Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.43","title":"Wire MCP tool servers for the chat agent, sandboxed","description":"The chat agent has only memory_edit and skill_activate, so it cannot act on the codebase. cfg.Tools.MCPServers + the stdio transport are the designed extension point (configuredMCPProvider in cmd/archied/main.go already builds providers from config). Sam's requirement is to expose specific capabilities narrowly rather than granting host access, and he has a Firecracker sandbox POC at /work/clones/gorev (firecracker/sandbox) intended for exactly this.","acceptance_criteria":"MCP servers are configurable per deployment and discovered into the chat agent tool loop. A narrowly scoped code MCP server runs in the daemon container against an explicitly configured workspace and can make a code change end to end. Firecracker execution remains a requirement tracked separately in archie-core-abg.17.44.","notes":"User explicitly re-scoped on 2026-07-27: implement the chat code MCP path without Firecracker for now; Sam will wire Firecracker later. This interim path must be labelled unsandboxed and constrained to the daemon container/workspace, with a narrow launcher/execution boundary so the later sandbox can replace it. Prior Firecracker substrate findings remain relevant.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T19:15:34Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:32:29Z","started_at":"2026-07-26T19:27:33Z","dependencies":[{"issue_id":"archie-core-abg.17.43","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-27T05:15:34Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.38","title":"Telegram: interactive /model selector","description":"When /model is invoked without an argument, present Telegram-native interactive controls rather than only plain text usage. Use the pinned go-telegram/bot SDK inline keyboard and callback query APIs; preserve /model provider/model for typed selection and enforce the existing sender allowlist on callbacks.","acceptance_criteria":"An allowlisted user invoking /model receives an inline keyboard of configured models with the active model marked; tapping a model switches it through gateway.ModelManager, acknowledges the callback, and updates the message; unauthorized or malformed callbacks cannot switch models; empty model catalogs degrade safely.","notes":"Implemented native Telegram inline keyboard model selector and callback handling. Added concurrency-safe chat model manager wired into the actual LLM responder so selection affects subsequent turns. Focused tests green; awaiting full gate and fresh review.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:29:39Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:46:24Z","started_at":"2026-07-26T19:34:49Z","dependencies":[{"issue_id":"archie-core-abg.16.38","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:29:38Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.37","title":"Telegram: comprehensive truthful /help output","description":"The live /help response lists only /status and /help and still says LLM chat is not wired, despite the gateway supporting model, task, restart, and free-text chat paths. Replace the stale hardcoded copy with a complete, maintainable command guide that matches the registered menu and actual router behavior.","acceptance_criteria":"/help describes every published command with accurate usage, includes free-text chat behavior, no longer claims chat is unwired, and a regression test fails if the published command menu and help surface drift.","notes":"Implemented comprehensive /help from a shared command spec; added exact usage assertions and executable/published parity against gateway.LocalCommands plus Telegram-only commands. Focused tests green; awaiting full gate and fresh re-review.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:29:38Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:46:24Z","started_at":"2026-07-26T19:29:46Z","dependencies":[{"issue_id":"archie-core-abg.16.37","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:29:38Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.43","title":"Wire MCP tool servers for the chat agent, sandboxed","description":"The chat agent has only memory_edit and skill_activate, so it cannot act on the codebase. cfg.Tools.MCPServers + the stdio transport are the designed extension point (configuredMCPProvider in cmd/archied/main.go already builds providers from config). Sam's requirement is to expose specific capabilities narrowly rather than granting host access, and he has a Firecracker sandbox POC at /work/clones/gorev (firecracker/sandbox) intended for exactly this.","acceptance_criteria":"MCP servers are configurable per deployment and discovered into the chat agent tool loop. A narrowly scoped code MCP server runs in the daemon container against an explicitly configured workspace and can make a code change end to end. Firecracker execution remains a requirement tracked separately in archie-core-abg.17.44.","notes":"Implemented interim unsandboxed MCP CLIENT path with Desktop Commander 0.2.46 as managed stdio provider. Corrected custom client from incompatible Content-Length framing to MCP-standard newline-delimited JSON, added explicit subprocess work_dir, Node/npm to archied image, /workspace compose mount, and active docker overlay config. External integration completes initialize + tool discovery and now asserts persistent shell tools start_process, interact_with_process, and read_process_output. Firecracker isolation remains 17.44; no chat-output warning labels per Sam.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:15:34Z","created_by":"Sam Catlow","updated_at":"2026-07-26T20:06:03Z","started_at":"2026-07-26T19:27:33Z","dependencies":[{"issue_id":"archie-core-abg.17.43","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-27T05:15:34Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.35","title":"Telegram: /restart command to reload gateway config","description":"Operator escape hatch: restart the chat gateway from chat to pick up config changes (notably the allowlist) or recover from a wedged adapter, without shell access to the host.","acceptance_criteria":"/restart is admin-only (allowlisted sender). Re-reads config and restarts the gateway. Replies with the outcome. In-flight agent tasks are not killed.","notes":"Live Telegram transcript on 2026-07-27 shows /restart fell through to the LLM, which falsely replied that everything was reset. /help also omits /restart. Reopened for production-path diagnosis before /restore.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:11:42Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:26:25Z","started_at":"2026-07-26T19:20:06Z","closed_at":"2026-07-26T19:26:25Z","close_reason":"Shipped in e600cfa. Temporarily reopened after seeing a Telegram transcript where /restart fell through to the LLM, then Sam clarified that transcript predates deployment; no regression evidence.","dependencies":[{"issue_id":"archie-core-abg.16.35","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:11:42Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.34","title":"Telegram: register command menu via SetMyCommands","description":"The bot never calls SetMyCommands, so Telegram shows no command menu and the commands the Router implements (/status, /help, /models, /model, /spawn, /approve, /cancel) are undiscoverable. Asking the bot for /commands makes the LLM answer that it has none, which is wrong.","acceptance_criteria":"SetMyCommands is called at startup with the commands the Router actually handles. Failure is logged, not fatal.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T19:11:41Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:15:22Z","closed_at":"2026-07-26T19:15:22Z","close_reason":"Shipped in cec0f3e. 16.33: chat.telegram.allowed_user_ids plumbed through config; empty list now DENIES (was: allowed everyone); matches sender from.id not chat id so groups cannot inherit access; rejections logged with sender id; startup warns on empty list. Old TestIsChatAllowed asserted the vulnerable fail-open behaviour and was replaced with fail-closed tests. Sam's id 1312197967 added to carina's config.toml before push. 16.34: SetMyCommands publishes the command list Router actually handles; non-fatal on failure.","dependencies":[{"issue_id":"archie-core-abg.16.34","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:11:41Z","created_by":"Sam Catlow","metadata":"{}"}],"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":"closed","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:57:44Z","started_at":"2026-07-26T18:52:30Z","closed_at":"2026-07-26T18:57:44Z","close_reason":"Implemented via go-telegram/bot v1.22.0 rich messages. gateway.LLMStreamResponder + Router.RouteStream provide the streaming seam (degrades to Route when unset); telegram draft.go streams deltas through sendRichMessageDraft throttled to 700ms; main.go derives blocking and streaming responders from one shared turn impl using runtime.ChatStream. Also removed the markdownToHTML converter from the prior commit -- v1.22 takes Markdown natively and supports tables, so the conversion was unnecessary. 4 RouteStream tests; full suite + golangci-lint clean.","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}
|
||||
@@ -123,6 +126,8 @@
|
||||
{"_type":"issue","id":"archie-core-s1r","title":"Test forge fakes missing LinkBranch method broke go vet/test for whole module","description":"forge.Forge gained LinkBranch(ctx, owner, repo, issueNumber, branch) error in the branch-linking feature (ff4c51e) but the hand-rolled test doubles (stubForge in cmd/archied/main_test.go, prCapturingForge in cmd/archie-agent/taskrun_test.go, testForge in internal/daemon/daemon_test.go, fakeForge in internal/forgerpc/forgerpc_test.go) never got the method added, so they stopped satisfying forge.Forge. This broke go vet ./... and go test ./... for the entire module, not just those 4 packages, since go vet type-checks all test files as part of module vet. Fixed by adding LinkBranch stubs to all four fakes.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:04:53Z","created_by":"Sam Catlow","updated_at":"2026-07-24T03:04:58Z","closed_at":"2026-07-24T03:04:58Z","close_reason":"Added LinkBranch stub methods to stubForge, prCapturingForge, testForge, and fakeForge. go build/vet/test ./... now clean across the whole module.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-633","title":"config.docker.toml missing required fields, no overlay merge implemented","description":"config.docker.toml was rewritten to be a docs-as-overlay file (comment says base+overlay merge) but internal/config.Load has no merge logic and docker-compose.yml mounts only config.docker.toml at /etc/archie/config.toml. It is missing bot_user, [forge], [dispatch], [models], [providers], [budgets] which Load requires -\u003e daemon fails to start in docker as currently configured. Implement real base+overlay config loading (or restore a full standalone docker config) so there is one source of truth.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-24T02:42:07Z","created_by":"Sam Catlow","updated_at":"2026-07-24T02:44:53Z","started_at":"2026-07-24T02:42:11Z","closed_at":"2026-07-24T02:44:53Z","close_reason":"Implemented config.LoadOverlay (base decode + overlay decode into same struct, then shared finalize/validate), wired -config-overlay flag in cmd/archied, fixed docker-compose.yml to mount both base config.toml and config.docker.toml overlay, minimized config.docker.toml to true diff-only overlay, added tests proving overlay-omitted required fields (bot_user, repos) still come from base.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-u64","title":"Daemon: process multiple tasks concurrently (max_concurrency enforcement)","description":"Daemon currently processes one task at a time (docs/prds/archie-core-v2-architecture.md Phase 2). This is the core blocker between current state and any multi-agent scaling mode — needed before container max_concurrency or same-repo concurrency can matter. Wire the daemon's dispatch loop to run N tasks in parallel, respecting a configurable max_concurrency.","design":"internal/container/pool.go already enforces max_concurrency for container lifecycle — reuse that limit/pattern in the daemon's task dispatch rather than inventing a second concurrency control.","acceptance_criteria":"Daemon dispatch loop runs multiple tasks concurrently up to a configured max_concurrency limit; single-task-at-a-time behavior is gone.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:31Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:37:42Z","started_at":"2026-07-23T21:29:41Z","closed_at":"2026-07-23T21:37:42Z","close_reason":"Implemented concurrent SQLite and NATS task dispatch using containers.max_concurrency, with default same-repo serialization and race-tested dispatcher coverage.","dependency_count":0,"dependent_count":2,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-rqp","title":"Telegram: component-aware /update with approve or defer","description":"Add an /update control flow that checks for available releases, presents separate archied gateway and archie-agent runtime versions/changelog sections, and lets an authorized user approve or defer. Keep discovery and execution behind typed interfaces so Docker/Watchtower, package-manager, and other installations can supply their own updater without the Telegram gateway assuming a deployment mechanism.","acceptance_criteria":"/update reports whether gateway and runtime updates are available, with separate version and changelog sections and explicit no-change wording. Telegram provides Approve and Defer actions restricted to authorized users. Deferral is persisted and suppresses repeated prompts according to an explicit policy. Approval calls a typed installation updater and reports progress/failure without claiming success early. No Watchtower-only or Docker-only behavior exists in the gateway package. Commands, menu, help, callback authorization, concurrency, persistence, and failure paths are tested.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T19:47:21Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:47:21Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-b8t","title":"Telegram: announce newly installed Archie releases","description":"When archied starts after an installed release upgrade, notify authorized Telegram users once with an exact component-aware rundown from CHANGELOG.md. Present archied as THE GATEWAY and archie-agent as THE RUNTIME, explicitly saying when either component has no changes. Persist announced versions per recipient so ordinary restarts do not repeat notifications.","acceptance_criteria":"Repository has a maintained component-aware CHANGELOG.md. On an installed version advance, each configured authorized Telegram user receives one concise message with separate THE GATEWAY and THE RUNTIME sections and explicit no-change wording where applicable. Announced component versions are persisted and duplicate restarts do not repeat. First-run and development builds have explicit non-spam behavior. Parsing, version transition, persistence failure, and delivery failure paths are tested.","notes":"Component history decision: CHANGELOG.archied.md for gateway/control plane and CHANGELOG.archie.md for agent runtime, with root CHANGELOG.md as index. Installed/update messages render both sources and explicitly state when a component has no changes.","status":"in_progress","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:39:18Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:48:38Z","started_at":"2026-07-26T19:46:23Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.36","title":"Telegram: /restore to revert the last change","description":"Operator escape hatch requested alongside /restart: revert the last change from chat when an agent-authored change breaks something, without needing shell access to the host. Gateway-scoped.","acceptance_criteria":"Admin-only (allowlisted sender). Reverts the last change and reports what was reverted. Safe to run when there is nothing to revert.","notes":"Design finding: /restore must restore the latest agent-authored filesystem checkpoint, not revert an arbitrary daemon checkout commit. The change boundary will be owned by the sandboxed MCP execution layer: capture a pre-change checkpoint once per mutating agent turn, retain enough metadata to report files, and make restore safe/idempotent when empty. Hermes reference behavior uses this same filesystem-checkpoint boundary for /rollback; /undo is conversation-only. Blocked on 17.43.","status":"in_progress","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:15:34Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:27:32Z","started_at":"2026-07-26T19:25:16Z","dependencies":[{"issue_id":"archie-core-abg.16.36","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:15:33Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.16.36","depends_on_id":"archie-core-abg.17.43","type":"blocks","created_at":"2026-07-27T05:27:32Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-a5w","title":"Evaluate internal/workflow architecture and APIs","description":"Perform a read-only, repository-grounded evaluation of internal/workflow. Identify correctness, definition clarity, reuse, interface ownership, coupling, testability, and maintainability improvements, with concrete evidence and prioritized recommendations.","acceptance_criteria":"Assessment covers package definitions, consumers, subpackages, tests, and architecture invariants; findings are prioritized with file references and actionable recommendations; no code or git changes are made.","notes":"Evaluation completed. Highest-priority findings: repository Yaegi stages expose full TaskContext and may be evaluated in the daemon; workflow Run ignores persistence failures and returns no result; baseline runs after repo stages; push precedes custom gate and diff cap; TDD repro is not environmentally restricted to tests; routing and status models are stringly and ambiguous; extension loaders duplicate incompatible plugin contracts and silently skip failures; AgentStage review is unused by production definitions; chat tasks still hit issue-only operations; lifecycle and routing tests are materially incomplete. Scoped workflow tests passed with GPG fixture access and scoped golangci-lint reported zero issues.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T06:39:19Z","created_by":"Sam Catlow","updated_at":"2026-07-26T06:47:45Z","started_at":"2026-07-26T06:39:27Z","closed_at":"2026-07-26T06:47:45Z","close_reason":"Read-only package evaluation completed and reported with prioritized, actionable findings.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.42","title":"wire MCP per-server parallel-tool-calls flag into config and daemon startup","description":"Follow-up to archie-core-abg.17.20, which added mcp.Client.parallelToolCalls + WithParallelToolCalls(bool) at the client-API level (adversarially reviewed, race-clean). Nothing currently sets it: config.MCPServer (internal/config/config.go) has no field for it, and both NewClient call sites (cmd/archied/main.go:510's mcp.NewClient, and internal/tools/provider/mcp/provider.go:85's protocol.NewClient) construct clients without the option -- so the flag has zero effect in production as things stand today.","acceptance_criteria":"config.MCPServer gains a ParallelToolCalls bool field (default false, matching the client's safe-by-default); both NewClient call sites read it and pass mcp.WithParallelToolCalls(cfg value) accordingly; a config-driven test proves a server configured with parallel_tool_calls=true actually gets a parallel-opted Client.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T06:36:40Z","created_by":"Sam Catlow","updated_at":"2026-07-26T06:36:40Z","dependencies":[{"issue_id":"archie-core-abg.17.42","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T16:36:39Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
|
||||
@@ -7,6 +7,7 @@ name: deploy
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["archied/v*", "archie/v*"]
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
@@ -14,16 +15,30 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Log in to registry
|
||||
run: echo "${{ secrets.DEPLOY_TOKEN }}" | docker login git.catlow.cloud -u sam --password-stdin
|
||||
|
||||
- name: Build and push archied
|
||||
run: |
|
||||
docker build -f Dockerfile.archied -t git.catlow.cloud/sam/archied:latest .
|
||||
GATEWAY_TAG="$(git tag --points-at HEAD --list 'archied/v*' | sort -V | tail -1)"
|
||||
RUNTIME_TAG="$(git tag --points-at HEAD --list 'archie/v*' | sort -V | tail -1)"
|
||||
GATEWAY_VERSION="${GATEWAY_TAG#archied/}"
|
||||
RUNTIME_VERSION="${RUNTIME_TAG#archie/}"
|
||||
[ -n "$GATEWAY_VERSION" ] || GATEWAY_VERSION=dev
|
||||
[ -n "$RUNTIME_VERSION" ] || RUNTIME_VERSION=dev
|
||||
docker build \
|
||||
--build-arg GATEWAY_VERSION="$GATEWAY_VERSION" \
|
||||
--build-arg RUNTIME_VERSION="$RUNTIME_VERSION" \
|
||||
-f Dockerfile.archied -t git.catlow.cloud/sam/archied:latest .
|
||||
docker push git.catlow.cloud/sam/archied:latest
|
||||
|
||||
- name: Build and push archie-agent
|
||||
run: |
|
||||
docker build -f Dockerfile -t git.catlow.cloud/sam/archie-agent:latest .
|
||||
RUNTIME_TAG="$(git tag --points-at HEAD --list 'archie/v*' | sort -V | tail -1)"
|
||||
RUNTIME_VERSION="${RUNTIME_TAG#archie/}"
|
||||
[ -n "$RUNTIME_VERSION" ] || RUNTIME_VERSION=dev
|
||||
docker build --build-arg RUNTIME_VERSION="$RUNTIME_VERSION" -f Dockerfile -t git.catlow.cloud/sam/archie-agent:latest .
|
||||
docker push git.catlow.cloud/sam/archie-agent:latest
|
||||
@@ -0,0 +1,17 @@
|
||||
# archie-agent changelog
|
||||
|
||||
## [1.1.0] - 2026-07-27
|
||||
|
||||
- feat: add streamed agent execution with typed message events
|
||||
- feat: add MCP client transports and managed tool-provider discovery
|
||||
- feat: add memory context scrubbing and normalized memory tool schemas
|
||||
- feat: add plugin metadata extraction from `metadata.archie.plugins`
|
||||
- feat: add configurable container networking for daemon-launched runtimes
|
||||
- fix: preserve valid UTF-8 when clipping runtime output
|
||||
- fix: make MCP stdio lifecycle, retries, and timeout handling race-safe
|
||||
- fix: enforce a zero-finding lint and vet baseline
|
||||
|
||||
## [1.0.0] - 2026-07-22
|
||||
|
||||
- feat: ship the isolated agent runtime, NATS RPC boundary, workflow execution, skills, and plugin support
|
||||
- feat: publish the `archie-agent` container image to the Gitea registry
|
||||
@@ -0,0 +1,31 @@
|
||||
# archied changelog
|
||||
|
||||
## [1.1.0] - 2026-07-27
|
||||
|
||||
- feat: add the Telegram gateway with persistent sessions, topic-thread support, streamed rich replies, typing indicators, and Markdown rendering
|
||||
- feat: add `/spawn`, `/approve`, and `/cancel` for chat-driven task control
|
||||
- feat: provide a comprehensive `/help` guide whose command list stays aligned with Telegram's published menu and Archie's executable command surface
|
||||
- feat: add `/provider` and provider-filtered `/model` selectors that switch the provider and model used by subsequent live chat turns
|
||||
- feat: include the active provider and full model reference in `/status`
|
||||
- feat: notify authorized Telegram users once when a newly tagged component release is installed
|
||||
- feat: add `/restart` to reload and relaunch the Telegram gateway without interrupting in-flight daemon tasks
|
||||
- feat: add deny-by-default Telegram sender authorization and native command-menu publication
|
||||
- feat: connect Desktop Commander through Archie's managed MCP client so chat can use workspace file and process tools
|
||||
- feat: add multi-identity daemon configuration, persona routing, an email channel, and webhook platform support
|
||||
- feat: add NellDB-backed task, session, message, and memory persistence
|
||||
- feat: add memory synchronization, prefetch, context scrubbing, threat scanning, and built-in memory tools
|
||||
- feat: add tool guardrails, classification, budgets, availability filtering, and disclosure controls
|
||||
- feat: add feature-based YAML configuration with `conf.d` overlay loading
|
||||
- feat: add typed secret-engine registration and Yaegi extension support
|
||||
- fix: reject unknown slash commands locally instead of allowing the LLM to fabricate command behavior
|
||||
- fix: publish Telegram commands to default, private-chat, and group-chat scopes so stale commands inherited with the bot token cannot shadow Archie's menu
|
||||
- fix: drain the SDK's full event stream so streamed Telegram replies cannot deadlock
|
||||
- fix: use standard newline-delimited JSON framing for MCP stdio clients
|
||||
- fix: make MCP stdio shutdown and timeout handling race-safe
|
||||
- fix: restore legacy `[forge].token_env` compatibility and required container environment passthrough
|
||||
- fix: make the agent-container Docker network explicitly configurable
|
||||
|
||||
## [1.0.0] - 2026-07-22
|
||||
|
||||
- feat: ship the resident forge-polling daemon, deterministic workflow engine, isolated worktrees, quality gates, Gitea integration, Docker/NATS worker split, plugin loading, and skills support
|
||||
- feat: publish `archied` and `archie-agent` container images to the Gitea registry
|
||||
@@ -0,0 +1,10 @@
|
||||
# Changelogs
|
||||
|
||||
Archie has two independently versioned components:
|
||||
|
||||
- [CHANGELOG.archied.md](CHANGELOG.archied.md) — `archied`, the user-facing gateway and control plane.
|
||||
- [CHANGELOG.archie.md](CHANGELOG.archie.md) — `archie-agent`, the agent runtime.
|
||||
|
||||
Release tags use `archied/vX.Y.Z` and `archie/vX.Y.Z`. The gateway combines
|
||||
the matching component entries when it reports an installed or available
|
||||
update.
|
||||
@@ -78,5 +78,3 @@ bd close <id> # Complete work
|
||||
- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists.
|
||||
- Use `bd remember` / `bd memories <keyword>` for persistent knowledge — do NOT use MEMORY.md files.
|
||||
- Issues live in a local Dolt DB; sync uses `refs/dolt/data` on the git remote; `.beads/issues.jsonl` is a passive export, not the source of truth. See [SYNC_CONCEPTS.md](https://github.com/gastownhall/beads/blob/main/docs/SYNC_CONCEPTS.md).
|
||||
|
||||
**Git/session policy (conservative, default):** do not commit, push, or run Dolt remote sync unless explicitly asked. At session end: file beads for remaining work, run quality gates if code changed, update issue status, report `git status` and proposed commands, and wait for approval before any git operation.
|
||||
@@ -16,6 +16,8 @@ RUN CGO_ENABLED=0 go build -o /usr/local/bin/archie-agent ./cmd/archie-agent/
|
||||
|
||||
# ── runtime ───────────────────────────────────────────────────────────
|
||||
FROM ubuntu:24.04
|
||||
ARG RUNTIME_VERSION=dev
|
||||
LABEL org.opencontainers.image.version="${RUNTIME_VERSION}"
|
||||
|
||||
# Avoid interactive prompts during package installs.
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
+12
-2
@@ -6,11 +6,21 @@ WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 go build -o /usr/local/bin/archied ./cmd/archied/
|
||||
ARG GATEWAY_VERSION=dev
|
||||
ARG RUNTIME_VERSION=dev
|
||||
RUN CGO_ENABLED=0 go build \
|
||||
-ldflags "-X main.gatewayVersion=${GATEWAY_VERSION} -X main.runtimeVersion=${RUNTIME_VERSION}" \
|
||||
-o /usr/local/bin/archied ./cmd/archied/
|
||||
|
||||
FROM ubuntu:24.04
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates git && \
|
||||
ca-certificates git nodejs npm && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=builder /usr/local/bin/archied /usr/local/bin/archied
|
||||
ARG GATEWAY_VERSION=dev
|
||||
ARG RUNTIME_VERSION=dev
|
||||
LABEL org.opencontainers.image.version="${GATEWAY_VERSION}"
|
||||
LABEL cloud.catlow.archie.runtime-version="${RUNTIME_VERSION}"
|
||||
COPY CHANGELOG.archied.md /usr/share/archie/CHANGELOG.archied.md
|
||||
COPY CHANGELOG.archie.md /usr/share/archie/CHANGELOG.archie.md
|
||||
ENTRYPOINT ["archied"]
|
||||
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// chatModelManager owns the process-local model selected for interactive chat.
|
||||
// The configured role-to-model map supplies the available catalog; switching
|
||||
// chat models does not rewrite daemon configuration or affect workflow roles.
|
||||
type chatModelManager struct {
|
||||
mu sync.RWMutex
|
||||
models []string
|
||||
active string
|
||||
}
|
||||
|
||||
func newChatModelManager(configured map[string]string, catalogs ...[]string) *chatModelManager {
|
||||
unique := make(map[string]struct{}, len(configured))
|
||||
for _, ref := range configured {
|
||||
ref = strings.TrimSpace(ref)
|
||||
if ref != "" {
|
||||
unique[ref] = struct{}{}
|
||||
}
|
||||
}
|
||||
for _, catalog := range catalogs {
|
||||
for _, ref := range catalog {
|
||||
ref = strings.TrimSpace(ref)
|
||||
if ref != "" {
|
||||
unique[ref] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
models := make([]string, 0, len(unique))
|
||||
for ref := range unique {
|
||||
models = append(models, ref)
|
||||
}
|
||||
slices.Sort(models)
|
||||
|
||||
active := strings.TrimSpace(configured["chat"])
|
||||
if active == "" {
|
||||
active = strings.TrimSpace(configured["builder"])
|
||||
}
|
||||
return &chatModelManager{models: models, active: active}
|
||||
}
|
||||
|
||||
func (m *chatModelManager) Models() []string {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return slices.Clone(m.models)
|
||||
}
|
||||
|
||||
func (m *chatModelManager) ActiveModel() string {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.active
|
||||
}
|
||||
|
||||
func (m *chatModelManager) SetActiveModel(ctx context.Context, ref string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !slices.Contains(m.models, ref) {
|
||||
return fmt.Errorf("model %q is not configured", ref)
|
||||
}
|
||||
m.active = ref
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *chatModelManager) Providers() []string {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
seen := make(map[string]bool)
|
||||
var providers []string
|
||||
for _, model := range m.models {
|
||||
provider, _, ok := strings.Cut(model, "/")
|
||||
if ok && provider != "" && !seen[provider] {
|
||||
seen[provider] = true
|
||||
providers = append(providers, provider)
|
||||
}
|
||||
}
|
||||
slices.Sort(providers)
|
||||
return providers
|
||||
}
|
||||
|
||||
func (m *chatModelManager) ActiveProvider() string {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
provider, _, _ := strings.Cut(m.active, "/")
|
||||
return provider
|
||||
}
|
||||
|
||||
func (m *chatModelManager) ModelsForProvider(provider string) []string {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
prefix := provider + "/"
|
||||
var models []string
|
||||
for _, model := range m.models {
|
||||
if strings.HasPrefix(model, prefix) {
|
||||
models = append(models, model)
|
||||
}
|
||||
}
|
||||
return models
|
||||
}
|
||||
|
||||
func (m *chatModelManager) SetActiveProvider(ctx context.Context, provider string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
prefix := provider + "/"
|
||||
for _, model := range m.models {
|
||||
if strings.HasPrefix(model, prefix) {
|
||||
m.active = model
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("provider %q is not configured", provider)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChatModelManagerBuildsUniqueCatalogAndSelectsChatDefault(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"builder": "provider/zeta",
|
||||
"chat": "provider/alpha",
|
||||
"review": "provider/zeta",
|
||||
"empty": "",
|
||||
})
|
||||
|
||||
models := manager.Models()
|
||||
if len(models) != 2 || models[0] != "provider/alpha" || models[1] != "provider/zeta" {
|
||||
t.Fatalf("Models() = %v, want sorted unique model references", models)
|
||||
}
|
||||
models[0] = "mutated"
|
||||
if got := manager.Models()[0]; got != "provider/alpha" {
|
||||
t.Fatalf("Models() exposed internal state: first model = %q", got)
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "provider/alpha" {
|
||||
t.Fatalf("ActiveModel() = %q, want chat model", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerFallsBackToBuilder(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"builder": "provider/builder",
|
||||
"review": "provider/reviewer",
|
||||
})
|
||||
|
||||
if got := manager.ActiveModel(); got != "provider/builder" {
|
||||
t.Fatalf("ActiveModel() = %q, want builder fallback", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerSwitchesOnlyToConfiguredModels(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"chat": "provider/one",
|
||||
"review": "provider/two",
|
||||
})
|
||||
|
||||
if err := manager.SetActiveModel(context.Background(), "provider/two"); err != nil {
|
||||
t.Fatalf("SetActiveModel() error = %v", err)
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "provider/two" {
|
||||
t.Fatalf("ActiveModel() = %q, want switched model", got)
|
||||
}
|
||||
|
||||
if err := manager.SetActiveModel(context.Background(), "provider/unknown"); err == nil {
|
||||
t.Fatal("SetActiveModel() error = nil, want unknown-model error")
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "provider/two" {
|
||||
t.Fatalf("failed switch changed ActiveModel() to %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerHonorsCancelledContext(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"chat": "provider/one",
|
||||
"review": "provider/two",
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
if err := manager.SetActiveModel(ctx, "provider/two"); err == nil {
|
||||
t.Fatal("SetActiveModel() error = nil, want context cancellation")
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "provider/one" {
|
||||
t.Fatalf("cancelled switch changed ActiveModel() to %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerSeparatesProvidersAndModels(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"chat": "openrouter/openai/gpt-5.6",
|
||||
"builder": "openai/gpt-5.6",
|
||||
"review": "anthropic/claude-opus",
|
||||
})
|
||||
|
||||
providers := manager.Providers()
|
||||
if len(providers) != 3 ||
|
||||
providers[0] != "anthropic" ||
|
||||
providers[1] != "openai" ||
|
||||
providers[2] != "openrouter" {
|
||||
t.Fatalf("Providers() = %v", providers)
|
||||
}
|
||||
if got := manager.ActiveProvider(); got != "openrouter" {
|
||||
t.Fatalf("ActiveProvider() = %q, want openrouter", got)
|
||||
}
|
||||
if got := manager.ModelsForProvider("openai"); len(got) != 1 || got[0] != "openai/gpt-5.6" {
|
||||
t.Fatalf("openai models = %v", got)
|
||||
}
|
||||
if got := manager.ModelsForProvider("openrouter"); len(got) != 1 || got[0] != "openrouter/openai/gpt-5.6" {
|
||||
t.Fatalf("openrouter models = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerProviderSwitchSelectsValidModel(t *testing.T) {
|
||||
manager := newChatModelManager(map[string]string{
|
||||
"chat": "openrouter/openai/gpt-5.6",
|
||||
"builder": "openai/gpt-5.6",
|
||||
"review": "openai/o3",
|
||||
})
|
||||
|
||||
if err := manager.SetActiveProvider(context.Background(), "openai"); err != nil {
|
||||
t.Fatalf("SetActiveProvider() error = %v", err)
|
||||
}
|
||||
if got := manager.ActiveProvider(); got != "openai" {
|
||||
t.Fatalf("ActiveProvider() = %q, want openai", got)
|
||||
}
|
||||
if got := manager.ActiveModel(); got != "openai/gpt-5.6" {
|
||||
t.Fatalf("ActiveModel() = %q, want first configured openai model", got)
|
||||
}
|
||||
|
||||
if err := manager.SetActiveProvider(context.Background(), "missing"); err == nil {
|
||||
t.Fatal("SetActiveProvider() error = nil, want unknown-provider error")
|
||||
}
|
||||
if got := manager.ActiveProvider(); got != "openai" {
|
||||
t.Fatalf("failed switch changed provider to %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelManagerIncludesExplicitChatCatalog(t *testing.T) {
|
||||
manager := newChatModelManager(
|
||||
map[string]string{"chat": "openai/gpt-5.6-sol"},
|
||||
[]string{
|
||||
"openrouter/openai/gpt-5.6-sol",
|
||||
"anthropic/claude-opus",
|
||||
"openai/gpt-5.6-sol",
|
||||
},
|
||||
)
|
||||
|
||||
if got := manager.Models(); len(got) != 3 {
|
||||
t.Fatalf("Models() = %v, want workflow model plus explicit catalog", got)
|
||||
}
|
||||
if got := manager.ModelsForProvider("openrouter"); len(got) != 1 ||
|
||||
got[0] != "openrouter/openai/gpt-5.6-sol" {
|
||||
t.Fatalf("OpenRouter catalog = %v", got)
|
||||
}
|
||||
}
|
||||
+57
-15
@@ -6,6 +6,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
@@ -47,6 +48,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/plugin/pluginextract"
|
||||
"github.com/samcharles93/archie-core/internal/releaseannounce"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/skill"
|
||||
"github.com/samcharles93/archie-core/internal/storage"
|
||||
@@ -63,7 +65,19 @@ func main() {
|
||||
os.Exit(run())
|
||||
}
|
||||
|
||||
const defaultChatMaxSteps = 8
|
||||
const (
|
||||
defaultChatMaxSteps = 8
|
||||
packagedGatewayChangelogPath = "/usr/share/archie/CHANGELOG.archied.md"
|
||||
packagedRuntimeChangelogPath = "/usr/share/archie/CHANGELOG.archie.md"
|
||||
)
|
||||
|
||||
// Component versions are injected from their independent release tags.
|
||||
// Components without a release tag remain "dev" and never generate upgrade
|
||||
// notifications.
|
||||
var (
|
||||
gatewayVersion = "dev"
|
||||
runtimeVersion = "dev"
|
||||
)
|
||||
|
||||
func chatGenerateOptions(
|
||||
messages []chat.Message,
|
||||
@@ -99,6 +113,7 @@ func configuredMCPProvider(server config.MCPServer) (toolprovider.Engine, error)
|
||||
transport := mcp.NewStdioTransport(mcp.StdioTransportConfig{
|
||||
Command: command,
|
||||
Args: append([]string(nil), server.Args...),
|
||||
Dir: server.WorkDir,
|
||||
})
|
||||
return mcptoolprovider.New(name, transport), nil
|
||||
}
|
||||
@@ -241,6 +256,7 @@ func run() int {
|
||||
providers := executionProviders(cfg)
|
||||
llm := agentexec.NewRuntime(providers)
|
||||
toolReg := tools.NewRegistry()
|
||||
chatModels := newChatModelManager(cfg.Models, cfg.Chat.Models)
|
||||
|
||||
// ── Persona registry ─────────────────────────────────────────────
|
||||
personas := gateway.NewPersonaRegistry(gateway.DefaultPersonas())
|
||||
@@ -276,6 +292,24 @@ func run() int {
|
||||
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
|
||||
}
|
||||
tg := telegram.New(tgToken, "", "", cfg.Chat.Telegram.AllowedUserIDs, log)
|
||||
releaseAnnouncements := &releaseannounce.Announcer{
|
||||
StatePath: releaseAnnouncementStatePath(cfg.WorkDir, cfg.BotUser),
|
||||
Components: []releaseannounce.Component{
|
||||
{
|
||||
ID: "gateway",
|
||||
Label: "THE GATEWAY",
|
||||
Version: gatewayVersion,
|
||||
ChangelogPath: packagedGatewayChangelogPath,
|
||||
},
|
||||
{
|
||||
ID: "runtime",
|
||||
Label: "THE RUNTIME",
|
||||
Version: runtimeVersion,
|
||||
ChangelogPath: packagedRuntimeChangelogPath,
|
||||
},
|
||||
},
|
||||
}
|
||||
tg.ReleaseAnnouncements = releaseAnnouncements
|
||||
|
||||
// /restart re-reads config from disk so allowlist and token edits
|
||||
// apply without restarting the daemon and killing running tasks.
|
||||
@@ -317,23 +351,24 @@ func run() int {
|
||||
var llmResponder gateway.LLMResponder
|
||||
var llmStream gateway.LLMStreamResponder
|
||||
if llm != nil {
|
||||
chatModel := cfg.Models["chat"]
|
||||
if chatModel == "" {
|
||||
chatModel = cfg.Models["builder"]
|
||||
}
|
||||
// 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)
|
||||
if err := sessionStore.SaveMessage(ctx, sessionKey, msg); err != nil {
|
||||
return "", fmt.Errorf("save inbound chat message: %w", err)
|
||||
}
|
||||
|
||||
// Load recent conversation history for context.
|
||||
// Use a larger fetch window so compression has room to work
|
||||
// — older messages get summarised, recent ones stay intact.
|
||||
history, _ := sessionStore.RecentMessages(ctx, sessionKey, 100)
|
||||
compressed := make([]gateway.CompressedMessage, 0, len(history)+1)
|
||||
history, err := sessionStore.RecentMessages(ctx, sessionKey, 100)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("load chat history: %w", err)
|
||||
}
|
||||
compressed := make([]gateway.CompressedMessage, 0, len(history))
|
||||
for _, h := range history {
|
||||
role := "user"
|
||||
if h.From == cfg.BotUser {
|
||||
@@ -344,11 +379,6 @@ func run() int {
|
||||
Content: h.Text,
|
||||
})
|
||||
}
|
||||
compressed = append(compressed, gateway.CompressedMessage{
|
||||
Role: "user",
|
||||
Content: msg.Text,
|
||||
})
|
||||
|
||||
// Apply context compression for long-running sessions.
|
||||
compCfg := gateway.DefaultCompressionConfig()
|
||||
view := gateway.CompressHistory(compressed, compCfg)
|
||||
@@ -381,6 +411,7 @@ func run() int {
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build chat tools: %w", err)
|
||||
}
|
||||
chatModel := chatModels.ActiveModel()
|
||||
var text string
|
||||
if onDelta == nil {
|
||||
result, err := llm.Chat(ctx, chatModel, options)
|
||||
@@ -418,10 +449,12 @@ func run() int {
|
||||
}
|
||||
|
||||
// Persist the response.
|
||||
_ = sessionStore.SaveMessage(ctx, sessionKey, gateway.Message{
|
||||
if err := sessionStore.SaveMessage(ctx, sessionKey, gateway.Message{
|
||||
From: cfg.BotUser,
|
||||
Text: text,
|
||||
})
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("save outbound chat message: %w", err)
|
||||
}
|
||||
|
||||
return text, nil
|
||||
}
|
||||
@@ -436,6 +469,7 @@ func run() int {
|
||||
|
||||
router := gateway.NewRouter(st, llmResponder, "telegram")
|
||||
router.LLMStream = llmStream
|
||||
router.Models = chatModels
|
||||
configureTaskCommands(router, chatTasks, chatController, defaultChatIdentity)
|
||||
startGateways = append(startGateways, func() {
|
||||
go func() {
|
||||
@@ -915,6 +949,14 @@ func configHome() string {
|
||||
return filepath.Join(home, ".config")
|
||||
}
|
||||
|
||||
func releaseAnnouncementStatePath(workDir, identity string) string {
|
||||
identityHash := sha256.Sum256([]byte(identity))
|
||||
return filepath.Join(
|
||||
workDir,
|
||||
fmt.Sprintf("release-announcements-%x.json", identityHash[:8]),
|
||||
)
|
||||
}
|
||||
|
||||
// safePluginInfo calls Name() and Version() on a plugin, recovering from
|
||||
// panics. A panicking plugin must not crash the daemon at startup.
|
||||
func safePluginInfo(p plugin.Plugin) (name, version string) {
|
||||
|
||||
@@ -87,6 +87,22 @@ func TestGatewaysStartOnlyAfterCapabilityHostAndDaemonStartup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelegramRouterUsesRuntimeSelectableChatModel(t *testing.T) {
|
||||
source, err := os.ReadFile("main.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(source)
|
||||
for _, marker := range []string{
|
||||
"router.Models = chatModels",
|
||||
"chatModel := chatModels.ActiveModel()",
|
||||
} {
|
||||
if !strings.Contains(text, marker) {
|
||||
t.Errorf("Telegram chat model wiring missing %q", marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredMCPProviderSupportsOnlyExecutableStdioServers(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -144,6 +160,16 @@ func TestConfiguredMCPProviderSupportsOnlyExecutableStdioServers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredMCPProviderPassesWorkingDirectoryToClientTransport(t *testing.T) {
|
||||
source, err := os.ReadFile("main.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(source), "Dir: server.WorkDir") {
|
||||
t.Fatal("configured MCP client transport does not receive server.WorkDir")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatTaskWriterAdapter(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestArchiedImageAndComposeProvideDesktopCommanderClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
path string
|
||||
markers []string
|
||||
}{
|
||||
{
|
||||
path: "../../Dockerfile.archied",
|
||||
markers: []string{
|
||||
"nodejs npm",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "../../config.docker.toml",
|
||||
markers: []string{
|
||||
`name = "desktop-commander"`,
|
||||
`command = "npx"`,
|
||||
`"@wonderwhy-er/desktop-commander@0.2.46"`,
|
||||
`work_dir = "/workspace"`,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "../../docker-compose.yml",
|
||||
markers: []string{
|
||||
"./:/workspace",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "../../config.example.toml",
|
||||
markers: []string{
|
||||
"[[tools.mcp_servers]]",
|
||||
`work_dir = "/path/to/workspace"`,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.path, func(t *testing.T) {
|
||||
data, err := os.ReadFile(test.path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, marker := range test.markers {
|
||||
if !strings.Contains(string(data), marker) {
|
||||
t.Errorf("%s missing %q", test.path, marker)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReleaseMetadataIsBuiltAndPackagedWithArchied(t *testing.T) {
|
||||
dockerfile, err := os.ReadFile("../../Dockerfile.archied")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, marker := range []string{
|
||||
"ARG GATEWAY_VERSION=dev",
|
||||
"ARG RUNTIME_VERSION=dev",
|
||||
"-X main.gatewayVersion=${GATEWAY_VERSION}",
|
||||
"-X main.runtimeVersion=${RUNTIME_VERSION}",
|
||||
"COPY CHANGELOG.archied.md /usr/share/archie/CHANGELOG.archied.md",
|
||||
"COPY CHANGELOG.archie.md /usr/share/archie/CHANGELOG.archie.md",
|
||||
} {
|
||||
if !strings.Contains(string(dockerfile), marker) {
|
||||
t.Errorf("Dockerfile.archied missing %q", marker)
|
||||
}
|
||||
}
|
||||
|
||||
workflow, err := os.ReadFile("../../.gitea/workflows/deploy.yml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, marker := range []string{
|
||||
"fetch-depth: 0",
|
||||
`--points-at HEAD --list 'archied/v*'`,
|
||||
`--points-at HEAD --list 'archie/v*'`,
|
||||
`--build-arg GATEWAY_VERSION="$GATEWAY_VERSION"`,
|
||||
`--build-arg RUNTIME_VERSION="$RUNTIME_VERSION"`,
|
||||
} {
|
||||
if !strings.Contains(string(workflow), marker) {
|
||||
t.Errorf("deploy workflow missing %q", marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangelogsTrackGatewayAndRuntimeIndependently(t *testing.T) {
|
||||
changelog, err := os.ReadFile("../../CHANGELOG.md")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
index := string(changelog)
|
||||
for _, marker := range []string{
|
||||
"CHANGELOG.archied.md",
|
||||
"CHANGELOG.archie.md",
|
||||
"archied/vX.Y.Z",
|
||||
"archie/vX.Y.Z",
|
||||
} {
|
||||
if !strings.Contains(index, marker) {
|
||||
t.Errorf("CHANGELOG.md missing %q", marker)
|
||||
}
|
||||
}
|
||||
gateway, err := os.ReadFile("../../CHANGELOG.archied.md")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, marker := range []string{"## [1.1.0] - 2026-07-27", "/help", "/provider", "/model", "MCP"} {
|
||||
if !strings.Contains(string(gateway), marker) {
|
||||
t.Errorf("CHANGELOG.archied.md missing %q", marker)
|
||||
}
|
||||
}
|
||||
runtime, err := os.ReadFile("../../CHANGELOG.archie.md")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(runtime), "## [1.1.0] - 2026-07-27") {
|
||||
t.Error("CHANGELOG.archie.md missing current release section")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelegramReleaseAnnouncementsAreWiredFromDeploymentMetadata(t *testing.T) {
|
||||
source, err := os.ReadFile("main.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(source)
|
||||
for _, marker := range []string{
|
||||
"releaseannounce.Announcer{",
|
||||
`Label: "THE GATEWAY"`,
|
||||
`Label: "THE RUNTIME"`,
|
||||
"Version: gatewayVersion",
|
||||
"Version: runtimeVersion",
|
||||
"tg.ReleaseAnnouncements = releaseAnnouncements",
|
||||
} {
|
||||
if !strings.Contains(text, marker) {
|
||||
t.Errorf("Telegram release announcement wiring missing %q", marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -20,7 +20,14 @@ enabled = true
|
||||
image = "git.catlow.cloud/sam/archie-agent:latest"
|
||||
max_concurrency = 4
|
||||
max_uptime = "60m"
|
||||
pull_policy = "missing"
|
||||
pull_policy = "always"
|
||||
|
||||
[web]
|
||||
listen = "0.0.0.0:8484"
|
||||
|
||||
[[tools.mcp_servers]]
|
||||
name = "desktop-commander"
|
||||
transport = "stdio"
|
||||
command = "npx"
|
||||
args = ["-y", "@wonderwhy-er/desktop-commander@0.2.46", "--no-onboarding"]
|
||||
work_dir = "/workspace"
|
||||
@@ -42,6 +42,23 @@ api_key_env = "OPENAI_API_KEY"
|
||||
[providers.ollama]
|
||||
class = "ollama"
|
||||
|
||||
# Optional interactive-chat catalog. /provider groups these references by
|
||||
# their first path segment, and /model shows only the selected provider's
|
||||
# entries. When omitted, Archie uses the distinct refs in [models].
|
||||
# [chat]
|
||||
# models = [
|
||||
# "openai/gpt-5.6-sol",
|
||||
# "openrouter/openai/gpt-5.6-sol",
|
||||
# ]
|
||||
|
||||
# External MCP tools are launched and managed by Archie's MCP client.
|
||||
# [[tools.mcp_servers]]
|
||||
# name = "desktop-commander"
|
||||
# transport = "stdio"
|
||||
# command = "npx"
|
||||
# args = ["-y", "@wonderwhy-er/desktop-commander@0.2.46", "--no-onboarding"]
|
||||
# work_dir = "/path/to/workspace"
|
||||
|
||||
[agent]
|
||||
mode = "inprocess" # "subprocess" runs each stage through archie-agent (stdin/stdout); "nats" sends stages over NATS
|
||||
command = "archie-agent" # executable path for subprocess mode (not used in nats mode)
|
||||
|
||||
@@ -37,6 +37,7 @@ services:
|
||||
volumes:
|
||||
- ${HOME}/.config/archie/config.toml:/etc/archie/config.toml:ro
|
||||
- ./config.docker.toml:/etc/archie/config.docker.toml:ro
|
||||
- ./:/workspace
|
||||
- /var/lib/archie/work:/var/lib/archie/work
|
||||
- /var/lib/archie/db:/var/lib/archie
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
@@ -21,6 +21,7 @@ type commandSpec struct {
|
||||
var gatewayCommandSpecs = []commandSpec{
|
||||
{Command: "status", Description: "Show task counts by state", Usage: "/status"},
|
||||
{Command: "models", Description: "List available models", Usage: "/models"},
|
||||
{Command: "provider", Description: "Choose the provider used for chat", Usage: "/provider"},
|
||||
{Command: "model", Description: "Show the model selector or switch directly", Usage: "/model [provider/model]"},
|
||||
{Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] <title>"},
|
||||
{Command: "approve", Description: "Approve and requeue a waiting task", Usage: "/approve [identity=name] <task-id>"},
|
||||
@@ -29,6 +30,8 @@ var gatewayCommandSpecs = []commandSpec{
|
||||
{Command: "help", Description: "Show this guide", Usage: "/help"},
|
||||
}
|
||||
|
||||
var telegramOnlyCommands = []string{"provider", "restart", "help"}
|
||||
|
||||
var gatewayCommands = func() []models.BotCommand {
|
||||
commands := make([]models.BotCommand, 0, len(gatewayCommandSpecs))
|
||||
for _, spec := range gatewayCommandSpecs {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
const modelCallbackPrefix = "model:"
|
||||
|
||||
func isModelSelectorRequest(text string) bool {
|
||||
fields := strings.Fields(text)
|
||||
if len(fields) != 1 {
|
||||
return false
|
||||
}
|
||||
command, _, _ := strings.Cut(fields[0], "@")
|
||||
return command == "/model"
|
||||
}
|
||||
|
||||
func (g *Gateway) sendModelSelector(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
msg *models.Message,
|
||||
router *gateway.Router,
|
||||
) {
|
||||
if router.Models == nil || len(router.Models.Models()) == 0 {
|
||||
reply, err := router.Route(ctx, gateway.Message{Text: "/model"})
|
||||
if err != nil {
|
||||
g.log.Error("model selector fallback failed", "error", err)
|
||||
return
|
||||
}
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply)
|
||||
return
|
||||
}
|
||||
|
||||
params := &bot.SendMessageParams{
|
||||
ChatID: msg.Chat.ID,
|
||||
Text: modelSelectorText(router.Models.ActiveModel()),
|
||||
ReplyMarkup: modelSelectorKeyboard(router.Models),
|
||||
}
|
||||
if msg.MessageThreadID != 0 {
|
||||
params.MessageThreadID = msg.MessageThreadID
|
||||
}
|
||||
if _, err := b.SendMessage(ctx, params); err != nil {
|
||||
g.log.Error("send model selector failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func modelSelectorText(active string) string {
|
||||
if active == "" {
|
||||
return "Choose a model:"
|
||||
}
|
||||
return "Choose a model:\nActive: " + active
|
||||
}
|
||||
|
||||
func modelSelectorKeyboard(manager gateway.ModelManager) *models.InlineKeyboardMarkup {
|
||||
active := manager.ActiveModel()
|
||||
available := selectableModels(manager)
|
||||
activeProvider := ""
|
||||
if providerManager, ok := manager.(gateway.ProviderModelManager); ok {
|
||||
activeProvider = providerManager.ActiveProvider()
|
||||
}
|
||||
rows := make([][]models.InlineKeyboardButton, 0, len(available))
|
||||
for index, model := range available {
|
||||
label := model
|
||||
if activeProvider != "" {
|
||||
label = strings.TrimPrefix(model, activeProvider+"/")
|
||||
}
|
||||
if model == active {
|
||||
label = "✓ " + model
|
||||
}
|
||||
rows = append(rows, []models.InlineKeyboardButton{{
|
||||
Text: label,
|
||||
CallbackData: modelCallbackPrefix + strconv.Itoa(index),
|
||||
}})
|
||||
}
|
||||
return &models.InlineKeyboardMarkup{InlineKeyboard: rows}
|
||||
}
|
||||
|
||||
func selectableModels(manager gateway.ModelManager) []string {
|
||||
if providerManager, ok := manager.(gateway.ProviderModelManager); ok {
|
||||
return providerManager.ModelsForProvider(providerManager.ActiveProvider())
|
||||
}
|
||||
return manager.Models()
|
||||
}
|
||||
|
||||
func (g *Gateway) handleModelCallback(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
update *models.Update,
|
||||
router *gateway.Router,
|
||||
) {
|
||||
query := update.CallbackQuery
|
||||
if query == nil {
|
||||
return
|
||||
}
|
||||
if !g.isSenderAllowed(query.From.ID) {
|
||||
g.log.Warn("model callback from unauthorized sender", "user_id", query.From.ID)
|
||||
g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
if router.Models == nil {
|
||||
g.answerModelCallback(ctx, b, query.ID, "Model switching is not configured.", true)
|
||||
return
|
||||
}
|
||||
|
||||
indexText := strings.TrimPrefix(query.Data, modelCallbackPrefix)
|
||||
index, err := strconv.Atoi(indexText)
|
||||
available := selectableModels(router.Models)
|
||||
if err != nil || index < 0 || index >= len(available) {
|
||||
g.answerModelCallback(ctx, b, query.ID, "That model selection is no longer valid.", true)
|
||||
return
|
||||
}
|
||||
selected := available[index]
|
||||
if err := router.Models.SetActiveModel(ctx, selected); err != nil {
|
||||
g.answerModelCallback(ctx, b, query.ID, fmt.Sprintf("Cannot switch: %v", err), true)
|
||||
return
|
||||
}
|
||||
|
||||
g.answerModelCallback(ctx, b, query.ID, "Active model: "+selected, false)
|
||||
g.updateModelSelector(ctx, b, query, router.Models)
|
||||
}
|
||||
|
||||
func (g *Gateway) answerModelCallback(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
queryID string,
|
||||
text string,
|
||||
alert bool,
|
||||
) {
|
||||
if _, err := b.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{
|
||||
CallbackQueryID: queryID,
|
||||
Text: text,
|
||||
ShowAlert: alert,
|
||||
}); err != nil {
|
||||
g.log.Warn("answer model callback failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) updateModelSelector(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
query *models.CallbackQuery,
|
||||
manager gateway.ModelManager,
|
||||
) {
|
||||
params := &bot.EditMessageTextParams{
|
||||
Text: modelSelectorText(manager.ActiveModel()),
|
||||
ReplyMarkup: modelSelectorKeyboard(manager),
|
||||
}
|
||||
switch {
|
||||
case query.Message.Message != nil:
|
||||
params.ChatID = query.Message.Message.Chat.ID
|
||||
params.MessageID = query.Message.Message.ID
|
||||
case query.InlineMessageID != "":
|
||||
params.InlineMessageID = query.InlineMessageID
|
||||
default:
|
||||
return
|
||||
}
|
||||
if _, err := b.EditMessageText(ctx, params); err != nil {
|
||||
g.log.Warn("update model selector failed", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
type modelManagerStub struct {
|
||||
models []string
|
||||
active string
|
||||
}
|
||||
|
||||
func (m *modelManagerStub) Models() []string {
|
||||
return append([]string(nil), m.models...)
|
||||
}
|
||||
|
||||
func (m *modelManagerStub) ActiveModel() string {
|
||||
return m.active
|
||||
}
|
||||
|
||||
func (m *modelManagerStub) SetActiveModel(_ context.Context, ref string) error {
|
||||
if slices.Contains(m.models, ref) {
|
||||
m.active = ref
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown model: %s", ref)
|
||||
}
|
||||
|
||||
func (m *modelManagerStub) Providers() []string {
|
||||
seen := make(map[string]bool)
|
||||
var providers []string
|
||||
for _, model := range m.models {
|
||||
provider, _, ok := strings.Cut(model, "/")
|
||||
if ok && !seen[provider] {
|
||||
seen[provider] = true
|
||||
providers = append(providers, provider)
|
||||
}
|
||||
}
|
||||
return providers
|
||||
}
|
||||
|
||||
func (m *modelManagerStub) ActiveProvider() string {
|
||||
provider, _, _ := strings.Cut(m.active, "/")
|
||||
return provider
|
||||
}
|
||||
|
||||
func (m *modelManagerStub) ModelsForProvider(provider string) []string {
|
||||
var models []string
|
||||
for _, model := range m.models {
|
||||
if strings.HasPrefix(model, provider+"/") {
|
||||
models = append(models, model)
|
||||
}
|
||||
}
|
||||
return models
|
||||
}
|
||||
|
||||
func (m *modelManagerStub) SetActiveProvider(_ context.Context, provider string) error {
|
||||
models := m.ModelsForProvider(provider)
|
||||
if len(models) == 0 {
|
||||
return fmt.Errorf("unknown provider: %s", provider)
|
||||
}
|
||||
m.active = models[0]
|
||||
return nil
|
||||
}
|
||||
|
||||
type telegramRequest struct {
|
||||
method string
|
||||
form map[string]string
|
||||
}
|
||||
|
||||
func newTelegramTestBot(t *testing.T) (*bot.Bot, *[]telegramRequest) {
|
||||
t.Helper()
|
||||
|
||||
var requests []telegramRequest
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseMultipartForm(1 << 20); err != nil {
|
||||
t.Errorf("parse Telegram request: %v", err)
|
||||
}
|
||||
form := make(map[string]string, len(r.MultipartForm.Value))
|
||||
for key, values := range r.MultipartForm.Value {
|
||||
if len(values) > 0 {
|
||||
form[key] = values[0]
|
||||
}
|
||||
}
|
||||
requests = append(requests, telegramRequest{
|
||||
method: r.URL.Path[strings.LastIndexByte(r.URL.Path, '/')+1:],
|
||||
form: form,
|
||||
})
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch requests[len(requests)-1].method {
|
||||
case "answerCallbackQuery", "sendChatAction":
|
||||
_, _ = w.Write([]byte(`{"ok":true,"result":true}`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":9,"date":1,"chat":{"id":7,"type":"private"}}}`))
|
||||
}
|
||||
}))
|
||||
t.Cleanup(api.Close)
|
||||
|
||||
b, err := bot.New(
|
||||
"1:test",
|
||||
bot.WithServerURL(api.URL),
|
||||
bot.WithSkipGetMe(),
|
||||
bot.WithNotAsyncHandlers(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("new test bot: %v", err)
|
||||
}
|
||||
return b, &requests
|
||||
}
|
||||
|
||||
func TestModelCommandShowsInlineSelector(t *testing.T) {
|
||||
const allowedUserID = int64(42)
|
||||
manager := &modelManagerStub{
|
||||
models: []string{"provider/alpha", "provider/beta"},
|
||||
active: "provider/beta",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
Message: &models.Message{
|
||||
From: &models.User{ID: allowedUserID},
|
||||
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
|
||||
Text: "/model",
|
||||
},
|
||||
})
|
||||
|
||||
var markup models.InlineKeyboardMarkup
|
||||
found := false
|
||||
for _, request := range *requests {
|
||||
raw, ok := request.form["reply_markup"]
|
||||
if request.method != "sendMessage" || !ok {
|
||||
continue
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &markup); err != nil {
|
||||
t.Fatalf("decode reply markup: %v", err)
|
||||
}
|
||||
found = true
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("/model did not send an inline keyboard; requests: %#v", *requests)
|
||||
}
|
||||
if got := len(markup.InlineKeyboard); got != len(manager.models) {
|
||||
t.Fatalf("keyboard rows = %d, want %d", got, len(manager.models))
|
||||
}
|
||||
for index, row := range markup.InlineKeyboard {
|
||||
if len(row) != 1 {
|
||||
t.Fatalf("keyboard row %d has %d buttons, want 1", index, len(row))
|
||||
}
|
||||
button := row[0]
|
||||
if button.CallbackData != fmt.Sprintf("model:%d", index) {
|
||||
t.Errorf("button %d callback = %q", index, button.CallbackData)
|
||||
}
|
||||
_, modelLabel, _ := strings.Cut(manager.models[index], "/")
|
||||
if !strings.Contains(button.Text, modelLabel) {
|
||||
t.Errorf("button %d text = %q, want model label %q", index, button.Text, modelLabel)
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(markup.InlineKeyboard[1][0].Text, "✓ ") {
|
||||
t.Errorf("active model button is not marked: %q", markup.InlineKeyboard[1][0].Text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderCommandFiltersSubsequentModelSelector(t *testing.T) {
|
||||
const allowedUserID = int64(42)
|
||||
manager := &modelManagerStub{
|
||||
models: []string{
|
||||
"openrouter/openai/gpt-5.6",
|
||||
"openai/gpt-5.6",
|
||||
"openai/o3",
|
||||
},
|
||||
active: "openrouter/openai/gpt-5.6",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
Message: &models.Message{
|
||||
From: &models.User{ID: allowedUserID},
|
||||
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
|
||||
Text: "/provider",
|
||||
},
|
||||
})
|
||||
var providerMarkup models.InlineKeyboardMarkup
|
||||
if err := json.Unmarshal([]byte((*requests)[0].form["reply_markup"]), &providerMarkup); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(providerMarkup.InlineKeyboard) != 2 {
|
||||
t.Fatalf("provider rows = %d, want 2", len(providerMarkup.InlineKeyboard))
|
||||
}
|
||||
|
||||
*requests = nil
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "provider-callback",
|
||||
From: models.User{ID: allowedUserID},
|
||||
Data: "provider:1",
|
||||
Message: models.MaybeInaccessibleMessage{
|
||||
Type: models.MaybeInaccessibleMessageTypeMessage,
|
||||
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
|
||||
},
|
||||
},
|
||||
})
|
||||
if manager.ActiveProvider() != "openai" {
|
||||
t.Fatalf("active provider = %q, want openai", manager.ActiveProvider())
|
||||
}
|
||||
|
||||
*requests = nil
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
Message: &models.Message{
|
||||
From: &models.User{ID: allowedUserID},
|
||||
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
|
||||
Text: "/model",
|
||||
},
|
||||
})
|
||||
var modelMarkup models.InlineKeyboardMarkup
|
||||
for _, request := range *requests {
|
||||
if raw := request.form["reply_markup"]; raw != "" {
|
||||
if err := json.Unmarshal([]byte(raw), &modelMarkup); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(modelMarkup.InlineKeyboard) != 2 {
|
||||
t.Fatalf("filtered model rows = %d, want 2", len(modelMarkup.InlineKeyboard))
|
||||
}
|
||||
for _, row := range modelMarkup.InlineKeyboard {
|
||||
if strings.Contains(row[0].Text, "openrouter") {
|
||||
t.Fatalf("OpenRouter model leaked into OpenAI selection: %q", row[0].Text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelCallbackSwitchesAndUpdatesSelector(t *testing.T) {
|
||||
const allowedUserID = int64(42)
|
||||
manager := &modelManagerStub{
|
||||
models: []string{"provider/alpha", "provider/beta"},
|
||||
active: "provider/alpha",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "callback-id",
|
||||
From: models.User{ID: allowedUserID},
|
||||
Data: "model:1",
|
||||
Message: models.MaybeInaccessibleMessage{
|
||||
Type: models.MaybeInaccessibleMessageTypeMessage,
|
||||
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if manager.active != "provider/beta" {
|
||||
t.Fatalf("active model = %q, want provider/beta", manager.active)
|
||||
}
|
||||
var answered, edited bool
|
||||
for _, request := range *requests {
|
||||
answered = answered || request.method == "answerCallbackQuery"
|
||||
edited = edited || request.method == "editMessageText"
|
||||
}
|
||||
if !answered || !edited {
|
||||
t.Fatalf("callback answered=%t edited=%t, requests: %#v", answered, edited, *requests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelCallbackRejectsUnauthorizedAndMalformedSelections(t *testing.T) {
|
||||
const allowedUserID = int64(42)
|
||||
tests := []struct {
|
||||
name string
|
||||
userID int64
|
||||
data string
|
||||
}{
|
||||
{name: "unauthorized sender", userID: 99, data: "model:1"},
|
||||
{name: "malformed index", userID: allowedUserID, data: "model:not-an-index"},
|
||||
{name: "out of range", userID: allowedUserID, data: "model:99"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
manager := &modelManagerStub{
|
||||
models: []string{"provider/alpha", "provider/beta"},
|
||||
active: "provider/alpha",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "callback-id",
|
||||
From: models.User{ID: tt.userID},
|
||||
Data: tt.data,
|
||||
},
|
||||
})
|
||||
|
||||
if manager.active != "provider/alpha" {
|
||||
t.Fatalf("active model changed to %q", manager.active)
|
||||
}
|
||||
var answer *telegramRequest
|
||||
for index := range *requests {
|
||||
if (*requests)[index].method == "answerCallbackQuery" {
|
||||
answer = &(*requests)[index]
|
||||
}
|
||||
}
|
||||
if answer == nil || answer.form["show_alert"] != "true" {
|
||||
t.Fatalf("rejection did not answer with an alert; requests: %#v", *requests)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderCallbackRejectsUnauthorizedAndMalformedSelections(t *testing.T) {
|
||||
const allowedUserID = int64(42)
|
||||
tests := []struct {
|
||||
name string
|
||||
userID int64
|
||||
data string
|
||||
}{
|
||||
{name: "unauthorized sender", userID: 99, data: "provider:1"},
|
||||
{name: "malformed index", userID: allowedUserID, data: "provider:not-an-index"},
|
||||
{name: "out of range", userID: allowedUserID, data: "provider:99"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
manager := &modelManagerStub{
|
||||
models: []string{"openrouter/openai/gpt-5.6", "openai/gpt-5.6"},
|
||||
active: "openrouter/openai/gpt-5.6",
|
||||
}
|
||||
router := gateway.NewRouter(nil, nil, "telegram")
|
||||
router.Models = manager
|
||||
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.defaultHandler(router)(context.Background(), b, &models.Update{
|
||||
CallbackQuery: &models.CallbackQuery{
|
||||
ID: "callback-id",
|
||||
From: models.User{ID: tt.userID},
|
||||
Data: tt.data,
|
||||
},
|
||||
})
|
||||
|
||||
if manager.active != "openrouter/openai/gpt-5.6" {
|
||||
t.Fatalf("active provider/model changed to %q", manager.active)
|
||||
}
|
||||
var answer *telegramRequest
|
||||
for index := range *requests {
|
||||
if (*requests)[index].method == "answerCallbackQuery" {
|
||||
answer = &(*requests)[index]
|
||||
}
|
||||
}
|
||||
if answer == nil || answer.form["show_alert"] != "true" {
|
||||
t.Fatalf("rejection did not answer with an alert; requests: %#v", *requests)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
const providerCallbackPrefix = "provider:"
|
||||
|
||||
func isProviderSelectorRequest(text string) bool {
|
||||
fields := strings.Fields(text)
|
||||
if len(fields) != 1 {
|
||||
return false
|
||||
}
|
||||
command, _, _ := strings.Cut(fields[0], "@")
|
||||
return command == "/provider"
|
||||
}
|
||||
|
||||
func (g *Gateway) sendProviderSelector(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
msg *models.Message,
|
||||
router *gateway.Router,
|
||||
) {
|
||||
manager, ok := router.Models.(gateway.ProviderModelManager)
|
||||
if !ok || len(manager.Providers()) == 0 {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Provider switching is not configured.")
|
||||
return
|
||||
}
|
||||
params := &bot.SendMessageParams{
|
||||
ChatID: msg.Chat.ID,
|
||||
Text: providerSelectorText(manager.ActiveProvider()),
|
||||
ReplyMarkup: providerSelectorKeyboard(manager),
|
||||
}
|
||||
if msg.MessageThreadID != 0 {
|
||||
params.MessageThreadID = msg.MessageThreadID
|
||||
}
|
||||
if _, err := b.SendMessage(ctx, params); err != nil {
|
||||
g.log.Error("send provider selector failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func providerSelectorText(active string) string {
|
||||
if active == "" {
|
||||
return "Choose a provider:"
|
||||
}
|
||||
return "Choose a provider:\nActive: " + providerDisplayName(active)
|
||||
}
|
||||
|
||||
func providerSelectorKeyboard(manager gateway.ProviderModelManager) *models.InlineKeyboardMarkup {
|
||||
active := manager.ActiveProvider()
|
||||
providers := manager.Providers()
|
||||
rows := make([][]models.InlineKeyboardButton, 0, len(providers))
|
||||
for index, provider := range providers {
|
||||
label := providerDisplayName(provider)
|
||||
if provider == active {
|
||||
label = "✓ " + label
|
||||
}
|
||||
rows = append(rows, []models.InlineKeyboardButton{{
|
||||
Text: label,
|
||||
CallbackData: providerCallbackPrefix + strconv.Itoa(index),
|
||||
}})
|
||||
}
|
||||
return &models.InlineKeyboardMarkup{InlineKeyboard: rows}
|
||||
}
|
||||
|
||||
func providerDisplayName(provider string) string {
|
||||
switch strings.ToLower(provider) {
|
||||
case "openai":
|
||||
return "OpenAI"
|
||||
case "openrouter":
|
||||
return "OpenRouter"
|
||||
case "anthropic":
|
||||
return "Anthropic"
|
||||
case "deepseek":
|
||||
return "DeepSeek"
|
||||
case "google":
|
||||
return "Google"
|
||||
case "ollama":
|
||||
return "Ollama"
|
||||
default:
|
||||
return provider
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) handleProviderCallback(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
update *models.Update,
|
||||
router *gateway.Router,
|
||||
) {
|
||||
query := update.CallbackQuery
|
||||
if query == nil {
|
||||
return
|
||||
}
|
||||
if !g.isSenderAllowed(query.From.ID) {
|
||||
g.log.Warn("provider callback from unauthorized sender", "user_id", query.From.ID)
|
||||
g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
manager, ok := router.Models.(gateway.ProviderModelManager)
|
||||
if !ok {
|
||||
g.answerModelCallback(ctx, b, query.ID, "Provider switching is not configured.", true)
|
||||
return
|
||||
}
|
||||
indexText := strings.TrimPrefix(query.Data, providerCallbackPrefix)
|
||||
index, err := strconv.Atoi(indexText)
|
||||
providers := manager.Providers()
|
||||
if err != nil || index < 0 || index >= len(providers) {
|
||||
g.answerModelCallback(ctx, b, query.ID, "That provider selection is no longer valid.", true)
|
||||
return
|
||||
}
|
||||
selected := providers[index]
|
||||
if err := manager.SetActiveProvider(ctx, selected); err != nil {
|
||||
g.answerModelCallback(ctx, b, query.ID, fmt.Sprintf("Cannot switch: %v", err), true)
|
||||
return
|
||||
}
|
||||
g.answerModelCallback(ctx, b, query.ID, "Active provider: "+providerDisplayName(selected), false)
|
||||
g.updateProviderSelector(ctx, b, query, manager)
|
||||
}
|
||||
|
||||
func (g *Gateway) updateProviderSelector(
|
||||
ctx context.Context,
|
||||
b *bot.Bot,
|
||||
query *models.CallbackQuery,
|
||||
manager gateway.ProviderModelManager,
|
||||
) {
|
||||
params := &bot.EditMessageTextParams{
|
||||
Text: providerSelectorText(manager.ActiveProvider()),
|
||||
ReplyMarkup: providerSelectorKeyboard(manager),
|
||||
}
|
||||
switch {
|
||||
case query.Message.Message != nil:
|
||||
params.ChatID = query.Message.Message.Chat.ID
|
||||
params.MessageID = query.Message.Message.ID
|
||||
case query.InlineMessageID != "":
|
||||
params.InlineMessageID = query.InlineMessageID
|
||||
default:
|
||||
return
|
||||
}
|
||||
if _, err := b.EditMessageText(ctx, params); err != nil {
|
||||
g.log.Warn("update provider selector failed", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,10 @@ type Gateway struct {
|
||||
// Supplied by the composition root, which owns config paths. Nil
|
||||
// restarts with the settings already in memory.
|
||||
Reload func(*Gateway) error
|
||||
// ReleaseAnnouncements sends one-time upgrade notes to authorized users.
|
||||
// It is supplied by the composition root because version, changelog, and
|
||||
// persistence paths are deployment concerns.
|
||||
ReleaseAnnouncements ReleaseAnnouncer
|
||||
|
||||
// restartCh carries /restart requests from a bot handler to the
|
||||
// supervisor loop in Start. Buffered so a handler never blocks.
|
||||
@@ -48,6 +52,14 @@ type Gateway struct {
|
||||
running bool
|
||||
}
|
||||
|
||||
type ReleaseAnnouncer interface {
|
||||
Announce(
|
||||
ctx context.Context,
|
||||
recipients []int64,
|
||||
send func(context.Context, int64, string) error,
|
||||
) error
|
||||
}
|
||||
|
||||
// New returns an unstarted Gateway. Call Start to begin webhook
|
||||
// processing.
|
||||
func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *slog.Logger) *Gateway {
|
||||
@@ -134,14 +146,16 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot,
|
||||
g.bot = b
|
||||
|
||||
// Gateway-local commands: handled directly, no LLM.
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypePrefix, g.statusHandler(router))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypePrefix, g.helpHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/restart", bot.MatchTypePrefix, g.restartHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypeExact, g.statusHandler(router))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, g.startHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypeExact, g.helpHandler())
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/restart", bot.MatchTypeExact, g.restartHandler())
|
||||
|
||||
// Publish the command list so Telegram renders a menu. Without this
|
||||
// the commands are undiscoverable and the LLM, having no idea they
|
||||
// exist, tells users there are none.
|
||||
g.registerCommands(ctx, b)
|
||||
g.announceRelease(ctx, b)
|
||||
|
||||
// Set up webhook or fall back to long polling.
|
||||
if g.WebhookURL != "" {
|
||||
@@ -181,6 +195,28 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot,
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (g *Gateway) announceRelease(ctx context.Context, b *bot.Bot) {
|
||||
if g.ReleaseAnnouncements == nil {
|
||||
return
|
||||
}
|
||||
err := g.ReleaseAnnouncements.Announce(
|
||||
ctx,
|
||||
slices.Clone(g.AllowedUserIDs),
|
||||
func(ctx context.Context, recipient int64, message string) error {
|
||||
_, err := b.SendMessage(ctx, &bot.SendMessageParams{
|
||||
ChatID: recipient,
|
||||
Text: message,
|
||||
})
|
||||
return err
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
// Notifications are ancillary to chat availability. Keep the gateway
|
||||
// running and let the announcer retry unrecorded recipients next time.
|
||||
g.log.Warn("release announcement failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Stop gracefully shuts down the bot and deletes the webhook.
|
||||
func (g *Gateway) Stop(ctx context.Context) error {
|
||||
if !g.running {
|
||||
@@ -243,14 +279,36 @@ func (g *Gateway) helpHandler() bot.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) startHandler() bot.HandlerFunc {
|
||||
return g.helpHandler()
|
||||
}
|
||||
|
||||
// ── default handler (non-command text → router) ─────────────
|
||||
|
||||
func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
if update.CallbackQuery != nil {
|
||||
switch {
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, providerCallbackPrefix):
|
||||
g.handleProviderCallback(ctx, b, update, router)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix):
|
||||
g.handleModelCallback(ctx, b, update, router)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok || msg.Text == "" {
|
||||
return
|
||||
}
|
||||
if isModelSelectorRequest(msg.Text) {
|
||||
g.sendModelSelector(ctx, b, msg, router)
|
||||
return
|
||||
}
|
||||
if isProviderSelectorRequest(msg.Text) {
|
||||
g.sendProviderSelector(ctx, b, msg, router)
|
||||
return
|
||||
}
|
||||
|
||||
// An LLM turn takes many seconds. Stream it into a draft so the
|
||||
// reply appears as it is written; the typing indicator covers the
|
||||
|
||||
@@ -74,9 +74,9 @@ func TestHelpDescribesPublishedCommandsAndChat(t *testing.T) {
|
||||
},
|
||||
})
|
||||
|
||||
for _, command := range gatewayCommands {
|
||||
if !strings.Contains(sentText, "/"+command.Command) {
|
||||
t.Errorf("help text does not describe published /%s command:\n%s", command.Command, sentText)
|
||||
for _, spec := range gatewayCommandSpecs {
|
||||
if !strings.Contains(sentText, "`"+spec.Usage+"`") {
|
||||
t.Errorf("help text does not contain exact usage %q:\n%s", spec.Usage, sentText)
|
||||
}
|
||||
}
|
||||
if strings.Contains(sentText, "not yet wired") {
|
||||
@@ -87,6 +87,99 @@ func TestHelpDescribesPublishedCommandsAndChat(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartHasDeterministicGatewayResponse(t *testing.T) {
|
||||
const allowedUserID = int64(42)
|
||||
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.startHandler()(context.Background(), b, &models.Update{
|
||||
Message: &models.Message{
|
||||
From: &models.User{ID: allowedUserID},
|
||||
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
|
||||
Text: "/start",
|
||||
},
|
||||
})
|
||||
|
||||
if len(*requests) == 0 {
|
||||
t.Fatal("/start sent no response")
|
||||
}
|
||||
found := false
|
||||
for _, request := range *requests {
|
||||
found = found || request.method == "sendRichMessage"
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("/start did not use deterministic gateway help response: %#v", *requests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishedCommandsMatchExecutableCommandSurface(t *testing.T) {
|
||||
executable := make(map[string]bool)
|
||||
for _, command := range gateway.LocalCommands() {
|
||||
executable[strings.TrimPrefix(command, "/")] = true
|
||||
}
|
||||
for _, command := range telegramOnlyCommands {
|
||||
executable[command] = true
|
||||
}
|
||||
|
||||
published := make(map[string]bool, len(gatewayCommandSpecs))
|
||||
for _, spec := range gatewayCommandSpecs {
|
||||
published[spec.Command] = true
|
||||
}
|
||||
|
||||
for command := range executable {
|
||||
if !published[command] {
|
||||
t.Errorf("executable /%s command is missing from the menu and help", command)
|
||||
}
|
||||
}
|
||||
for command := range published {
|
||||
if !executable[command] {
|
||||
t.Errorf("published /%s command has no executable implementation", command)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type releaseAnnouncerStub struct {
|
||||
recipients []int64
|
||||
message string
|
||||
}
|
||||
|
||||
func (s *releaseAnnouncerStub) Announce(
|
||||
ctx context.Context,
|
||||
recipients []int64,
|
||||
send func(context.Context, int64, string) error,
|
||||
) error {
|
||||
s.recipients = append([]int64(nil), recipients...)
|
||||
for _, recipient := range recipients {
|
||||
if err := send(ctx, recipient, s.message); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestReleaseAnnouncementTargetsAuthorizedUsers(t *testing.T) {
|
||||
const message = "Archie has just been updated to v0.2.0"
|
||||
announcer := &releaseAnnouncerStub{message: message}
|
||||
g := New("1:test", "", "", []int64{7, 8}, slog.Default())
|
||||
g.ReleaseAnnouncements = announcer
|
||||
b, requests := newTelegramTestBot(t)
|
||||
|
||||
g.announceRelease(context.Background(), b)
|
||||
|
||||
if len(announcer.recipients) != 2 || announcer.recipients[0] != 7 || announcer.recipients[1] != 8 {
|
||||
t.Fatalf("announcement recipients = %v, want authorized users [7 8]", announcer.recipients)
|
||||
}
|
||||
var sends int
|
||||
for _, request := range *requests {
|
||||
if request.method == "sendMessage" && request.form["text"] == message {
|
||||
sends++
|
||||
}
|
||||
}
|
||||
if sends != 2 {
|
||||
t.Fatalf("release announcement sends = %d, want 2; requests: %#v", sends, *requests)
|
||||
}
|
||||
}
|
||||
|
||||
// The allowlist must fail closed: a bot handle is public, so an unset
|
||||
// allowlist has to deny rather than admit everyone.
|
||||
func TestSenderAllowlistFailsClosed(t *testing.T) {
|
||||
|
||||
@@ -263,11 +263,12 @@ type MemoryConfig struct {
|
||||
|
||||
// MCPServer describes one MCP server connection.
|
||||
type MCPServer struct {
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Transport string `yaml:"transport" json:"transport"`
|
||||
Command string `yaml:"command" json:"command,omitempty"`
|
||||
Args []string `yaml:"args" json:"args,omitempty"`
|
||||
URL string `yaml:"url" json:"url,omitempty"`
|
||||
Name string `toml:"name" yaml:"name" json:"name"`
|
||||
Transport string `toml:"transport" yaml:"transport" json:"transport"`
|
||||
Command string `toml:"command" yaml:"command" json:"command,omitempty"`
|
||||
Args []string `toml:"args" yaml:"args" json:"args,omitempty"`
|
||||
WorkDir string `toml:"work_dir" yaml:"work_dir" json:"work_dir,omitempty"`
|
||||
URL string `toml:"url" yaml:"url" json:"url,omitempty"`
|
||||
}
|
||||
|
||||
// ToolPolicy holds tool execution limits.
|
||||
@@ -278,8 +279,8 @@ type ToolPolicy struct {
|
||||
|
||||
// ToolsConfig holds MCP server and tool policy configuration.
|
||||
type ToolsConfig struct {
|
||||
MCPServers []MCPServer `yaml:"mcp_servers" json:"mcp_servers"`
|
||||
Policy ToolPolicy `yaml:"tool_policy" json:"tool_policy"`
|
||||
MCPServers []MCPServer `toml:"mcp_servers" yaml:"mcp_servers" json:"mcp_servers"`
|
||||
Policy ToolPolicy `toml:"tool_policy" yaml:"tool_policy" json:"tool_policy"`
|
||||
}
|
||||
|
||||
// Config is the daemon configuration.
|
||||
@@ -470,6 +471,10 @@ type ContainerConfig struct {
|
||||
// collaboration PRD, phase C -- docs/prds/multi-agent-collaboration.md).
|
||||
// Empty (Telegram.Token.Key == "") disables chat entirely.
|
||||
type ChatConfig struct {
|
||||
// Models is the optional interactive-chat model catalog. When empty,
|
||||
// chat falls back to the distinct model references assigned to workflow
|
||||
// roles in the top-level [models] table.
|
||||
Models []string `toml:"models" yaml:"models"`
|
||||
// Email configures the inbound email gateway via SMTP.
|
||||
Email EmailConfig `toml:"email" yaml:"email"`
|
||||
// WebhookAddr is the host:port for the inbound webhook gateway.
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
@@ -46,6 +48,43 @@ func TestTaskConfigToConfigRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPServerTOMLIncludesClientWorkingDirectory(t *testing.T) {
|
||||
var cfg Config
|
||||
if _, err := toml.Decode(`
|
||||
[[tools.mcp_servers]]
|
||||
name = "desktop-commander"
|
||||
transport = "stdio"
|
||||
command = "npx"
|
||||
args = ["-y", "@wonderwhy-er/desktop-commander@0.2.46", "--no-onboarding"]
|
||||
work_dir = "/workspace"
|
||||
`, &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cfg.Tools.MCPServers) != 1 {
|
||||
t.Fatalf("MCPServers = %#v, want one server", cfg.Tools.MCPServers)
|
||||
}
|
||||
server := cfg.Tools.MCPServers[0]
|
||||
if server.Name != "desktop-commander" || server.Command != "npx" || server.WorkDir != "/workspace" {
|
||||
t.Fatalf("MCP server = %#v", server)
|
||||
}
|
||||
if len(server.Args) != 3 || server.Args[1] != "@wonderwhy-er/desktop-commander@0.2.46" {
|
||||
t.Fatalf("MCP args = %v", server.Args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelCatalogDecodesFromTOML(t *testing.T) {
|
||||
var cfg Config
|
||||
if _, err := toml.Decode(`
|
||||
[chat]
|
||||
models = ["openai/gpt-5.6-sol", "openrouter/openai/gpt-5.6-sol"]
|
||||
`, &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cfg.Chat.Models) != 2 || cfg.Chat.Models[1] != "openrouter/openai/gpt-5.6-sol" {
|
||||
t.Fatalf("chat models = %v", cfg.Chat.Models)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigForTaskJSONRoundTrip(t *testing.T) {
|
||||
cfg := Config{
|
||||
DiffCapLines: 321,
|
||||
|
||||
+47
-15
@@ -11,6 +11,7 @@ package gateway
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -79,6 +80,16 @@ type ModelManager interface {
|
||||
SetActiveModel(ctx context.Context, ref string) error
|
||||
}
|
||||
|
||||
// ProviderModelManager is the optional provider-aware extension used by
|
||||
// gateways that offer a provider selector before model selection.
|
||||
type ProviderModelManager interface {
|
||||
ModelManager
|
||||
Providers() []string
|
||||
ActiveProvider() string
|
||||
ModelsForProvider(provider string) []string
|
||||
SetActiveProvider(ctx context.Context, provider string) error
|
||||
}
|
||||
|
||||
// SpawnRequest is a chat-originated task creation request. Repo and
|
||||
// Workflow are optional -- empty means "the daemon's configured
|
||||
// default for this identity".
|
||||
@@ -167,6 +178,9 @@ func (r *Router) Route(ctx context.Context, msg Message) (string, error) {
|
||||
case "/cancel":
|
||||
return r.handleCancel(ctx, restAfter(text, cmd, r.gatewayName))
|
||||
default:
|
||||
if strings.HasPrefix(cmd, "/") {
|
||||
return fmt.Sprintf("Unknown command %s. Try /help.", cmd), nil
|
||||
}
|
||||
if r.LLM == nil {
|
||||
return "I'm running but LLM processing isn't wired yet. Try /status.", nil
|
||||
}
|
||||
@@ -189,23 +203,25 @@ func (r *Router) RouteStream(ctx context.Context, msg Message, onDelta func(stri
|
||||
return r.Route(ctx, msg)
|
||||
}
|
||||
cmd, _ := parseCmd(strings.TrimSpace(msg.Text), r.gatewayName)
|
||||
if isLocalCommand(cmd) {
|
||||
if isLocalCommand(cmd) || strings.HasPrefix(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)
|
||||
}
|
||||
|
||||
var localCommands = []string{"/status", "/models", "/model", "/spawn", "/approve", "/cancel"}
|
||||
|
||||
// LocalCommands returns the command names Route answers from local state.
|
||||
// Gateways use this to verify that their published command surfaces match
|
||||
// the executable router surface.
|
||||
func LocalCommands() []string {
|
||||
return slices.Clone(localCommands)
|
||||
}
|
||||
|
||||
// isLocalCommand reports whether cmd is answered from local state by
|
||||
// Route rather than handed to the LLM. Keep in sync with Route's switch.
|
||||
// Route rather than handed to the LLM.
|
||||
func isLocalCommand(cmd string) bool {
|
||||
switch cmd {
|
||||
case "/status", "/models", "/model", "/spawn", "/approve", "/cancel":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return slices.Contains(localCommands, cmd)
|
||||
}
|
||||
|
||||
// parseCmd extracts the command name from text, stripping an optional
|
||||
@@ -232,6 +248,9 @@ func (r *Router) handleModels(ctx context.Context) (string, error) {
|
||||
return "Model management is not configured.", nil
|
||||
}
|
||||
models := r.Models.Models()
|
||||
if manager, ok := r.Models.(ProviderModelManager); ok {
|
||||
models = manager.ModelsForProvider(manager.ActiveProvider())
|
||||
}
|
||||
if len(models) == 0 {
|
||||
return "No models configured.", nil
|
||||
}
|
||||
@@ -255,6 +274,9 @@ func (r *Router) handleModel(ctx context.Context, arg string) (string, error) {
|
||||
}
|
||||
if arg == "" {
|
||||
models := r.Models.Models()
|
||||
if manager, ok := r.Models.(ProviderModelManager); ok {
|
||||
models = manager.ModelsForProvider(manager.ActiveProvider())
|
||||
}
|
||||
if len(models) == 0 {
|
||||
return "No models configured.\nUsage: /model <provider/model>", nil
|
||||
}
|
||||
@@ -389,7 +411,7 @@ func (r *Router) handleStatus(ctx context.Context) (string, error) {
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("status: %w", err)
|
||||
}
|
||||
if len(counts) == 0 {
|
||||
if len(counts) == 0 && r.Models == nil {
|
||||
return "No tasks yet.", nil
|
||||
}
|
||||
statuses := make([]string, 0, len(counts))
|
||||
@@ -399,9 +421,19 @@ func (r *Router) handleStatus(ctx context.Context) (string, error) {
|
||||
sort.Strings(statuses)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("Task status:\n")
|
||||
for _, s := range statuses {
|
||||
fmt.Fprintf(&b, " %s: %d\n", s, counts[s])
|
||||
if len(statuses) == 0 {
|
||||
b.WriteString("No tasks yet.\n")
|
||||
} else {
|
||||
b.WriteString("Task status:\n")
|
||||
for _, s := range statuses {
|
||||
fmt.Fprintf(&b, " %s: %d\n", s, counts[s])
|
||||
}
|
||||
}
|
||||
return b.String(), nil
|
||||
if r.Models != nil {
|
||||
if manager, ok := r.Models.(ProviderModelManager); ok {
|
||||
fmt.Fprintf(&b, "\nProvider: %s\n", manager.ActiveProvider())
|
||||
}
|
||||
fmt.Fprintf(&b, "Model: %s\n", r.Models.ActiveModel())
|
||||
}
|
||||
return strings.TrimSpace(b.String()), nil
|
||||
}
|
||||
@@ -67,9 +67,7 @@ func TestRouteStreamDoesNotStreamLocalCommands(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
func TestRouteStreamRejectsUnknownCommandLocally(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "telegram")
|
||||
streamed := false
|
||||
r.LLMStream = func(context.Context, Message, func(string)) (string, error) {
|
||||
@@ -77,10 +75,14 @@ func TestRouteStreamStreamsUnknownCommand(t *testing.T) {
|
||||
return "ok", nil
|
||||
}
|
||||
|
||||
if _, err := r.RouteStream(context.Background(), Message{Text: "/commands"}, func(string) {}); err != nil {
|
||||
reply, err := r.RouteStream(context.Background(), Message{Text: "/commands"}, func(string) {})
|
||||
if err != nil {
|
||||
t.Fatalf("RouteStream: %v", err)
|
||||
}
|
||||
if !streamed {
|
||||
t.Error("unknown /commands should stream, since Route sends it to the LLM")
|
||||
if streamed {
|
||||
t.Error("unknown /commands must not reach the streaming responder")
|
||||
}
|
||||
if !strings.Contains(reply, "/help") {
|
||||
t.Fatalf("reply = %q, want /help guidance", reply)
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,25 @@ func TestRouteStatusWithTasks(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteStatusIncludesActiveProviderAndModel(t *testing.T) {
|
||||
manager := &fakeProviderModelManager{
|
||||
fakeModelManager: fakeModelManager{
|
||||
models: []string{"openai/gpt-5.6", "openrouter/openai/gpt-5.6"},
|
||||
activeModel: "openai/gpt-5.6",
|
||||
},
|
||||
}
|
||||
r := NewRouter(&fakeStore{counts: map[string]int{"running": 1}}, nil, "test")
|
||||
r.Models = manager
|
||||
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/status"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(reply, "Provider: openai") || !strings.Contains(reply, "Model: openai/gpt-5.6") {
|
||||
t.Fatalf("status missing active provider/model:\n%s", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteStatusAtMention(t *testing.T) {
|
||||
r := NewRouter(&fakeStore{counts: map[string]int{"running": 3}}, nil, "archie")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/status@archie"})
|
||||
@@ -85,13 +104,34 @@ func TestRouteNonCommandWithoutLLM(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRouterRejectsUnknownCommand(t *testing.T) {
|
||||
r := NewRouter(nil, nil, "test")
|
||||
reply, err := r.Route(context.Background(), Message{Text: "/frobnicate"})
|
||||
if err != nil {
|
||||
t.Fatalf("Route: %v", err)
|
||||
tests := []string{
|
||||
"/frobnicate",
|
||||
"/frobnicate with arguments",
|
||||
"/frobnicate@test with arguments",
|
||||
}
|
||||
if !strings.Contains(reply, "/status") {
|
||||
t.Errorf("reply = %q, want mention of /status", reply)
|
||||
for _, text := range tests {
|
||||
t.Run(text, func(t *testing.T) {
|
||||
llmCalls := 0
|
||||
r := NewRouter(nil, func(context.Context, Message) (string, error) {
|
||||
llmCalls++
|
||||
return "fabricated command behavior", nil
|
||||
}, "test")
|
||||
r.LLMStream = func(context.Context, Message, func(string)) (string, error) {
|
||||
llmCalls++
|
||||
return "fabricated streaming behavior", nil
|
||||
}
|
||||
|
||||
reply, err := r.RouteStream(context.Background(), Message{Text: text}, func(string) {})
|
||||
if err != nil {
|
||||
t.Fatalf("RouteStream: %v", err)
|
||||
}
|
||||
if llmCalls != 0 {
|
||||
t.Fatalf("unknown command invoked LLM %d times", llmCalls)
|
||||
}
|
||||
if !strings.Contains(reply, "/frobnicate") || !strings.Contains(reply, "/help") {
|
||||
t.Errorf("reply = %q, want unknown command and /help guidance", reply)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +143,38 @@ type fakeModelManager struct {
|
||||
setErr error
|
||||
}
|
||||
|
||||
type fakeProviderModelManager struct {
|
||||
fakeModelManager
|
||||
}
|
||||
|
||||
func (f *fakeProviderModelManager) Providers() []string {
|
||||
return []string{"openai", "openrouter"}
|
||||
}
|
||||
|
||||
func (f *fakeProviderModelManager) ActiveProvider() string {
|
||||
provider, _, _ := strings.Cut(f.activeModel, "/")
|
||||
return provider
|
||||
}
|
||||
|
||||
func (f *fakeProviderModelManager) ModelsForProvider(provider string) []string {
|
||||
var models []string
|
||||
for _, model := range f.models {
|
||||
if strings.HasPrefix(model, provider+"/") {
|
||||
models = append(models, model)
|
||||
}
|
||||
}
|
||||
return models
|
||||
}
|
||||
|
||||
func (f *fakeProviderModelManager) SetActiveProvider(_ context.Context, provider string) error {
|
||||
models := f.ModelsForProvider(provider)
|
||||
if len(models) == 0 {
|
||||
return fmt.Errorf("unknown provider: %s", provider)
|
||||
}
|
||||
f.activeModel = models[0]
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeModelManager) Models() []string {
|
||||
return f.models
|
||||
}
|
||||
@@ -142,6 +214,32 @@ func TestRouteModels(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteModelsFiltersActiveProvider(t *testing.T) {
|
||||
manager := &fakeProviderModelManager{
|
||||
fakeModelManager: fakeModelManager{
|
||||
models: []string{
|
||||
"openrouter/openai/gpt-5.6",
|
||||
"openai/gpt-5.6",
|
||||
"openai/o3",
|
||||
},
|
||||
activeModel: "openai/gpt-5.6",
|
||||
},
|
||||
}
|
||||
router := NewRouter(nil, nil, "test")
|
||||
router.Models = manager
|
||||
|
||||
reply, err := router.Route(context.Background(), Message{Text: "/models"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(reply, "openrouter/") {
|
||||
t.Fatalf("/models leaked another provider:\n%s", reply)
|
||||
}
|
||||
if !strings.Contains(reply, "openai/gpt-5.6") || !strings.Contains(reply, "openai/o3") {
|
||||
t.Fatalf("/models omitted active-provider models:\n%s", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteModelsWithActive(t *testing.T) {
|
||||
mgr := &fakeModelManager{
|
||||
models: []string{"a/b", "c/d"},
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
// Package releaseannounce turns versioned CHANGELOG sections into one-time
|
||||
// upgrade notifications.
|
||||
package releaseannounce
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Sender = func(ctx context.Context, recipient int64, message string) error
|
||||
|
||||
type Announcer struct {
|
||||
StatePath string
|
||||
Components []Component
|
||||
}
|
||||
|
||||
type Component struct {
|
||||
ID string
|
||||
Label string
|
||||
Version string
|
||||
ChangelogPath string
|
||||
}
|
||||
|
||||
func (a Announcer) Announce(ctx context.Context, recipients []int64, send Sender) error {
|
||||
if len(recipients) == 0 {
|
||||
return nil
|
||||
}
|
||||
hasReleasedComponent := false
|
||||
for _, component := range a.Components {
|
||||
if _, valid := parseReleaseVersion(component.Version); valid {
|
||||
hasReleasedComponent = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasReleasedComponent {
|
||||
return nil
|
||||
}
|
||||
if send == nil {
|
||||
return errors.New("release announcement sender is nil")
|
||||
}
|
||||
state, err := loadState(a.StatePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var errs []error
|
||||
for _, recipient := range recipients {
|
||||
recipientPrefix := strconv.FormatInt(recipient, 10) + ":"
|
||||
seenRecipient := false
|
||||
for _, component := range a.Components {
|
||||
if _, ok := state[recipientPrefix+component.ID]; ok {
|
||||
seenRecipient = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !seenRecipient {
|
||||
for _, component := range a.Components {
|
||||
if _, valid := parseReleaseVersion(component.Version); valid {
|
||||
state[recipientPrefix+component.ID] = component.Version
|
||||
}
|
||||
}
|
||||
if err := saveState(a.StatePath, state); err != nil {
|
||||
return fmt.Errorf("baseline components for recipient %d: %w", recipient, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
changed := make(map[string]bool, len(a.Components))
|
||||
stateChanged := false
|
||||
for _, component := range a.Components {
|
||||
current, validCurrent := parseReleaseVersion(component.Version)
|
||||
if !validCurrent {
|
||||
continue
|
||||
}
|
||||
key := recipientPrefix + component.ID
|
||||
previousText, seen := state[key]
|
||||
if !seen {
|
||||
state[key] = component.Version
|
||||
stateChanged = true
|
||||
continue
|
||||
}
|
||||
previous, validPrevious := parseReleaseVersion(previousText)
|
||||
if !validPrevious || compareVersions(current, previous) > 0 {
|
||||
changed[component.ID] = true
|
||||
}
|
||||
}
|
||||
if len(changed) == 0 {
|
||||
if stateChanged {
|
||||
if err := saveState(a.StatePath, state); err != nil {
|
||||
return fmt.Errorf("baseline new components for recipient %d: %w", recipient, err)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
message, err := a.componentMessage(changed)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := send(ctx, recipient, message); err != nil {
|
||||
errs = append(errs, fmt.Errorf("notify recipient %d: %w", recipient, err))
|
||||
continue
|
||||
}
|
||||
for _, component := range a.Components {
|
||||
if changed[component.ID] {
|
||||
state[recipientPrefix+component.ID] = component.Version
|
||||
}
|
||||
}
|
||||
if err := saveState(a.StatePath, state); err != nil {
|
||||
errs = append(errs, fmt.Errorf("record notification for recipient %d: %w", recipient, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (a Announcer) componentMessage(changed map[string]bool) (string, error) {
|
||||
var message strings.Builder
|
||||
message.WriteString("Archie has just been updated.")
|
||||
for _, component := range a.Components {
|
||||
fmt.Fprintf(&message, "\n\n--- %s ---\n\n", component.Label)
|
||||
if !changed[component.ID] {
|
||||
fmt.Fprintf(&message, "No %s changes as part of this release.", component.ID)
|
||||
continue
|
||||
}
|
||||
notes, err := changelogSection(component.ChangelogPath, component.Version)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s changelog: %w", component.ID, err)
|
||||
}
|
||||
fmt.Fprintf(&message, "%s installed - changes:\n\n%s", component.Version, notes)
|
||||
}
|
||||
return message.String(), nil
|
||||
}
|
||||
|
||||
type releaseVersion [3]uint64
|
||||
|
||||
func parseReleaseVersion(value string) (releaseVersion, bool) {
|
||||
if len(value) < len("v0.0.0") || value[0] != 'v' {
|
||||
return releaseVersion{}, false
|
||||
}
|
||||
parts := strings.Split(value[1:], ".")
|
||||
if len(parts) != 3 {
|
||||
return releaseVersion{}, false
|
||||
}
|
||||
var parsed releaseVersion
|
||||
for index, part := range parts {
|
||||
if part == "" || (len(part) > 1 && part[0] == '0') {
|
||||
return releaseVersion{}, false
|
||||
}
|
||||
number, err := strconv.ParseUint(part, 10, 64)
|
||||
if err != nil {
|
||||
return releaseVersion{}, false
|
||||
}
|
||||
parsed[index] = number
|
||||
}
|
||||
return parsed, true
|
||||
}
|
||||
|
||||
func compareVersions(left, right releaseVersion) int {
|
||||
for index := range left {
|
||||
switch {
|
||||
case left[index] < right[index]:
|
||||
return -1
|
||||
case left[index] > right[index]:
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func changelogSection(path, version string) (string, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open changelog: %w", err)
|
||||
}
|
||||
|
||||
headerPrefix := "## [" + version + "]"
|
||||
var lines []string
|
||||
found := false
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if !found {
|
||||
found = strings.HasPrefix(line, headerPrefix)
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, "## ") {
|
||||
break
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
_ = file.Close()
|
||||
return "", fmt.Errorf("read changelog: %w", err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
return "", fmt.Errorf("close changelog: %w", err)
|
||||
}
|
||||
notes := strings.TrimSpace(strings.Join(lines, "\n"))
|
||||
if !found || notes == "" {
|
||||
return "", fmt.Errorf("changelog has no notes for release %s", version)
|
||||
}
|
||||
return notes, nil
|
||||
}
|
||||
|
||||
func loadState(path string) (map[string]string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return make(map[string]string), nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read release announcement state: %w", err)
|
||||
}
|
||||
state := make(map[string]string)
|
||||
if err := json.Unmarshal(data, &state); err != nil {
|
||||
return nil, fmt.Errorf("decode release announcement state: %w", err)
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func saveState(path string, state map[string]string) error {
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return fmt.Errorf("create state directory: %w", err)
|
||||
}
|
||||
file, err := os.CreateTemp(dir, ".release-announcements-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temporary state: %w", err)
|
||||
}
|
||||
tempPath := file.Name()
|
||||
defer func() { _ = os.Remove(tempPath) }()
|
||||
|
||||
if err := file.Chmod(0o600); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("protect temporary state: %w", err)
|
||||
}
|
||||
if err := json.NewEncoder(file).Encode(state); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("encode release announcement state: %w", err)
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("sync release announcement state: %w", err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
return fmt.Errorf("close release announcement state: %w", err)
|
||||
}
|
||||
if err := os.Rename(tempPath, path); err != nil {
|
||||
return fmt.Errorf("replace release announcement state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package releaseannounce
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const testChangelog = `# Changelog
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
- feat: work in progress
|
||||
|
||||
## [v0.2.0] - 2026-07-27
|
||||
|
||||
- feat: improved the /help command
|
||||
- fix: model selection now affects live chat
|
||||
|
||||
## [v0.1.0] - 2026-07-20
|
||||
|
||||
- feat: initial release
|
||||
`
|
||||
|
||||
func TestAnnouncerBaselinesFirstReleaseWithoutSending(t *testing.T) {
|
||||
announcer := newTestAnnouncer(t, "v0.1.0")
|
||||
var sent []string
|
||||
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, func(_ context.Context, _ int64, message string) error {
|
||||
sent = append(sent, message)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("Announce() error = %v", err)
|
||||
}
|
||||
if len(sent) != 0 {
|
||||
t.Fatalf("first release sent %d messages, want baseline only", len(sent))
|
||||
}
|
||||
|
||||
announcer.Components[0].Version = "v0.2.0"
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, func(_ context.Context, _ int64, message string) error {
|
||||
sent = append(sent, message)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("Announce(upgrade) error = %v", err)
|
||||
}
|
||||
if len(sent) != 1 {
|
||||
t.Fatalf("upgrade sent %d messages, want 1", len(sent))
|
||||
}
|
||||
for _, want := range []string{
|
||||
"Archie has just been updated.",
|
||||
"--- THE GATEWAY ---",
|
||||
"v0.2.0 installed - changes:",
|
||||
"- feat: improved the /help command",
|
||||
"- fix: model selection now affects live chat",
|
||||
} {
|
||||
if !strings.Contains(sent[0], want) {
|
||||
t.Errorf("notification missing %q:\n%s", want, sent[0])
|
||||
}
|
||||
}
|
||||
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, func(context.Context, int64, string) error {
|
||||
t.Fatal("same version was announced twice")
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("Announce(restart) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnouncerSeparatesChangedAndUnchangedComponents(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
gatewayChangelog := filepath.Join(dir, "CHANGELOG.archied.md")
|
||||
runtimeChangelog := filepath.Join(dir, "CHANGELOG.archie.md")
|
||||
if err := os.WriteFile(gatewayChangelog, []byte(testChangelog), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(runtimeChangelog, []byte(testChangelog), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
announcer := Announcer{
|
||||
StatePath: filepath.Join(dir, "announced.json"),
|
||||
Components: []Component{
|
||||
{ID: "gateway", Label: "THE GATEWAY", Version: "v0.1.0", ChangelogPath: gatewayChangelog},
|
||||
{ID: "runtime", Label: "THE RUNTIME", Version: "v0.1.0", ChangelogPath: runtimeChangelog},
|
||||
},
|
||||
}
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, func(context.Context, int64, string) error {
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
announcer.Components[0].Version = "v0.2.0"
|
||||
var message string
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, func(_ context.Context, _ int64, text string) error {
|
||||
message = text
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"--- THE GATEWAY ---",
|
||||
"v0.2.0 installed - changes:",
|
||||
"- feat: improved the /help command",
|
||||
"--- THE RUNTIME ---",
|
||||
"No runtime changes as part of this release.",
|
||||
} {
|
||||
if !strings.Contains(message, want) {
|
||||
t.Errorf("component notification missing %q:\n%s", want, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnouncerTracksRecipientsIndependentlyAndRetriesFailures(t *testing.T) {
|
||||
announcer := newTestAnnouncer(t, "v0.1.0")
|
||||
if err := announcer.Announce(context.Background(), []int64{7, 8}, func(context.Context, int64, string) error {
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
announcer.Components[0].Version = "v0.2.0"
|
||||
|
||||
var attempts []int64
|
||||
send := func(_ context.Context, recipient int64, _ string) error {
|
||||
attempts = append(attempts, recipient)
|
||||
if recipient == 8 {
|
||||
return errors.New("telegram unavailable")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := announcer.Announce(context.Background(), []int64{7, 8}, send); err == nil {
|
||||
t.Fatal("Announce() error = nil, want delivery error")
|
||||
}
|
||||
|
||||
attempts = nil
|
||||
if err := announcer.Announce(context.Background(), []int64{7, 8}, func(_ context.Context, recipient int64, _ string) error {
|
||||
attempts = append(attempts, recipient)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("Announce(retry) error = %v", err)
|
||||
}
|
||||
if len(attempts) != 1 || attempts[0] != 8 {
|
||||
t.Fatalf("retry recipients = %v, want only failed recipient 8", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnouncerSkipsDevelopmentBuildsAndVersionRollbacks(t *testing.T) {
|
||||
announcer := newTestAnnouncer(t, "dev")
|
||||
calls := 0
|
||||
send := func(context.Context, int64, string) error {
|
||||
calls++
|
||||
return nil
|
||||
}
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, send); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(announcer.StatePath); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("development build created state: %v", err)
|
||||
}
|
||||
|
||||
announcer.Components[0].Version = "v0.2.0"
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, send); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
announcer.Components[0].Version = "v0.1.0"
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, send); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 0 {
|
||||
t.Fatalf("development/rollback sends = %d, want 0", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnouncerReportsMissingReleaseSectionWithoutAdvancingState(t *testing.T) {
|
||||
announcer := newTestAnnouncer(t, "v0.1.0")
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, func(context.Context, int64, string) error {
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
announcer.Components[0].Version = "v9.9.9"
|
||||
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, func(context.Context, int64, string) error {
|
||||
t.Fatal("missing changelog section must not send")
|
||||
return nil
|
||||
}); err == nil {
|
||||
t.Fatal("Announce() error = nil, want missing release section error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnouncerReportsStatePersistenceFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
changelog := filepath.Join(dir, "CHANGELOG.md")
|
||||
if err := os.WriteFile(changelog, []byte(testChangelog), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
notDirectory := filepath.Join(dir, "file")
|
||||
if err := os.WriteFile(notDirectory, []byte("occupied"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
announcer := Announcer{
|
||||
StatePath: filepath.Join(notDirectory, "announced.json"),
|
||||
Components: []Component{
|
||||
{ID: "gateway", Label: "THE GATEWAY", Version: "v0.1.0", ChangelogPath: changelog},
|
||||
},
|
||||
}
|
||||
|
||||
if err := announcer.Announce(context.Background(), []int64{7}, func(context.Context, int64, string) error {
|
||||
return nil
|
||||
}); err == nil {
|
||||
t.Fatal("Announce() error = nil, want state persistence error")
|
||||
}
|
||||
}
|
||||
|
||||
func newTestAnnouncer(t *testing.T, version string) Announcer {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
changelog := filepath.Join(dir, "CHANGELOG.md")
|
||||
if err := os.WriteFile(changelog, []byte(testChangelog), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return Announcer{
|
||||
StatePath: filepath.Join(dir, "announced.json"),
|
||||
Components: []Component{
|
||||
{ID: "gateway", Label: "THE GATEWAY", Version: version, ChangelogPath: changelog},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -2,47 +2,31 @@ package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// maxMessageSize is the maximum allowed MCP message body size (4 MB).
|
||||
const maxMessageSize = 4 * 1024 * 1024
|
||||
|
||||
// writeMessage frames raw data with Content-Length headers and writes it to w.
|
||||
//
|
||||
// The MCP stdio transport uses the same HTTP-like header framing as LSP:
|
||||
//
|
||||
// Content-Length: <length>\r\n
|
||||
// \r\n
|
||||
// <body>
|
||||
// writeMessage writes one newline-delimited JSON-RPC message. MCP stdio uses
|
||||
// one compact JSON object per line; Content-Length framing belongs to LSP and
|
||||
// is not understood by servers built with the official MCP SDKs.
|
||||
func writeMessage(w io.Writer, data []byte) error {
|
||||
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(data))
|
||||
_, err := io.WriteString(w, header)
|
||||
if err != nil {
|
||||
if _, err := w.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) > 0 {
|
||||
_, err = w.Write(data)
|
||||
}
|
||||
_, err := io.WriteString(w, "\n")
|
||||
return err
|
||||
}
|
||||
|
||||
// readMessage reads one Content-Length framed message from r and returns
|
||||
// the raw body bytes.
|
||||
// readMessage reads one newline-delimited JSON-RPC message from r and returns
|
||||
// the raw JSON bytes without its line ending.
|
||||
//
|
||||
// r must be a *bufio.Reader. Callers that hold a plain io.Reader should
|
||||
// wrap it once with bufio.NewReader and reuse that wrapper across
|
||||
// multiple readMessage calls -- creating a new bufio.Reader per call
|
||||
// silently drops buffered data and breaks multi-message streams.
|
||||
//
|
||||
// The function parses HTTP-like headers terminated by an empty line
|
||||
// (\r\n\r\n or \n\n), extracts Content-Length, and reads exactly that
|
||||
// many bytes of body. Other headers (e.g. Content-Type) are accepted
|
||||
// and ignored.
|
||||
func readMessage(r io.Reader) ([]byte, error) {
|
||||
br, ok := r.(*bufio.Reader)
|
||||
if !ok {
|
||||
@@ -55,54 +39,26 @@ func readMessage(r io.Reader) ([]byte, error) {
|
||||
}
|
||||
|
||||
func readMessageFromBufio(br *bufio.Reader) ([]byte, error) {
|
||||
var contentLength int
|
||||
contentLengthFound := false
|
||||
headerSectionEnd := false
|
||||
|
||||
message := make([]byte, 0, 4096)
|
||||
for {
|
||||
line, err := br.ReadString('\n')
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read header: %w", err)
|
||||
chunk, err := br.ReadSlice('\n')
|
||||
if len(message)+len(chunk) > maxMessageSize+1 {
|
||||
return nil, fmt.Errorf("message exceeds maximum %d bytes", maxMessageSize)
|
||||
}
|
||||
// Strip trailing \r\n or \n
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
|
||||
if line == "" {
|
||||
// End of headers.
|
||||
headerSectionEnd = true
|
||||
message = append(message, chunk...)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
|
||||
if strings.HasPrefix(line, "Content-Length:") {
|
||||
val := strings.TrimSpace(line[len("Content-Length:"):])
|
||||
n, err := strconv.Atoi(val)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid Content-Length value %q: %w", val, err)
|
||||
if err != bufio.ErrBufferFull {
|
||||
if err == io.EOF && len(message) > 0 {
|
||||
return nil, fmt.Errorf("read message: missing newline: %w", io.ErrUnexpectedEOF)
|
||||
}
|
||||
if n < 0 {
|
||||
return nil, fmt.Errorf("Content-Length %d is negative", n)
|
||||
}
|
||||
if n > maxMessageSize {
|
||||
return nil, fmt.Errorf("Content-Length %d exceeds maximum %d", n, maxMessageSize)
|
||||
}
|
||||
contentLength = n
|
||||
contentLengthFound = true
|
||||
}
|
||||
// Other headers (Content-Type, etc.) are ignored.
|
||||
}
|
||||
|
||||
if !headerSectionEnd {
|
||||
return nil, errors.New("missing empty line after headers")
|
||||
}
|
||||
if !contentLengthFound {
|
||||
return nil, errors.New("missing Content-Length header")
|
||||
}
|
||||
|
||||
body := make([]byte, contentLength)
|
||||
if contentLength > 0 {
|
||||
if _, err := io.ReadFull(br, body); err != nil {
|
||||
return nil, fmt.Errorf("read body: %w", err)
|
||||
return nil, fmt.Errorf("read message: %w", err)
|
||||
}
|
||||
}
|
||||
return body, nil
|
||||
message = message[:len(message)-1]
|
||||
if len(message) > 0 && message[len(message)-1] == '\r' {
|
||||
message = message[:len(message)-1]
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
@@ -32,6 +32,9 @@ type StdioTransportConfig struct {
|
||||
Command string
|
||||
// Args are passed to the server executable.
|
||||
Args []string
|
||||
// Dir is the subprocess working directory. Empty inherits the daemon's
|
||||
// working directory.
|
||||
Dir string
|
||||
// Env is additional environment variables in NAME=value format.
|
||||
// The subprocess inherits the parent process environment; these are added
|
||||
// on top of it.
|
||||
@@ -79,7 +82,7 @@ func (c StdioTransportConfig) effectiveShutdownGrace() time.Duration {
|
||||
|
||||
// StdioTransport manages an MCP server subprocess, sending JSON-RPC 2.0
|
||||
// messages to its stdin and receiving responses from its stdout. Messages
|
||||
// are framed with Content-Length headers.
|
||||
// use MCP's newline-delimited JSON framing.
|
||||
//
|
||||
// The transport supports automatic restart with exponential backoff when
|
||||
// the subprocess dies unexpectedly. Use [StdioTransport.Start] to begin,
|
||||
@@ -399,6 +402,7 @@ func (t *StdioTransport) commitSpawnedProcess(cmd *exec.Cmd, stdin io.WriteClose
|
||||
func (t *StdioTransport) spawnProcess() (*exec.Cmd, io.WriteCloser, *bufio.Reader, error) {
|
||||
cmd := exec.CommandContext(t.ctx, t.config.Command, t.config.Args...)
|
||||
cmd.Env = append(os.Environ(), t.config.Env...)
|
||||
cmd.Dir = t.config.Dir
|
||||
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
@@ -420,7 +424,7 @@ func (t *StdioTransport) spawnProcess() (*exec.Cmd, io.WriteCloser, *bufio.Reade
|
||||
return cmd, stdin, bufio.NewReader(stdout), nil
|
||||
}
|
||||
|
||||
// runReader loops reading Content-Length framed messages from the
|
||||
// runReader loops reading newline-delimited JSON messages from the
|
||||
// subprocess's stdout, routing responses to the matching pending
|
||||
// channels. On error (process crash, pipe close), it initiates the
|
||||
// auto-restart sequence.
|
||||
@@ -491,6 +495,7 @@ func (t *StdioTransport) handleProcessDeath() {
|
||||
|
||||
t.crashCount++
|
||||
t.state = StateStarting
|
||||
cmd := t.cmd
|
||||
t.cmd = nil
|
||||
t.stdin = nil
|
||||
|
||||
@@ -498,6 +503,10 @@ func (t *StdioTransport) handleProcessDeath() {
|
||||
t.failAllPendingLocked()
|
||||
t.mu.Unlock()
|
||||
|
||||
if cmd != nil {
|
||||
_ = cmd.Wait()
|
||||
}
|
||||
|
||||
// Attempt restart (outside lock because it waits).
|
||||
t.attemptRestart()
|
||||
}
|
||||
|
||||
@@ -103,10 +103,8 @@ func (s *testMCPServer) handle(msg Message) (*Message, error) {
|
||||
return s.echo(msg), nil
|
||||
|
||||
case "bad-framing":
|
||||
// Write malformed output (no Content-Length header, no newline) and
|
||||
// exit immediately. Without the exit, the client's reader would
|
||||
// block forever inside readMessage looking for a header terminator
|
||||
// that this payload never provides, hanging the test.
|
||||
// Write malformed output without MCP's required trailing newline and
|
||||
// exit immediately so the client observes an incomplete frame.
|
||||
_, _ = fmt.Fprint(os.Stdout, `{"jsonrpc":"2.0","id":1,"result":{}}`)
|
||||
syscall.Exit(0)
|
||||
return nil, nil
|
||||
@@ -117,9 +115,11 @@ func (s *testMCPServer) handle(msg Message) (*Message, error) {
|
||||
}
|
||||
|
||||
func (s *testMCPServer) echo(msg Message) *Message {
|
||||
cwd, _ := os.Getwd()
|
||||
result, _ := json.Marshal(map[string]any{
|
||||
"echoed": msg.Method,
|
||||
"notifications_received": notificationsReceived.Load(),
|
||||
"cwd": cwd,
|
||||
})
|
||||
return &Message{
|
||||
JSONRPC: "2.0",
|
||||
@@ -133,6 +133,36 @@ func (s *testMCPServer) echo(msg Message) *Message {
|
||||
// a notification itself gets no response to observe from the test side.
|
||||
var notificationsReceived atomic.Int64
|
||||
|
||||
func TestStdioTransportSetsSubprocessWorkingDirectory(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
tr := helperTransportWithConfig(t, "normal", StdioTransportConfig{
|
||||
Dir: workDir,
|
||||
InitialBackoff: 10 * time.Millisecond,
|
||||
MaxBackoff: 50 * time.Millisecond,
|
||||
MaxRetries: 2,
|
||||
})
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = tr.Stop(context.Background()) }()
|
||||
|
||||
response, err := tr.Send(context.Background(), []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var message struct {
|
||||
Result struct {
|
||||
CWD string `json:"cwd"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if err := json.Unmarshal(response, &message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if message.Result.CWD != workDir {
|
||||
t.Fatalf("MCP subprocess cwd = %q, want %q", message.Result.CWD, workDir)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Transport Tests ─────────────────────────────────────────────────────
|
||||
|
||||
// helperTransport creates a StdioTransport pointed at our test helper process.
|
||||
@@ -181,7 +211,7 @@ func TestWriteMessage(t *testing.T) {
|
||||
if err := writeMessage(&buf, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "Content-Length: 15\r\n\r\n{\"key\":\"value\"}"
|
||||
want := "{\"key\":\"value\"}\n"
|
||||
if got := buf.String(); got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
@@ -192,7 +222,7 @@ func TestWriteMessage(t *testing.T) {
|
||||
if err := writeMessage(&buf, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "Content-Length: 0\r\n\r\n"
|
||||
want := "\n"
|
||||
if got := buf.String(); got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
@@ -200,48 +230,40 @@ func TestWriteMessage(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestReadMessage(t *testing.T) {
|
||||
t.Run("reads body with content-length header", func(t *testing.T) {
|
||||
input := "Content-Length: 5\r\n\r\nhello"
|
||||
t.Run("reads newline-delimited JSON", func(t *testing.T) {
|
||||
input := "{\"ok\":true}\n"
|
||||
body, err := readMessage(strings.NewReader(input))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != "hello" {
|
||||
t.Errorf("got %q, want %q", string(body), "hello")
|
||||
if string(body) != `{"ok":true}` {
|
||||
t.Errorf("got %q, want JSON body", string(body))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ignores other headers", func(t *testing.T) {
|
||||
input := "Content-Type: application/json\r\nContent-Length: 3\r\n\r\nabc"
|
||||
t.Run("accepts CRLF line ending", func(t *testing.T) {
|
||||
input := "{\"ok\":true}\r\n"
|
||||
body, err := readMessage(strings.NewReader(input))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != "abc" {
|
||||
t.Errorf("got %q, want %q", string(body), "abc")
|
||||
if string(body) != `{"ok":true}` {
|
||||
t.Errorf("got %q, want JSON body", string(body))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing content-length header", func(t *testing.T) {
|
||||
_, err := readMessage(strings.NewReader("no-header\r\n\r\nbody"))
|
||||
t.Run("missing newline", func(t *testing.T) {
|
||||
_, err := readMessage(strings.NewReader(`{"ok":true}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing Content-Length")
|
||||
t.Fatal("expected error for incomplete newline-delimited message")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("negative content-length", func(t *testing.T) {
|
||||
input := "Content-Length: -1\r\n\r\n"
|
||||
t.Run("oversized message", func(t *testing.T) {
|
||||
input := strings.Repeat("x", maxMessageSize+1) + "\n"
|
||||
_, err := readMessage(strings.NewReader(input))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for negative Content-Length")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("oversized content-length", func(t *testing.T) {
|
||||
input := fmt.Sprintf("Content-Length: %d\r\n\r\n", maxMessageSize+1)
|
||||
_, err := readMessage(strings.NewReader(input))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for oversized Content-Length")
|
||||
t.Fatal("expected error for oversized message")
|
||||
}
|
||||
})
|
||||
|
||||
@@ -261,7 +283,7 @@ func TestReadMessage(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("truncated body returns error", func(t *testing.T) {
|
||||
input := "Content-Length: 10\r\n\r\nshort"
|
||||
input := `{"truncated":true}`
|
||||
_, err := readMessage(strings.NewReader(input))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for truncated body")
|
||||
@@ -786,7 +808,7 @@ func TestStdioTransportSendContextCancellationWhileWaiting(t *testing.T) {
|
||||
// TestStdioTransportBadFraming exercises the reader's malformed-framing
|
||||
// path against a real, live subprocess (rather than a synthetic
|
||||
// strings.Reader as in TestReadMessage): the server writes a response with
|
||||
// no Content-Length header, which readMessage cannot parse, so the reader
|
||||
// no trailing newline, which readMessage cannot parse, so the reader
|
||||
// goroutine treats the transport as dead and fails pending requests.
|
||||
func TestStdioTransportBadFraming(t *testing.T) {
|
||||
tr := helperTransportWithConfig(t, "bad-framing", StdioTransportConfig{
|
||||
@@ -855,8 +877,7 @@ func TestStdioTransportSendWriteFailureCleansPending(t *testing.T) {
|
||||
// ── Framing edge cases ──────────────────────────────────────────────────
|
||||
|
||||
func TestFramingCarriageReturnOnly(t *testing.T) {
|
||||
// Some servers might send \n without \r -- we should be lenient.
|
||||
input := "Content-Length: 4\n\nbody"
|
||||
input := "body\r\n"
|
||||
body, err := readMessage(strings.NewReader(input))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
@@ -867,7 +888,7 @@ func TestFramingCarriageReturnOnly(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFramingMultipleMessages(t *testing.T) {
|
||||
input := "Content-Length: 5\r\n\r\nhelloContent-Length: 3\r\n\r\nbye"
|
||||
input := "hello\nbye\n"
|
||||
br := bufio.NewReader(strings.NewReader(input))
|
||||
body1, err := readMessage(br)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
func TestDesktopCommanderClientCompatibility(t *testing.T) {
|
||||
if os.Getenv("ARCHIE_TEST_DESKTOP_COMMANDER") != "1" {
|
||||
t.Skip("set ARCHIE_TEST_DESKTOP_COMMANDER=1 to run the external MCP integration")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
transport := protocol.NewStdioTransport(protocol.StdioTransportConfig{
|
||||
Command: "npx",
|
||||
Args: []string{
|
||||
"-y",
|
||||
"@wonderwhy-er/desktop-commander@0.2.46",
|
||||
"--no-onboarding",
|
||||
},
|
||||
Dir: "../../..",
|
||||
})
|
||||
provider := New("desktop-commander", transport)
|
||||
if err := provider.Start(ctx); err != nil {
|
||||
t.Fatalf("start Desktop Commander through MCP client: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer stopCancel()
|
||||
if err := provider.Stop(stopCtx); err != nil {
|
||||
t.Errorf("stop Desktop Commander: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
entries, err := provider.Discover(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("discover Desktop Commander tools: %v", err)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
t.Fatal("Desktop Commander advertised no tools")
|
||||
}
|
||||
required := map[string]bool{
|
||||
"mcp.desktop_commander.start_process": false,
|
||||
"mcp.desktop_commander.interact_with_process": false,
|
||||
"mcp.desktop_commander.read_process_output": false,
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if _, ok := required[entry.Name]; ok {
|
||||
required[entry.Name] = true
|
||||
}
|
||||
}
|
||||
for name, found := range required {
|
||||
if !found {
|
||||
t.Errorf("Desktop Commander did not advertise required shell tool %q", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user