diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 3c4db4cdd..696a14f76 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -224,3 +224,4 @@ {"id":"int-9eb7bbde4ce8579fa6ff44b2b7c8837b","kind":"field_change","created_at":"2026-07-29T16:14:12.750427109Z","actor":"Sam Catlow","issue_id":"archie-core-rs9","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"text-based line patcher implemented in internal/infrastructure/configuration/tomlwrite; template embedded via configtemplate.go; tests pass, task check clean"}} {"id":"int-4b7430d2b3e135f65dd02e869735ddcb","kind":"field_change","created_at":"2026-07-29T16:19:14.81881455Z","actor":"Sam Catlow","issue_id":"archie-core-ifi","extra":{"field":"status","new_value":"closed","old_value":"open"}} {"id":"int-d72f7fa25fe6964e77322aefb6e51b92","kind":"field_change","created_at":"2026-07-29T16:19:22.842905807Z","actor":"Sam Catlow","issue_id":"archie-core-0d6","extra":{"field":"status","new_value":"closed","old_value":"open"}} +{"id":"int-708d599fdab7b76f04111619b278a3de","kind":"field_change","created_at":"2026-07-30T17:39:36.940566206Z","actor":"Sam Catlow","issue_id":"archie-core-v8x","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented SDK-backed provider discovery, unified Telegram model picker, safe catalog caching, and execution composition tests"}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 25ff49ec8..f00826cab 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -53,6 +53,7 @@ {"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"closed","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-28T17:04:41Z","closed_at":"2026-07-28T17:04:41Z","close_reason":"Superseded by merged work: all 32 children complete (32/32, bd flags it 'eligible for close'). MemoryProvider interface, built-in file-backed memory, MemoryManager, scrubber, drain and threat scanning all landed in internal/memory. Nothing left in scope.","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-v8x","title":"Unify Telegram provider and model selection around SDK catalog","description":"Replace the separate /provider and static configured-model surfaces with one /model provider-to-model wizard. Build the usable provider catalog from the local ai-sdk models.dev catalog plus environment credentials and explicit overrides, cache the filtered tool-capable catalog under the active config directory, and use the same resolved provider/model state across chat and execution paths. Remove the handwritten WellKnown table and remove external-framework references from the Archie tree.","acceptance_criteria":"/model first shows usable providers, then paginated tool-capable models, then atomically switches provider/model and reports model metadata and scope. /provider is absent from executable/menu/help surfaces. Catalog refresh is downloaded at daemon startup and cached beside configuration with safe cached fallback. Environment discovery and explicit overrides flow through chat, identities, subprocess and container/taskrun paths. Focused and composition tests cover discovery, pagination, callbacks and execution parity. A case-insensitive repository scan outside the explicit .references source tree finds no forbidden external-framework name.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-30T17:10:38Z","created_by":"Sam Catlow","updated_at":"2026-07-30T17:39:37Z","started_at":"2026-07-30T17:10:59Z","closed_at":"2026-07-30T17:39:37Z","close_reason":"Implemented SDK-backed provider discovery, unified Telegram model picker, safe catalog caching, and execution composition tests","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-ky6","title":"One optional MCP provider failing takes down the whole daemon","description":"internal/tools/provider/provider.go Start() is atomic by design -- 'Any failure rolls the complete family back' -- so a single failing provider unregisters every other provider including the builtins, capabilityHost.Start returns the error, and cmd/archied/main.go:655 exits 1. Under compose restart or systemd Restart=on-failure that is a crash loop. Observed 2026-07-30 on carina: mcp.desktop-commander could not start (missing unzip in the runtime image, fixed in 455fd6f) and archied restarted continuously, losing chat, the gateway and every builtin tool over one third-party npm package.\\n\\nAtomicity is correct for a provider the daemon requires. It is wrong for an external MCP server pulled from a registry at runtime, which is exactly the category that should be allowed to be absent -- the same reasoning applied to the forge in 518a1a0, where a missing credential now disables the capability rather than the daemon.","design":"Needs a required/optional distinction on the registration or manifest, which does not exist today. Keep the all-or-nothing path for required providers; the atomic batch semantics for tool visibility (tools appear only after Start and Discover both succeed) should hold per-provider either way. Relates to the plugin engine rule in ARCHITECTURE.md: failure isolation is explicitly the owning manager's responsibility.","acceptance_criteria":"A provider can be declared optional. An optional provider that fails to start or discover is logged, excluded from the running set, and does not roll back the family or stop the daemon. A required provider keeps today's atomic rollback. Provider health reflects the degraded state so the failure is visible rather than silent. Regression test starts a family containing one failing optional provider and asserts the other providers' tools remain registered and Start returns nil.","status":"open","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-30T06:49:26Z","created_by":"Sam Catlow","updated_at":"2026-07-30T06:49:26Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-qa4.5","title":"Phase 5: the 56 lint findings Phase 4 left behind","description":"Discovered as a side effect of the 6d4e0be audit (archie-core-ifi), not as its\ngoal: running golangci-lint over the two packages I had touched showed findings\nin files nobody had flagged, so I ran it repo-wide.\n\nAll four children of archie-core-qa4 are closed and the epic reports \"4/4\ncomplete (100%) -- eligible for close\", but `golangci-lint run ./...` still\nreports 56 issues. The epic must not be closed on that prompt; its own\ndescription says the gate is RED until it closes, so closing it early declares\na green gate that does not exist.\n\nBreakdown: noctx 11, gocognit 11, gocritic 6, errcheck 6, nilerr 4, recvcheck 3,\nnestif 3, godox 3, sloglint 2, predeclared 2, funlen 2, gofumpt 1, cyclop 1,\nstaticcheck 0 (the one hit, configtemplate.go:6, is fixed).\n\nThe gocognit remainder is concentrated in exactly the functions Phase 4 named as\ndeferred -- cmd/archied/main.go run (106, the description predicted \"108-\u003e30\nremaining\" and it did not land), internal/workflow AgentStage.Stage (68),\nFeasibility and TDD (funlen), cmd/archie-agent startMCPProviders (45) -- plus\nthe whole of internal/tools/builtin: grepFallback 58, runFindGoFallback 57,\nmakeReadExecutor 56, makeGrepExecutor 41, makeShellExecutor 40, makeWriteExecutor\n38, suggestPaths 36. tomlwrite.Apply (82) is new, uncommitted-until-7fab597 code.\n\nREAD archie-core-qa4's notes before starting. Both known behaviour regressions\nfrom this epic came out of structural extraction, and every remaining gocognit\nsite is a structural extraction waiting to happen. The nilerr findings in\ngrep.go are not noise either -- see archie-core-ts9, where the same swallow in\nfind.go is a live false-negative bug. Fixing nilerr by \"returning the error\"\nwithout deciding what the caller does with it will change tool behaviour.","acceptance_criteria":"golangci-lint run ./... reports 0 issues, or every remaining finding has an explicit nolint with a reason. Each structural extraction lands with a behavioural test for the function it splits, per the discipline recorded in archie-core-qa4's notes.","status":"open","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:26:57Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:26:57Z","dependencies":[{"issue_id":"archie-core-qa4.5","depends_on_id":"archie-core-qa4","type":"parent-child","created_at":"2026-07-30T02:26:57Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-qa4.5","depends_on_id":"archie-core-ts9","type":"blocks","created_at":"2026-07-30T02:27:02Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-qa4.5","depends_on_id":"archie-core-ifi","type":"discovered-from","created_at":"2026-07-30T02:26:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-0d6","title":"[BUG] /model \u003cname\u003e asked the router for a doubled model name","description":"The nestif extraction in 651de0a pulled --provider parsing out of parseModelRest into extractProviderFlag, which took the modelParts slice by pointer and appended every non-provider field to it. The caller's own loop then appended the same fields again, so every field of the model name was duplicated: '/model gpt-5.6' resolved to 'gpt-5.6 gpt-5.6' and SetActiveModel rejected it as an unknown model. '/model gpt-5.6 --provider openai' was worse -- the space-separated provider value was no longer consumed with its flag, giving 'gpt-5.6 gpt-5.6 openai'. Direct model switching over Telegram was broken for anything but a bare --refresh or a provider-only switch. Found while auditing 6d4e0be for archie-core-ifi: the naked return in the same function could not be regression-tested until the function produced correct values.","design":"Two ways to fix the double append were available. Rejected: keep the helper\nsignature and delete the caller's default-branch append. That restores correct\noutput but leaves the shape intact -- a helper holding a pointer to the\ncaller's accumulator, with two loops over the same fields -- so the next person\nwho adds a field type has the same trap waiting. It also does not fix the\nspace-separated provider value, because the helper returns early on the first\n--provider and never sees the fields after it.\n\nChosen: splitProviderFlag returns (provider, remaining) and is the sole\naccumulator. One loop owns the fields, and there is no shared slice to append\nto twice. The index loop is kept deliberately -- i++ after reading a\nspace-separated value is what removes it with its flag, and converting that to\na range loop is precisely what 651de0a did wrong.\n\nLast --provider wins if repeated, matching the pre-651de0a behaviour rather\nthan the buggy helper's first-wins. Not worth a flag: /model does not document\nrepeating it.","acceptance_criteria":"parseModelRest returns the model name exactly once for bare names, scope flags, and both --provider spellings, with a regression test asserting field count rather than string equality.","notes":"Fixed by making splitProviderFlag the sole accumulator of surviving fields and returning them, so the shared-slice shape that allowed the double append is structurally impossible. Tests: TestParseModelRestDoesNotDoubleTheModelName, TestParseModelRestReturnsDeclaredValuesInOrder.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:18:46Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:26:09Z","closed_at":"2026-07-29T16:19:23Z","dependencies":[{"issue_id":"archie-core-0d6","depends_on_id":"archie-core-ifi","type":"discovered-from","created_at":"2026-07-30T02:18:46Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/cmd/archied/chat_models.go b/cmd/archied/chat_models.go index 72386c4e7..cd7c0fa4f 100644 --- a/cmd/archied/chat_models.go +++ b/cmd/archied/chat_models.go @@ -6,15 +6,20 @@ import ( "slices" "strings" "sync" + + "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" ) // 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 + mu sync.RWMutex + models []string + active string + details map[string]gateway.ModelDetails + providerNames map[string]string } func newChatModelManager(configured map[string]string, catalogs ...[]string) *chatModelManager { @@ -44,7 +49,42 @@ func newChatModelManager(configured map[string]string, catalogs ...[]string) *ch if active == "" { active = strings.TrimSpace(configured["builder"]) } - return &chatModelManager{models: models, active: active} + return &chatModelManager{ + models: models, active: active, + details: make(map[string]gateway.ModelDetails), + providerNames: make(map[string]string), + } +} + +func (m *chatModelManager) ApplyModelCatalog(snapshot modelcatalog.Snapshot) { + m.mu.Lock() + defer m.mu.Unlock() + for _, provider := range snapshot.Providers { + m.providerNames[provider.ID] = provider.Name + for _, model := range provider.Models { + ref := provider.ID + "/" + model.ID + m.details[ref] = gateway.ModelDetails{ + Ref: ref, Name: model.Name, + ContextWindow: model.ContextWindow, MaxOutputTokens: model.MaxOutputTokens, + Reasoning: model.Reasoning, Tools: true, + Attachment: model.Attachment, Structured: model.Structured, + InputModalities: slices.Clone(model.InputModalities), + } + } + } +} + +func (m *chatModelManager) ProviderDisplayName(provider string) string { + m.mu.RLock() + defer m.mu.RUnlock() + return m.providerNames[provider] +} + +func (m *chatModelManager) ModelDetails(ref string) (gateway.ModelDetails, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + details, ok := m.details[ref] + return details, ok } func (m *chatModelManager) Models() []string { diff --git a/cmd/archied/main.go b/cmd/archied/main.go index ce454ee78..29c9dc664 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -37,6 +37,7 @@ import ( "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" + "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" "github.com/samcharles93/archie-core/internal/memory" "github.com/samcharles93/archie-core/internal/memory/builtin" "github.com/samcharles93/archie-core/internal/nell" @@ -251,6 +252,19 @@ func run() int { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() + catalog, err := modelcatalog.Load(ctx, modelcatalog.Options{ + CachePath: filepath.Join(filepath.Dir(*cfgPath), "models.json"), + Getenv: os.Getenv, + Configured: cfg.Providers, + }) + var catalogModels []string + if err != nil { + log.Warn("model catalog unavailable; using configured providers and models", "err", err) + } else { + catalogModels = applyModelCatalog(&cfg, catalog) + log.Info("model catalog loaded", "providers", len(catalog.Providers), "models", len(catalogModels)) + } + // Observability: every event is logged to SQLite (stamped with its // row id) and then fanned out to live dashboard connections. bus := events.NewBus() @@ -343,7 +357,8 @@ func run() int { providers := executionProviders(cfg) llm := agentexec.NewRuntime(providers) toolReg := tools.NewRegistry() - chatModels := newChatModelManager(cfg.Models, cfg.Chat.Models) + chatModels := newChatModelManager(cfg.Models, cfg.Chat.Models, catalogModels) + chatModels.ApplyModelCatalog(catalog) // ── Persona registry ───────────────────────────────────────────── personas := gateway.NewPersonaRegistry(gateway.DefaultPersonas()) diff --git a/cmd/archied/model_catalog.go b/cmd/archied/model_catalog.go new file mode 100644 index 000000000..edf795345 --- /dev/null +++ b/cmd/archied/model_catalog.go @@ -0,0 +1,47 @@ +package main + +import ( + "maps" + "slices" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" +) + +func applyModelCatalog(cfg *config.Config, snapshot modelcatalog.Snapshot) []string { + discovered := make(map[string]config.Provider, len(snapshot.Providers)) + var models []string + for _, provider := range snapshot.Providers { + discovered[provider.ID] = config.Provider{ + Class: provider.Class, APIKeyEnv: provider.APIKeyEnv, BaseURL: provider.BaseURL, + } + for _, model := range provider.Models { + models = append(models, provider.ID+"/"+model.ID) + } + } + cfg.Providers = mergeProviders(discovered, cfg.Providers) + for i := range cfg.Identities { + cfg.Identities[i].Providers = mergeProviders(discovered, cfg.Identities[i].Providers) + } + slices.Sort(models) + return models +} + +func mergeProviders(base, overrides map[string]config.Provider) map[string]config.Provider { + merged := make(map[string]config.Provider, len(base)+len(overrides)) + maps.Copy(merged, base) + for id, override := range overrides { + resolved := merged[id] + if override.Class != "" { + resolved.Class = override.Class + } + if override.APIKeyEnv != "" { + resolved.APIKeyEnv = override.APIKeyEnv + } + if override.BaseURL != "" { + resolved.BaseURL = override.BaseURL + } + merged[id] = resolved + } + return merged +} diff --git a/cmd/archied/model_catalog_test.go b/cmd/archied/model_catalog_test.go new file mode 100644 index 000000000..4c5b43006 --- /dev/null +++ b/cmd/archied/model_catalog_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "reflect" + "testing" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" +) + +func TestApplyModelCatalogNormalizesEveryExecutionScope(t *testing.T) { + cfg := config.Config{ + Providers: map[string]config.Provider{ + "openai": {Class: "custom", APIKeyEnv: "CUSTOM_KEY"}, + }, + Identities: []config.IdentityConfig{ + {Name: "one", Providers: map[string]config.Provider{ + "identity-only": {Class: "openai-compatible"}, + }}, + }, + } + snapshot := modelcatalog.Snapshot{Providers: []modelcatalog.Provider{ + { + ID: "openai", Class: "openai", APIKeyEnv: "OPENAI_API_KEY", + BaseURL: "https://api.openai.test/v1", + Models: []modelcatalog.Model{{ID: "gpt-tool"}}, + }, + { + ID: "anthropic", Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY", + Models: []modelcatalog.Model{{ID: "claude-tool"}}, + }, + }} + + models := applyModelCatalog(&cfg, snapshot) + + if got := cfg.Providers["openai"]; got.Class != "custom" || got.APIKeyEnv != "CUSTOM_KEY" { + t.Fatalf("explicit global provider was overwritten: %#v", got) + } + if _, ok := cfg.Providers["anthropic"]; !ok { + t.Fatal("discovered provider missing from global execution config") + } + if _, ok := cfg.Identities[0].Providers["anthropic"]; !ok { + t.Fatal("discovered provider missing from identity execution config") + } + if _, ok := cfg.Identities[0].Providers["identity-only"]; !ok { + t.Fatal("explicit identity provider was removed") + } + wantModels := []string{"anthropic/claude-tool", "openai/gpt-tool"} + if !reflect.DeepEqual(models, wantModels) { + t.Fatalf("models = %v, want %v", models, wantModels) + } +} diff --git a/docs/archive/archie-core-architecture.md b/docs/archive/archie-core-architecture.md index 39160330b..255a4d58f 100644 --- a/docs/archive/archie-core-architecture.md +++ b/docs/archive/archie-core-architecture.md @@ -1,6 +1,6 @@ # archie-core v2 Architecture -- Design Document -**Author:** Archie (Hermes agent) +**Author:** Archie **Date:** 2026-07-21 (implementation status updated 2026-07-22) **Status:** Final (substantially implemented -- remaining aspirational items are pluggable storage backends and Layer 2 daemon plugin loader) diff --git a/docs/archive/archie-core-skills-prd-v2.md b/docs/archive/archie-core-skills-prd-v2.md index 3eb30ca4a..668eff533 100644 --- a/docs/archive/archie-core-skills-prd-v2.md +++ b/docs/archive/archie-core-skills-prd-v2.md @@ -1,6 +1,6 @@ # archie-core Skills System -- PRD -**Author:** Archie (Hermes agent) +**Author:** Archie **Date:** 2026-07-18 **Status:** Draft @@ -323,7 +323,7 @@ metadata: ## 6. Comparison: archie-core vs existing systems -| | archie-core | Claude Code | Codex CLI | GitHub Actions | Hermes Agent | +| | archie-core | Claude Code | Codex CLI | GitHub Actions | External Agent | |---|---|---|---|---|---| | **How it receives work** | GitHub issue assignment, Linear label, webhook | Chat, slash commands | Chat, slash commands | YAML triggers (push, PR, schedule) | Chat, cron, webhooks | | **What it does** | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Run arbitrary shell commands | Analyse → implement → gate → PR | @@ -331,7 +331,7 @@ metadata: | **Gates** | Named checkpoints in archie.yaml | Ad-hoc (CLAUDE.md + lint) | Ad-hoc | Steps in jobs | Skills with gates | | **Engine pluggable** | Yes | No (fixed to Claude) | No (fixed to Codex) | No (fixed to GitHub) | Yes (provider config) | | **Worktree isolation** | Yes | Yes (`--worktree`) | No | No (ephemeral runner) | No | -| **Blueprint/cron** | Export to Hermes | No | No | Schedule trigger | Native | +| **Blueprint/cron** | Export externally | No | No | Schedule trigger | Native | | **Where it runs** | Docker sandbox | Host | Host or sandbox | GitHub runner | Host, Docker, Modal, SSH | --- @@ -361,7 +361,7 @@ metadata: - Gate overrides per skill - Skill templates for project scaffolding (`archie init --skill go-service`) - Remote skill libraries (git repos as skill sources) -- Blueprint export to Hermes cron +- Blueprint export to an external scheduler ### Phase 5: Additional interfaces - Linear webhook integration diff --git a/docs/archive/archie-core-skills-prd.md b/docs/archive/archie-core-skills-prd.md index 09a99b12f..7dc463177 100644 --- a/docs/archive/archie-core-skills-prd.md +++ b/docs/archive/archie-core-skills-prd.md @@ -1,6 +1,6 @@ # archie-core Workflows & Skills -- Product Requirements Document -**Author:** Archie (Hermes agent) +**Author:** Archie **Date:** 2026-07-18 **Status:** Draft @@ -323,9 +323,9 @@ skill-name/ `archie init --skill go-service` scaffolds a new project with the go-service skill's templates applied. -### 4.5 Blueprint export (Hermes cron integration) +### 4.5 Blueprint export (external cron integration) -Following the Hermes Automation Blueprints model, any archie-core workflow can be exported as a Hermes blueprint: +Any archie-core workflow can be exported as an automation blueprint: ```yaml metadata: @@ -336,20 +336,20 @@ metadata: name: "CI monitor" ``` -The export produces a `SKILL.md` with `metadata.hermes.blueprint` that Hermes can schedule. The blueprint's prompt is the archie workflow's quality pipeline. +The export produces a `SKILL.md` with scheduler metadata. The blueprint's prompt is the archie workflow's quality pipeline. --- ## 5. Comparison to Existing Systems -| Feature | archie-core | GitHub Actions | Dagger | Taskfile | devcontainer | Hermes Skills | +| Feature | archie-core | GitHub Actions | Dagger | Taskfile | devcontainer | External Skills | |---|---|---|---|---|---|---| | Language | YAML | YAML | Go/Python/TS | YAML | JSON | Markdown | | Gates | Named + composable | Steps in jobs | Functions | Tasks | Lifecycle scripts | N/A | | Engine abstraction | First-class | GitHub only | Dagger Engine | Shell only | None | Provider | | Skills | agentskills.io spec | Composite actions | Dagger Modules | Includes | Features | SKILL.md | | Worktree isolation | Built-in | No | Containers | No | Container | No | -| Blueprint export | To Hermes cron | No | No | No | No | Native | +| Blueprint export | To external cron | No | No | No | No | Native | | Multi-engine fallback | Yes (ordered list) | No | No | No | No | Provider config | | Progressive disclosure | Yes (skill spec) | No | No | No | Feature metadata | Yes | @@ -390,6 +390,6 @@ The export produces a `SKILL.md` with `metadata.hermes.blueprint` that Hermes ca ## 7. Open Questions 1. **Skill registry hosting:** Self-hosted on git.catlow.cloud, or use agentskills.io? -2. **Hermes integration:** Should archie-core be a Hermes tool, a Hermes skill, or standalone? +2. **External integration:** Should archie-core be exposed as a tool, a skill, or standalone? 3. **Budget enforcement:** Per-skill budget vs. per-workflow budget vs. monthly cap? 4. **Sandbox image building:** Pre-built images vs. Dockerfile in each skill? diff --git a/docs/archive/decisions.md b/docs/archive/decisions.md index b746ab0fe..0726b7a98 100644 --- a/docs/archive/decisions.md +++ b/docs/archive/decisions.md @@ -55,7 +55,7 @@ actual per-workflow/per-repo metrics. **Reasoning**: An agent killed mid-task at 1M tokens wastes every token it already consumed. There is no compaction or checkpointing yet, so a -killed agent is a total loss. Hermes regularly uses 160+ steps and +killed agent is a total loss. Long-running agents regularly use 160+ steps and hundreds of thousands of tokens per request. Large repositories need proportionally more. @@ -189,4 +189,4 @@ must be in the PATH before starting the daemon. **Symptom**: `baseline red -- gofumpt -w . fails` but manual run passes. Root cause: `which gofumpt` returns nothing because `~/go/bin` isn't on -PATH in Hermes sessions. +PATH in external agent sessions. diff --git a/docs/archive/prds/multi-agent-collaboration.md b/docs/archive/prds/multi-agent-collaboration.md index 10e200761..5142abcd9 100644 --- a/docs/archive/prds/multi-agent-collaboration.md +++ b/docs/archive/prds/multi-agent-collaboration.md @@ -18,7 +18,7 @@ not just identity. `Config.BotUser` is a single global field, so one process = one identity today. The goal stated for archie-core overall is to become a fully extensible -agentic workhorse -- comparable to and improving on OpenClaw/Hermes. This PRD +agentic workhorse. This PRD scopes the "multi-agent" slice of that: what it takes to go from N processes to one daemon that can do what N processes do, plus the surrounding capabilities (chat channels, plugins, memory) needed to reach that bar. diff --git a/docs/archive/prds/typescript-plugin-engine.md b/docs/archive/prds/typescript-plugin-engine.md index f2b9282e9..006d06413 100644 --- a/docs/archive/prds/typescript-plugin-engine.md +++ b/docs/archive/prds/typescript-plugin-engine.md @@ -1,6 +1,6 @@ # archie-core TypeScript Plugin Engine -- PRD -**Author:** Archie (Hermes agent) +**Author:** Archie **Date:** 2026-07-21 **Status:** Draft diff --git a/docs/archive/prds/yaegi-plugin-system.md b/docs/archive/prds/yaegi-plugin-system.md index 37899591a..66c378741 100644 --- a/docs/archive/prds/yaegi-plugin-system.md +++ b/docs/archive/prds/yaegi-plugin-system.md @@ -1,6 +1,6 @@ # archie-core Yaegi Plugin System -- PRD -**Author:** Archie (Hermes agent) +**Author:** Archie **Date:** 2026-07-21 **Status:** Draft diff --git a/go.mod b/go.mod index 380f91186..b3002245a 100644 --- a/go.mod +++ b/go.mod @@ -75,7 +75,7 @@ require ( github.com/nats-io/nats-server/v2 v2.14.3 github.com/nats-io/nats.go v1.52.0 github.com/samcharles93/NellDB v0.2.5 - github.com/samcharles93/ai-sdk v0.1.18 + github.com/samcharles93/ai-sdk v0.1.19 github.com/traefik/yaegi v0.16.1 gopkg.in/yaml.v3 v3.0.1 ) diff --git a/go.sum b/go.sum index 2f7cfb106..b00d53a31 100644 --- a/go.sum +++ b/go.sum @@ -150,6 +150,8 @@ github.com/samcharles93/NellDB v0.2.5 h1:VEasjyB4opTFAfWnV3s9TEHkfA41ee+7gYD8LqK github.com/samcharles93/NellDB v0.2.5/go.mod h1:vyfd6/T2Cp5U0acoh2LrebJteZqoFObedDZTxP0j4W0= github.com/samcharles93/ai-sdk v0.1.18 h1:Jvz2OSnzJ68XCAiTHdLKKvgoNI/rKrNw9LJ7jbZs55c= github.com/samcharles93/ai-sdk v0.1.18/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= +github.com/samcharles93/ai-sdk v0.1.19 h1:j/F4pRx9CEjsZmW41FLaM48P+1WRitMLLTqnvlJuBLI= +github.com/samcharles93/ai-sdk v0.1.19/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go index 29711f644..cdb86ddfe 100644 --- a/internal/channels/telegram/commands.go +++ b/internal/channels/telegram/commands.go @@ -22,8 +22,7 @@ var gatewayCommandSpecs = []commandSpec{ {Command: "status", Description: "Show task counts by state", Usage: "/status"}, {Command: "version", Description: "Show installed Archie versions", Usage: "/version"}, {Command: "update", Description: "Check for Archie updates", Usage: "/update"}, - {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: "model", Description: "Choose a provider and model or switch directly", Usage: "/model [provider/model]"}, {Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] "}, {Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"}, {Command: "new", Description: "Start a fresh session, clearing conversation history", Usage: "/new [title]"}, @@ -47,7 +46,7 @@ var gatewayCommandSpecs = []commandSpec{ {Command: "help", Description: "See what Archie can do", Usage: "/help"}, } -var telegramOnlyCommands = []string{"provider", "restart", "help", "version", "update", "rollback", "stop"} +var telegramOnlyCommands = []string{"restart", "help", "version", "update", "rollback", "stop"} var gatewayCommands = func() []models.BotCommand { commands := make([]models.BotCommand, 0, len(gatewayCommandSpecs)) diff --git a/internal/channels/telegram/model.go b/internal/channels/telegram/model.go index 699cb35a5..aad6e6854 100644 --- a/internal/channels/telegram/model.go +++ b/internal/channels/telegram/model.go @@ -12,7 +12,19 @@ import ( "github.com/samcharles93/archie-core/internal/gateway" ) -const modelCallbackPrefix = "model:" +const ( + modelCallbackPrefix = "model:" + modelPageCallbackPrefix = "modelpage:" + modelBackCallback = "modelback" + modelCancelCallback = "modelcancel" + modelNoopCallback = "modelnoop" + modelPageSize = 8 +) + +type modelPage struct { + Provider string + Page int +} func isModelSelectorRequest(text string) bool { fields := strings.Fields(text) @@ -140,10 +152,10 @@ func (g *Gateway) handleModelCommand( return } - // --provider with a model: set provider, then model. + // A provider-qualified direct selection is one atomic model mutation. if provider != "" && model != "" { - if manager, ok := router.Models.(gateway.ProviderModelManager); ok { - _ = manager.SetActiveProvider(ctx, provider) + if !strings.HasPrefix(model, provider+"/") { + model = provider + "/" + model } } @@ -233,27 +245,94 @@ func modelSelectorText(active string) string { "\nActive: " + modelDisplayName(active, provider) } +func modelSelectorTextForProvider(provider string, page, count int) string { + start, end := pageBounds(page, count) + return fmt.Sprintf("⚙ Model Configuration\n\nProvider: %s (%d–%d of %d)\nSelect a model:", + providerDisplayName(provider), start+1, end, count) +} + func (g *Gateway) modelSelectorKeyboard(manager gateway.ModelManager) *models.InlineKeyboardMarkup { - active := manager.ActiveModel() - available := selectableModels(manager) - activeProvider := "" + provider := "" if providerManager, ok := manager.(gateway.ProviderModelManager); ok { - activeProvider = providerManager.ActiveProvider() + provider = providerManager.ActiveProvider() } - rows := make([][]models.InlineKeyboardButton, 0, len(available)) - for _, model := range available { - label := modelDisplayName(model, activeProvider) + return g.modelSelectorKeyboardForProvider(manager, provider) +} + +func (g *Gateway) modelSelectorKeyboardForProvider(manager gateway.ModelManager, provider string) *models.InlineKeyboardMarkup { + return g.modelSelectorKeyboardPage(manager, provider, 0) +} + +func (g *Gateway) modelSelectorKeyboardPage(manager gateway.ModelManager, provider string, page int) *models.InlineKeyboardMarkup { + active := manager.ActiveModel() + available := manager.Models() + if providerManager, ok := manager.(gateway.ProviderModelManager); ok { + available = providerManager.ModelsForProvider(provider) + } + start, end := pageBounds(page, len(available)) + buttons := make([]models.InlineKeyboardButton, 0, end-start) + for _, model := range available[start:end] { + label := modelDisplayName(model, provider) if model == active { label = "✓ " + label } - rows = append(rows, []models.InlineKeyboardButton{{ + buttons = append(buttons, models.InlineKeyboardButton{ Text: label, CallbackData: g.modelCallbackToken(model), - }}) + }) } + rows := make([][]models.InlineKeyboardButton, 0, (len(buttons)+1)/2+2) + for i := 0; i < len(buttons); i += 2 { + rows = append(rows, buttons[i:min(i+2, len(buttons))]) + } + pages := max(1, (len(available)+modelPageSize-1)/modelPageSize) + if pages > 1 { + var nav []models.InlineKeyboardButton + if page > 0 { + nav = append(nav, models.InlineKeyboardButton{ + Text: "◀ Prev", CallbackData: g.modelPageCallbackToken(provider, page-1), + }) + } + nav = append(nav, models.InlineKeyboardButton{ + Text: fmt.Sprintf("%d/%d", page+1, pages), CallbackData: modelNoopCallback, + }) + if page+1 < pages { + nav = append(nav, models.InlineKeyboardButton{ + Text: "Next ▶", CallbackData: g.modelPageCallbackToken(provider, page+1), + }) + } + rows = append(rows, nav) + } + rows = append(rows, []models.InlineKeyboardButton{ + {Text: "◀ Back", CallbackData: modelBackCallback}, + {Text: "✗ Cancel", CallbackData: modelCancelCallback}, + }) return &models.InlineKeyboardMarkup{InlineKeyboard: rows} } +func pageBounds(page, count int) (int, int) { + pages := max(1, (count+modelPageSize-1)/modelPageSize) + page = max(0, min(page, pages-1)) + start := page * modelPageSize + return start, min(start+modelPageSize, count) +} + +func (g *Gateway) modelPageCallbackToken(provider string, page int) string { + sum := sha256.Sum256(fmt.Appendf(nil, "%s:%d", provider, page)) + token := fmt.Sprintf("%s%x", modelPageCallbackPrefix, sum[:24]) + g.modelMu.Lock() + g.modelPages[token] = modelPage{Provider: provider, Page: page} + g.modelMu.Unlock() + return token +} + +func (g *Gateway) modelPageForCallback(token string) (modelPage, bool) { + g.modelMu.RLock() + defer g.modelMu.RUnlock() + page, ok := g.modelPages[token] + return page, ok +} + // modelCallbackToken records a stable model identity for an inline button. // A positional index is unsafe: provider changes can reorder the selectable // list after Telegram has rendered the keyboard. @@ -286,13 +365,6 @@ func modelDisplayName(ref, provider string) string { return name } -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, @@ -326,7 +398,160 @@ func (g *Gateway) handleModelCallback( provider, _, _ := strings.Cut(selected, "/") g.answerModelCallback(ctx, b, query.ID, "The model has been changed to: "+modelDisplayName(selected, provider), false) - g.updateModelSelector(ctx, b, query, router.Models) + g.editModelPicker(ctx, b, query, modelSelectionConfirmation(router.Models, selected), nil) +} + +func modelSelectionConfirmation(manager gateway.ModelManager, ref string) string { + provider, _, _ := strings.Cut(ref, "/") + var b strings.Builder + fmt.Fprintf(&b, "Model switched to %s\nProvider: %s", + modelDisplayName(ref, provider), providerDisplayName(provider)) + detailed, ok := manager.(gateway.DetailedModelManager) + if !ok { + b.WriteString("\n\n_(active for this daemon process; resets on restart)_") + return b.String() + } + details, ok := detailed.ModelDetails(ref) + if !ok { + b.WriteString("\n\n_(active for this daemon process; resets on restart)_") + return b.String() + } + if details.ContextWindow > 0 { + fmt.Fprintf(&b, "\nContext: %d tokens", details.ContextWindow) + } + if details.MaxOutputTokens > 0 { + fmt.Fprintf(&b, "\nMax output: %d tokens", details.MaxOutputTokens) + } + var capabilities []string + if details.Reasoning { + capabilities = append(capabilities, "reasoning") + } + if details.Tools { + capabilities = append(capabilities, "tools") + } + for _, modality := range details.InputModalities { + if modality != "text" { + capabilities = append(capabilities, modality) + } + } + if details.Attachment { + capabilities = append(capabilities, "attachments") + } + if details.Structured { + capabilities = append(capabilities, "structured output") + } + if len(capabilities) > 0 { + fmt.Fprintf(&b, "\nCapabilities: %s", strings.Join(capabilities, ", ")) + } + b.WriteString("\n\n_(active for this daemon process; resets on restart)_") + return b.String() +} + +func (g *Gateway) handleModelPageCallback( + 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.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, "Model switching is not configured.", true) + return + } + page, ok := g.modelPageForCallback(query.Data) + if !ok { + g.answerModelCallback(ctx, b, query.ID, "That model page is no longer valid.", true) + return + } + models := manager.ModelsForProvider(page.Provider) + if page.Page < 0 || page.Page*modelPageSize >= len(models) { + g.answerModelCallback(ctx, b, query.ID, "That model page is no longer valid.", true) + return + } + g.answerModelCallback(ctx, b, query.ID, "", false) + g.editModelPicker(ctx, b, query, + modelSelectorTextForProvider(page.Provider, page.Page, len(manager.ModelsForProvider(page.Provider))), + g.modelSelectorKeyboardPage(manager, page.Provider, page.Page)) +} + +func (g *Gateway) handleModelBackCallback( + 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.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, "Model switching is not configured.", true) + return + } + g.answerModelCallback(ctx, b, query.ID, "", false) + g.editModelPicker(ctx, b, query, + providerSelectorText(manager.ActiveModel(), manager.ActiveProvider()), + g.providerSelectorKeyboard(manager)) +} + +func (g *Gateway) handleModelCancelCallback(ctx context.Context, b *bot.Bot, update *models.Update) { + query := update.CallbackQuery + if query == nil { + return + } + if !g.isSenderAllowed(query.From.ID) { + g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) + return + } + g.answerModelCallback(ctx, b, query.ID, "", false) + g.editModelPicker(ctx, b, query, "Model selection cancelled.", nil) +} + +func (g *Gateway) handleModelNoopCallback(ctx context.Context, b *bot.Bot, update *models.Update) { + query := update.CallbackQuery + if query == nil { + return + } + if !g.isSenderAllowed(query.From.ID) { + g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) + return + } + g.answerModelCallback(ctx, b, query.ID, "", false) +} + +func (g *Gateway) editModelPicker( + ctx context.Context, + b *bot.Bot, + query *models.CallbackQuery, + text string, + markup *models.InlineKeyboardMarkup, +) { + params := &bot.EditMessageTextParams{Text: text, ReplyMarkup: markup} + 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 picker failed", "error", err) + } } func (g *Gateway) answerModelCallback( @@ -344,27 +569,3 @@ func (g *Gateway) answerModelCallback( 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: g.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) - } -} diff --git a/internal/channels/telegram/model_test.go b/internal/channels/telegram/model_test.go index 61ac05982..8c01e3628 100644 --- a/internal/channels/telegram/model_test.go +++ b/internal/channels/telegram/model_test.go @@ -22,6 +22,16 @@ type modelManagerStub struct { active string } +type detailedModelManagerStub struct { + *modelManagerStub + details map[string]gateway.ModelDetails +} + +func (m *detailedModelManagerStub) ModelDetails(ref string) (gateway.ModelDetails, bool) { + details, ok := m.details[ref] + return details, ok +} + func (m *modelManagerStub) Models() []string { return append([]string(nil), m.models...) } @@ -124,7 +134,7 @@ func newTelegramTestBot(t *testing.T) (*bot.Bot, *[]telegramRequest) { func TestModelCommandShowsInlineSelector(t *testing.T) { const allowedUserID = int64(42) manager := &modelManagerStub{ - models: []string{"provider/alpha", "provider/beta"}, + models: []string{"provider/alpha", "provider/beta", "other/gamma"}, active: "provider/beta", } router := gateway.NewRouter(nil, nil, "telegram") @@ -155,36 +165,24 @@ func TestModelCommandShowsInlineSelector(t *testing.T) { if !found { t.Fatalf("/model did not send an inline keyboard; requests: %#v", *requests) } - if got := modelSelectorText("deepseek/deepseek-v4-pro"); got != "Select a model:\nCurrent Provider: DeepSeek\nActive: deepseek-v4-pro" { - t.Errorf("model selector text = %q", got) + if got := len(markup.InlineKeyboard); got != 2 { + t.Fatalf("provider keyboard rows = %d, want provider row and cancel row", got) } - if got := len(markup.InlineKeyboard); got != len(manager.models) { - t.Fatalf("keyboard rows = %d, want %d", got, len(manager.models)) + if got := len(markup.InlineKeyboard[0]); got != 2 { + t.Fatalf("provider buttons = %d, want 2", got) } - 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 !strings.HasPrefix(button.CallbackData, modelCallbackPrefix) || button.CallbackData == fmt.Sprintf("model:%d", index) { - t.Errorf("button %d callback = %q, want a stable model token", 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.Contains(markup.InlineKeyboard[0][0].Text, "(2)") { + t.Errorf("provider button lacks model count: %q", markup.InlineKeyboard[0][0].Text) } - if !strings.HasPrefix(markup.InlineKeyboard[1][0].Text, "✓ ") { - t.Errorf("active model button is not marked: %q", markup.InlineKeyboard[1][0].Text) + if !strings.HasPrefix(markup.InlineKeyboard[0][0].Text, "✓ ") { + t.Errorf("active provider button is not marked: %q", markup.InlineKeyboard[0][0].Text) } - for _, row := range markup.InlineKeyboard { - if strings.Contains(row[0].Text, "provider/") { - t.Errorf("model button must not repeat the provider: %q", row[0].Text) - } + if got := markup.InlineKeyboard[1][0].CallbackData; got != modelCancelCallback { + t.Errorf("provider cancel callback = %q", got) } } -func TestProviderCommandFiltersSubsequentModelSelector(t *testing.T) { +func TestModelCommandDrillsFromProviderIntoFilteredModels(t *testing.T) { const allowedUserID = int64(42) manager := &modelManagerStub{ models: []string{ @@ -203,19 +201,19 @@ func TestProviderCommandFiltersSubsequentModelSelector(t *testing.T) { Message: &models.Message{ From: &models.User{ID: allowedUserID}, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}, - Text: "/provider", + Text: "/model", }, }) 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)) + if len(providerMarkup.InlineKeyboard) != 2 || len(providerMarkup.InlineKeyboard[0]) != 2 { + t.Fatalf("provider grid = %#v, want two-column row and cancel", providerMarkup.InlineKeyboard) } *requests = nil - providerCallback := providerMarkup.InlineKeyboard[1][0].CallbackData + providerCallback := providerMarkup.InlineKeyboard[0][1].CallbackData g.defaultHandler(router)(context.Background(), b, &models.Update{ CallbackQuery: &models.CallbackQuery{ ID: "provider-callback", @@ -227,18 +225,10 @@ func TestProviderCommandFiltersSubsequentModelSelector(t *testing.T) { }, }, }) - if manager.ActiveProvider() != "openai" { - t.Fatalf("active provider = %q, want openai", manager.ActiveProvider()) + if manager.ActiveProvider() != "openrouter" { + t.Fatalf("provider selection changed active model prematurely: %q", 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 != "" { @@ -248,11 +238,73 @@ func TestProviderCommandFiltersSubsequentModelSelector(t *testing.T) { } } if len(modelMarkup.InlineKeyboard) != 2 { - t.Fatalf("filtered model rows = %d, want 2", len(modelMarkup.InlineKeyboard)) + t.Fatalf("filtered model rows = %d, want one two-column model row plus navigation", 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) + for _, button := range modelMarkup.InlineKeyboard[0] { + if strings.Contains(button.Text, "openrouter") { + t.Fatalf("OpenRouter model leaked into OpenAI selection: %q", button.Text) + } + } +} + +func TestModelSelectorPaginatesEightModelsWithBackAndCancel(t *testing.T) { + manager := &modelManagerStub{active: "provider/model-09"} + for i := 1; i <= 9; i++ { + manager.models = append(manager.models, fmt.Sprintf("provider/model-%02d", i)) + } + g := New("1:test", "", "", []int64{42}, slog.Default()) + + first := g.modelSelectorKeyboardPage(manager, "provider", 0) + if got := len(first.InlineKeyboard); got != 6 { + t.Fatalf("first page rows = %d, want four model rows, pagination, and actions", got) + } + nav := first.InlineKeyboard[4] + if len(nav) != 2 || nav[0].Text != "1/2" || nav[1].Text != "Next ▶" { + t.Fatalf("first page navigation = %#v", nav) + } + actions := first.InlineKeyboard[5] + if len(actions) != 2 || actions[0].CallbackData != modelBackCallback || + actions[1].CallbackData != modelCancelCallback { + t.Fatalf("actions = %#v", actions) + } + + page, ok := g.modelPageForCallback(nav[1].CallbackData) + if !ok { + t.Fatal("next page callback was not recorded") + } + second := g.modelSelectorKeyboardPage(manager, page.Provider, page.Page) + if got := len(second.InlineKeyboard); got != 3 { + t.Fatalf("second page rows = %d, want model, pagination, and actions", got) + } + if got := second.InlineKeyboard[0][0].Text; got != "✓ model-09" { + t.Fatalf("second page model = %q", got) + } +} + +func TestModelSelectionConfirmationIncludesCatalogMetadata(t *testing.T) { + const ref = "google/gemini-3.6-flash" + manager := &detailedModelManagerStub{ + modelManagerStub: &modelManagerStub{models: []string{ref}, active: ref}, + details: map[string]gateway.ModelDetails{ + ref: { + Ref: ref, ContextWindow: 1_048_576, MaxOutputTokens: 65_536, + Reasoning: true, Tools: true, Structured: true, + InputModalities: []string{"text", "image", "audio"}, + }, + }, + } + + got := modelSelectionConfirmation(manager, ref) + for _, want := range []string{ + "Model switched to gemini-3.6-flash", + "Provider: Google", + "Context: 1048576 tokens", + "Max output: 65536 tokens", + "Capabilities: reasoning, tools, image, audio, structured output", + "active for this daemon process; resets on restart", + } { + if !strings.Contains(got, want) { + t.Errorf("confirmation missing %q:\n%s", want, got) } } } @@ -279,7 +331,7 @@ func TestProviderCallbackHonoursTheProviderRenderedInTheSelector(t *testing.T) { }}, router) if got := manager.ActiveProvider(); got != "openai" { - t.Errorf("stale selector chose %q, want the originally rendered provider", got) + t.Errorf("opening a provider page changed active provider to %q", got) } } @@ -324,6 +376,44 @@ func TestModelCallbackSwitchesAndUpdatesSelector(t *testing.T) { } } +func TestDirectModelSelectionWithProviderIsAtomicOnFailure(t *testing.T) { + const allowedUserID = int64(42) + manager := &modelManagerStub{ + models: []string{"openai/gpt-5.6", "anthropic/claude"}, + active: "openai/gpt-5.6", + } + router := gateway.NewRouter(nil, nil, "telegram") + router.Models = manager + g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + b, _ := newTelegramTestBot(t) + + g.handleModelCommand(context.Background(), b, &models.Message{ + From: &models.User{ID: allowedUserID}, + Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}, + Text: "/model missing --provider anthropic", + }, router) + + if manager.active != "openai/gpt-5.6" { + t.Fatalf("failed selection changed active model to %q", manager.active) + } +} + +func TestModelPageIndicatorCallbackIsAnswered(t *testing.T) { + const allowedUserID = int64(42) + g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + b, requests := newTelegramTestBot(t) + + g.defaultHandler(gateway.NewRouter(nil, nil, "telegram"))(context.Background(), b, &models.Update{ + CallbackQuery: &models.CallbackQuery{ + ID: "noop-id", From: models.User{ID: allowedUserID}, Data: modelNoopCallback, + }, + }) + + if len(*requests) != 1 || (*requests)[0].method != "answerCallbackQuery" { + t.Fatalf("page indicator requests = %#v, want callback acknowledgement", *requests) + } +} + func TestModelCallbackHonoursTheModelRenderedInTheSelector(t *testing.T) { const allowedUserID = int64(42) manager := &modelManagerStub{ diff --git a/internal/channels/telegram/provider.go b/internal/channels/telegram/provider.go index c6397720e..c0b795c7f 100644 --- a/internal/channels/telegram/provider.go +++ b/internal/channels/telegram/provider.go @@ -14,15 +14,6 @@ import ( 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, @@ -36,7 +27,7 @@ func (g *Gateway) sendProviderSelector( } params := &bot.SendMessageParams{ ChatID: msg.Chat.ID, - Text: providerSelectorText(manager.ActiveProvider()), + Text: providerSelectorText(manager.ActiveModel(), manager.ActiveProvider()), ReplyMarkup: g.providerSelectorKeyboard(manager), } if msg.MessageThreadID != 0 { @@ -47,30 +38,47 @@ func (g *Gateway) sendProviderSelector( } } -func providerSelectorText(active string) string { - if active == "" { - return "Choose a provider:" - } - return "Choose a provider:\nActive: " + providerDisplayName(active) +func providerSelectorText(activeModel, activeProvider string) string { + return "⚙ Model Configuration\n\nCurrent model: " + + modelDisplayName(activeModel, activeProvider) + + "\nProvider: " + providerDisplayName(activeProvider) + + "\n\nSelect a provider:" } func (g *Gateway) providerSelectorKeyboard(manager gateway.ProviderModelManager) *models.InlineKeyboardMarkup { active := manager.ActiveProvider() providers := manager.Providers() - rows := make([][]models.InlineKeyboardButton, 0, len(providers)) + buttons := make([]models.InlineKeyboardButton, 0, len(providers)) for _, provider := range providers { - label := providerDisplayName(provider) + label := fmt.Sprintf("%s (%d)", providerName(manager, provider), len(manager.ModelsForProvider(provider))) if provider == active { label = "✓ " + label } - rows = append(rows, []models.InlineKeyboardButton{{ + buttons = append(buttons, models.InlineKeyboardButton{ Text: label, CallbackData: g.providerCallbackToken(provider), - }}) + }) } + rows := make([][]models.InlineKeyboardButton, 0, (len(buttons)+1)/2) + for i := 0; i < len(buttons); i += 2 { + end := min(i+2, len(buttons)) + rows = append(rows, buttons[i:end]) + } + rows = append(rows, []models.InlineKeyboardButton{{ + Text: "✗ Cancel", CallbackData: modelCancelCallback, + }}) return &models.InlineKeyboardMarkup{InlineKeyboard: rows} } +func providerName(manager gateway.ModelManager, provider string) string { + if namer, ok := manager.(gateway.ProviderDisplayNamer); ok { + if name := strings.TrimSpace(namer.ProviderDisplayName(provider)); name != "" { + return name + } + } + return providerDisplayName(provider) +} + func (g *Gateway) providerCallbackToken(provider string) string { sum := sha256.Sum256([]byte(provider)) token := fmt.Sprintf("%s%x", providerCallbackPrefix, sum[:24]) @@ -131,23 +139,24 @@ func (g *Gateway) handleProviderCallback( g.answerModelCallback(ctx, b, query.ID, "That provider selection is no longer valid.", true) return } - if err := manager.SetActiveProvider(ctx, selected); err != nil { - g.answerModelCallback(ctx, b, query.ID, fmt.Sprintf("Cannot switch: %v", err), true) + if len(manager.ModelsForProvider(selected)) == 0 { + g.answerModelCallback(ctx, b, query.ID, "That provider has no selectable models.", true) return } - g.answerModelCallback(ctx, b, query.ID, "Active provider: "+providerDisplayName(selected), false) - g.updateProviderSelector(ctx, b, query, manager) + g.answerModelCallback(ctx, b, query.ID, "", false) + g.updateModelSelectorForProvider(ctx, b, query, manager, selected) } -func (g *Gateway) updateProviderSelector( +func (g *Gateway) updateModelSelectorForProvider( ctx context.Context, b *bot.Bot, query *models.CallbackQuery, manager gateway.ProviderModelManager, + provider string, ) { params := &bot.EditMessageTextParams{ - Text: providerSelectorText(manager.ActiveProvider()), - ReplyMarkup: g.providerSelectorKeyboard(manager), + Text: modelSelectorTextForProvider(provider, 0, len(manager.ModelsForProvider(provider))), + ReplyMarkup: g.modelSelectorKeyboardForProvider(manager, provider), } switch { case query.Message.Message != nil: diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index aff24c4c7..5eec749dd 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -61,6 +61,7 @@ type Gateway struct { pendingRestart *restartRequest modelMu sync.RWMutex modelCallbacks map[string]string + modelPages map[string]modelPage providerMu sync.RWMutex providerCallbacks map[string]string updateMu sync.Mutex @@ -113,6 +114,7 @@ func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *s AllowedUserIDs: allowedUserIDs, restartCh: make(chan restartRequest, 1), modelCallbacks: make(map[string]string), + modelPages: make(map[string]modelPage), providerCallbacks: make(map[string]string), updateActions: make(map[string]updateAction), dangerousActions: make(map[string]dangerousAction), @@ -426,6 +428,14 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { g.handleProviderCallback(ctx, b, update, router) case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix): g.handleModelCallback(ctx, b, update, router) + case strings.HasPrefix(update.CallbackQuery.Data, modelPageCallbackPrefix): + g.handleModelPageCallback(ctx, b, update, router) + case update.CallbackQuery.Data == modelBackCallback: + g.handleModelBackCallback(ctx, b, update, router) + case update.CallbackQuery.Data == modelCancelCallback: + g.handleModelCancelCallback(ctx, b, update) + case update.CallbackQuery.Data == modelNoopCallback: + g.handleModelNoopCallback(ctx, b, update) case strings.HasPrefix(update.CallbackQuery.Data, personalityCallbackPrefix): g.handlePersonalityCallback(ctx, b, update, router) case strings.HasPrefix(update.CallbackQuery.Data, updateCallbackPrefix): @@ -439,17 +449,13 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { return } if isModelSelectorRequest(msg.Text) { - g.sendModelSelector(ctx, b, msg, router) + g.sendProviderSelector(ctx, b, msg, router) return } if isModelCommand(msg.Text) { g.handleModelCommand(ctx, b, msg, router) return } - if isProviderSelectorRequest(msg.Text) { - g.sendProviderSelector(ctx, b, msg, router) - return - } if isPersonalityRequest(msg.Text) { g.handlePersonalityCommand(ctx, b, msg, router) return diff --git a/internal/gateway/compression.go b/internal/gateway/compression.go index 4ce1776a8..9fcc2221e 100644 --- a/internal/gateway/compression.go +++ b/internal/gateway/compression.go @@ -38,7 +38,7 @@ type CompressionConfig struct { } // DefaultCompressionConfig returns a CompressionConfig with sensible -// defaults matching Hermes: compression at 50% threshold, protecting +// defaults: compression at 50% threshold, protecting // first 3 and last 20 messages. ContextWindow defaults to 128k. func DefaultCompressionConfig() CompressionConfig { return CompressionConfig{ diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b36407387..7f9cc4165 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -90,6 +90,31 @@ type ProviderModelManager interface { SetActiveProvider(ctx context.Context, provider string) error } +// ModelDetails is the catalog metadata rendered after an interactive model +// selection. Limits are zero when the upstream catalog does not publish them. +type ModelDetails struct { + Ref string + Name string + ContextWindow int + MaxOutputTokens int + Reasoning bool + Tools bool + Attachment bool + Structured bool + InputModalities []string +} + +// DetailedModelManager is the optional catalog-aware extension used by rich +// model selectors. Runtime routing remains on ModelManager. +type DetailedModelManager interface { + ModelManager + ModelDetails(ref string) (ModelDetails, bool) +} + +type ProviderDisplayNamer interface { + ProviderDisplayName(provider string) string +} + // SpawnRequest is a chat-originated task creation request. Repo and // Workflow are optional -- empty means "the daemon's configured // default for this identity". diff --git a/internal/infrastructure/modelcatalog/catalog.go b/internal/infrastructure/modelcatalog/catalog.go new file mode 100644 index 000000000..89c7d1c5e --- /dev/null +++ b/internal/infrastructure/modelcatalog/catalog.go @@ -0,0 +1,252 @@ +// Adapted from /work/apps/tau/internal/providers/snapshot/gen/main.go at +// b41dda42ef869cc919044ff4f23d7b568531c3f5. +// +// Deliberate mutations: +// - runtime startup fetch and disk fallback replace build-time generation; +// - every models.dev provider is eligible rather than a Tau-owned allowlist; +// - usable providers are derived from live environment and Archie overrides. +package modelcatalog + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/samcharles93/ai-sdk/runtime" + + "github.com/samcharles93/archie-core/internal/config" +) + +type Options struct { + URL string + CachePath string + Getenv func(string) string + Configured map[string]config.Provider + HTTPClient *http.Client +} + +type Snapshot struct { + Providers []Provider +} + +type Provider struct { + ID string + Name string + Class string + APIKeyEnv string + BaseURL string + Models []Model +} + +type Model struct { + ID string + Name string + ContextWindow int + MaxOutputTokens int + Reasoning bool + Attachment bool + Structured bool + InputModalities []string +} + +type catalogProvider struct { + ID string `json:"id"` + Name string `json:"name"` + NPM string `json:"npm"` + API string `json:"api"` + Env []string `json:"env"` + Models map[string]runtime.CatalogModel `json:"models"` +} + +func Load(ctx context.Context, opts Options) (Snapshot, error) { + if opts.Getenv == nil { + opts.Getenv = os.Getenv + } + raw, fetchErr := fetch(ctx, opts) + if fetchErr == nil { + snapshot, parseErr := parse(raw, opts) + if parseErr == nil { + if opts.CachePath != "" { + // The downloaded catalog is already usable. A cache persistence + // failure must not prevent startup with valid in-memory data. + _ = writeCache(opts.CachePath, raw) + } + return snapshot, nil + } + fetchErr = parseErr + } + cached, cacheErr := os.ReadFile(opts.CachePath) + if cacheErr != nil { + return Snapshot{}, errors.Join(fetchErr, fmt.Errorf("read model catalog cache: %w", cacheErr)) + } + snapshot, cacheErr := parse(cached, opts) + if cacheErr != nil { + return Snapshot{}, errors.Join(fetchErr, fmt.Errorf("parse cached model catalog: %w", cacheErr)) + } + return snapshot, nil +} + +func fetch(ctx context.Context, opts Options) ([]byte, error) { + url := strings.TrimSpace(opts.URL) + if url == "" { + url = runtime.DefaultCatalogURL + } + client := opts.HTTPClient + if client == nil { + client = &http.Client{Timeout: 30 * time.Second} + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, fmt.Errorf("build model catalog request: %w", err) + } + resp, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("fetch model catalog: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("fetch model catalog: status %d", resp.StatusCode) + } + raw, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read model catalog response: %w", err) + } + return raw, nil +} + +func writeCache(path string, raw []byte) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(path), ".models-*.json") + if err != nil { + return err + } + tmpName := tmp.Name() + defer func() { _ = os.Remove(tmpName) }() + if err := tmp.Chmod(0o600); err != nil { + _ = tmp.Close() + return err + } + if _, err := tmp.Write(raw); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmpName, path) +} + +func parse(raw []byte, opts Options) (Snapshot, error) { + var catalog map[string]catalogProvider + if err := json.Unmarshal(raw, &catalog); err != nil { + return Snapshot{}, fmt.Errorf("parse model catalog: %w", err) + } + providers := make([]Provider, 0, len(catalog)) + for key, source := range catalog { + if provider, ok := usableProvider(key, source, opts); ok { + providers = append(providers, provider) + } + } + slices.SortFunc(providers, func(a, b Provider) int { + return strings.Compare(a.Name, b.Name) + }) + return Snapshot{Providers: providers}, nil +} + +func usableProvider(key string, source catalogProvider, opts Options) (Provider, bool) { + id := strings.TrimSpace(source.ID) + if id == "" { + id = key + } + override, configured := opts.Configured[id] + envVar := firstSetEnv(source.Env, opts.Getenv) + if configured && override.APIKeyEnv != "" { + envVar = override.APIKeyEnv + } + if (!configured && envVar == "") || + (configured && override.APIKeyEnv != "" && opts.Getenv(override.APIKeyEnv) == "") { + return Provider{}, false + } + models := toolModels(source.Models) + if len(models) == 0 { + return Provider{}, false + } + class, baseURL, supported := providerRuntimeDefaults(source) + if configured { + if override.Class != "" { + class = override.Class + // Explicit classes may be registered by the application before + // runtime construction, so configuration is authoritative here. + supported = true + } + if override.BaseURL != "" { + baseURL = override.BaseURL + } + } + if !supported { + return Provider{}, false + } + name := strings.TrimSpace(source.Name) + if name == "" { + name = displayName(id) + } + return Provider{ + ID: id, Name: name, Class: class, APIKeyEnv: envVar, + BaseURL: baseURL, Models: models, + }, true +} + +func providerRuntimeDefaults(source catalogProvider) (class, baseURL string, supported bool) { + class, supported = runtime.NPMClassMapping[source.NPM] + return class, source.API, supported +} + +func firstSetEnv(names []string, getenv func(string) string) string { + for _, name := range names { + if name = strings.TrimSpace(name); name != "" && getenv(name) != "" { + return name + } + } + return "" +} + +func toolModels(source map[string]runtime.CatalogModel) []Model { + models := make([]Model, 0, len(source)) + for key, model := range source { + if !model.ToolCall { + continue + } + id := strings.TrimSpace(model.ID) + if id == "" { + id = key + } + models = append(models, Model{ + ID: id, Name: model.Name, + ContextWindow: model.ContextWindow(), MaxOutputTokens: model.MaxOutputTokens(), + Reasoning: model.Reasoning, Attachment: model.Attachment, Structured: model.Structured, + InputModalities: slices.Clone(model.Modalities.Input), + }) + } + slices.SortFunc(models, func(a, b Model) int { return strings.Compare(a.ID, b.ID) }) + return models +} + +func displayName(id string) string { + words := strings.FieldsFunc(id, func(r rune) bool { return r == '-' || r == '_' }) + for i := range words { + if words[i] != "" { + words[i] = strings.ToUpper(words[i][:1]) + words[i][1:] + } + } + return strings.Join(words, " ") +} diff --git a/internal/infrastructure/modelcatalog/catalog_test.go b/internal/infrastructure/modelcatalog/catalog_test.go new file mode 100644 index 000000000..08626c829 --- /dev/null +++ b/internal/infrastructure/modelcatalog/catalog_test.go @@ -0,0 +1,231 @@ +package modelcatalog + +import ( + "context" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/config" +) + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +func catalogClient(body string) *http.Client { + return &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(body)), + Header: make(http.Header), + }, nil + })} +} + +func TestLoadDownloadsFiltersAndDiscoversUsableProviders(t *testing.T) { + const body = `{ + "openai": { + "id": "openai", + "name": "OpenAI", + "npm": "@ai-sdk/openai", + "api": "https://api.openai.test/v1", + "env": ["OPENAI_API_KEY"], + "models": { + "tool-model": {"id":"tool-model","name":"Tool Model","tool_call":true,"limit":{"context":1000,"output":100}}, + "text-model": {"id":"text-model","name":"Text Model","tool_call":false} + } + }, + "anthropic": { + "id": "anthropic", + "npm": "@ai-sdk/anthropic", + "env": ["ANTHROPIC_API_KEY"], + "models": {"claude": {"id":"claude","tool_call":true}} + } + }` + cachePath := filepath.Join(t.TempDir(), "models.json") + got, err := Load(context.Background(), Options{ + URL: "https://models.test/catalog.json", + CachePath: cachePath, + HTTPClient: catalogClient(body), + Getenv: func(name string) string { + if name == "OPENAI_API_KEY" { + return "present" + } + return "" + }, + }) + if err != nil { + t.Fatal(err) + } + if len(got.Providers) != 1 { + t.Fatalf("providers = %#v, want one usable provider", got.Providers) + } + provider := got.Providers[0] + if provider.ID != "openai" || provider.Class != "openai" || provider.APIKeyEnv != "OPENAI_API_KEY" { + t.Fatalf("provider = %#v", provider) + } + if len(provider.Models) != 1 || provider.Models[0].ID != "tool-model" { + t.Fatalf("models = %#v, want only tool-capable model", provider.Models) + } + if provider.Models[0].ContextWindow != 1000 || provider.Models[0].MaxOutputTokens != 100 { + t.Fatalf("model limits = %#v", provider.Models[0]) + } + if _, err := os.Stat(cachePath); err != nil { + t.Fatalf("cache was not written: %v", err) + } +} + +func TestLoadFallsBackToCache(t *testing.T) { + cachePath := filepath.Join(t.TempDir(), "models.json") + if err := os.WriteFile(cachePath, []byte(`{ + "openai": { + "id":"openai", + "npm":"@ai-sdk/openai", + "env":["OPENAI_API_KEY"], + "models":{"cached":{"id":"cached","tool_call":true}} + } + }`), 0o600); err != nil { + t.Fatal(err) + } + + got, err := Load(context.Background(), Options{ + URL: "http://127.0.0.1:1", + CachePath: cachePath, + Getenv: func(string) string { return "present" }, + }) + if err != nil { + t.Fatal(err) + } + if len(got.Providers) != 1 || got.Providers[0].Models[0].ID != "cached" { + t.Fatalf("snapshot = %#v", got) + } +} + +func TestLoadPreservesAndUsesCacheWhenDownloadIsInvalid(t *testing.T) { + cachePath := filepath.Join(t.TempDir(), "models.json") + cached := []byte(`{ + "openai": { + "id":"openai", + "npm":"@ai-sdk/openai", + "env":["OPENAI_API_KEY"], + "models":{"cached":{"id":"cached","tool_call":true}} + } + }`) + if err := os.WriteFile(cachePath, cached, 0o600); err != nil { + t.Fatal(err) + } + + got, err := Load(context.Background(), Options{ + URL: "https://models.test/catalog.json", + CachePath: cachePath, + HTTPClient: catalogClient(`{"broken":`), + Getenv: func(string) string { return "present" }, + }) + if err != nil { + t.Fatal(err) + } + if len(got.Providers) != 1 || got.Providers[0].Models[0].ID != "cached" { + t.Fatalf("snapshot = %#v, want preserved cached catalog", got) + } + after, err := os.ReadFile(cachePath) + if err != nil { + t.Fatal(err) + } + if string(after) != string(cached) { + t.Fatalf("invalid download replaced cache:\n%s", after) + } +} + +func TestLoadExplicitProviderOverridesCatalogDefaults(t *testing.T) { + const body = `{ + "openai": { + "id":"openai", + "npm":"@ai-sdk/openai", + "api":"https://catalog.invalid/v1", + "env":["OPENAI_API_KEY"], + "models":{"tool":{"id":"tool","tool_call":true}} + } + }` + got, err := Load(context.Background(), Options{ + URL: "https://models.test/catalog.json", + CachePath: filepath.Join(t.TempDir(), "models.json"), + HTTPClient: catalogClient(body), + Getenv: func(string) string { return "present" }, + Configured: map[string]config.Provider{ + "openai": { + Class: "openai-compatible", + APIKeyEnv: "CUSTOM_KEY", + BaseURL: "https://custom.test/v1", + }, + }, + }) + if err != nil { + t.Fatal(err) + } + provider := got.Providers[0] + if provider.Class != "openai-compatible" || provider.APIKeyEnv != "CUSTOM_KEY" || + provider.BaseURL != "https://custom.test/v1" { + t.Fatalf("configured override lost: %#v", provider) + } +} + +func TestLoadMapsGoogleCatalogProviderToSDKGeminiClass(t *testing.T) { + const body = `{ + "google": { + "id":"google", + "npm":"@ai-sdk/google", + "env":["GOOGLE_API_KEY","GEMINI_API_KEY"], + "models":{"gemini":{"id":"gemini","tool_call":true}} + } + }` + got, err := Load(context.Background(), Options{ + URL: "https://models.test/catalog.json", + CachePath: filepath.Join(t.TempDir(), "models.json"), + HTTPClient: catalogClient(body), + Getenv: func(name string) string { + if name == "GEMINI_API_KEY" { + return "present" + } + return "" + }, + }) + if err != nil { + t.Fatal(err) + } + if len(got.Providers) != 1 { + t.Fatalf("providers = %#v, want Google provider", got.Providers) + } + if got.Providers[0].Class != "gemini" { + t.Fatalf("Google class = %q, want ai-sdk native gemini class", got.Providers[0].Class) + } + if got.Providers[0].APIKeyEnv != "GEMINI_API_KEY" { + t.Fatalf("Google key env = %q, want present catalog env", got.Providers[0].APIKeyEnv) + } +} + +func TestLoadExcludesProviderWithoutSupportedSDKClass(t *testing.T) { + const body = `{ + "native-only": { + "id":"native-only", + "npm":"@ai-sdk/native-only", + "env":["NATIVE_KEY"], + "models":{"tool":{"id":"tool","tool_call":true}} + } + }` + got, err := Load(context.Background(), Options{ + URL: "https://models.test/catalog.json", CachePath: filepath.Join(t.TempDir(), "models.json"), + HTTPClient: catalogClient(body), Getenv: func(string) string { return "present" }, + }) + if err != nil { + t.Fatal(err) + } + if len(got.Providers) != 0 { + t.Fatalf("providers = %#v, want unsupported provider excluded", got.Providers) + } +}