feat(telegram): /restart to reload config without dropping tasks (16.35)
Operator escape hatch: reload gateway config (notably the sender allowlist) or recover a wedged adapter from chat, with no shell access to the host. Start becomes a supervisor loop that relaunches the bot on request, so a restart is scoped to the gateway: the daemon keeps running and in-flight agent tasks are untouched. Exiting the process would also have restarted under the unless-stopped policy, but would have killed running work. Two failure modes are handled deliberately: - The handler runs on the very bot the supervisor is about to stop, so it hands off over a buffered channel and returns instead of tearing down inline, which would deadlock the restart it just requested. A duplicate request while one is in flight is dropped, not queued. - A failed config reload logs and relaunches on the previous settings, so a bad config edit cannot take chat down permanently -- which would also remove the means to fix it. Authorisation is inherited from authorizedMessage: only allowlisted senders reach any handler, so /restart is admin-only by construction. main.go supplies Reload, which re-reads config from disk and refreshes token and allowlist; other fields still need a full daemon restart, since they are wired at construction.
This commit is contained in:
1 parent
9fd4696492
commit
19a6311f6c
5 files changed
+194
-13
No files matched your search
+5
-3
@@ -1,4 +1,4 @@
|
||||
{"_type":"issue","id":"archie-core-abg.16.33","title":"Telegram: allowlist senders, fail closed when unset","description":"telegram.New is called with a nil allowlist and isChatAllowed returns true when the allowlist is empty, so any Telegram user who finds the bot can talk to it. AllowedChatIDs is not plumbed into config at all. This gates exposing any real tools to the chat agent: with an MCP shell/filesystem server wired, allow-all becomes RCE for arbitrary senders.","acceptance_criteria":"Allowlist is configurable via config.toml. Unset means deny, not allow. Sender identity (user id) is checked, not just chat id, so a group chat cannot be used to bypass it. Rejections are logged with the sender id. Startup logs loudly when the chat gateway is enabled with an empty allowlist.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T19:11:40Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:11:40Z","dependencies":[{"issue_id":"archie-core-abg.16.33","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:11:40Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.33","title":"Telegram: allowlist senders, fail closed when unset","description":"telegram.New is called with a nil allowlist and isChatAllowed returns true when the allowlist is empty, so any Telegram user who finds the bot can talk to it. AllowedChatIDs is not plumbed into config at all. This gates exposing any real tools to the chat agent: with an MCP shell/filesystem server wired, allow-all becomes RCE for arbitrary senders.","acceptance_criteria":"Allowlist is configurable via config.toml. Unset means deny, not allow. Sender identity (user id) is checked, not just chat id, so a group chat cannot be used to bypass it. Rejections are logged with the sender id. Startup logs loudly when the chat gateway is enabled with an empty allowlist.","status":"closed","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T19:11:40Z","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.33","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:11:40Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.41","title":"Tool-provider engine: lifecycle registry with MCP and memory providers","description":"Build the typed tool-provider capability family over the central tools registry. Providers declare a plugin manifest, lifecycle/health, and discover executable ToolEntry values. Add adapters for memory.Manager and configured MCP servers, perform MCP initialize/tools-list/tools-call, register handlers atomically with collision rollback, translate available entries to ai-sdk core.ToolSet, and wire consumers so registered tools are actually callable rather than dead daemon fields.","design":"internal/tools owns Provider and ProviderRegistry; Provider is a typed domain contract and uses the shared plugin manifest/lifecycle vocabulary. The registry owns provider registration and tool indexing while the capability host orchestrates cross-family lifecycle. Memory is adapted without changing internal/memory concurrent work. MCP provider wraps the existing stdio transport without modifying its concurrent implementation, adds protocol client behavior in new files, prefixes/sanitizes server tool names deterministically, and retains original MCP names for calls. Never advertise a tool on an execution path that cannot invoke its handler; explicitly proxy or omit tools across subprocess/NATS boundaries.","acceptance_criteria":"Provider registration is atomic and rejects duplicate provider/tool IDs without partial state. Start/discovery failure rolls back tools and lifecycle; stop removes availability and shuts providers down in reverse order. Memory provider tools appear in the central registry and execute through memory.Manager. A fake MCP server proves initialize, initialized notification where supported, tools/list discovery, tools/call execution, JSON-RPC errors, shutdown, and name mapping. Available tools convert to valid ai-sdk core.ToolSet and are used by the gateway conversational loop and supported agent execution paths; unsupported remote paths do not advertise unusable handlers. Configuration creates providers through typed factories. Focused/race tests, lint, task check, and fresh adversarial review pass subject only to documented concurrent baseline failures.","notes":"Implemented typed provider.Engine + provider.Registry capability family; atomic central RegisterBatch/Unregister; dependency-ordered start/discovery, bounded rollback, retryable failed cleanup, reverse stop and health aggregation. Added memory.Manager adapter and lifecycle-managed MCP adapter with initialize/list/call, deterministic ASCII name mapping, original-name dispatch, tool errors, resource text and multimodal preservation. Composition uses typed config factory, omits unsupported HTTP/unknown transports, registers the family with capabilityHost, defers gateways until host+daemon startup, shuts memory down, builds validated ai-sdk ToolSets, uses independent 8-step chat loop, and exposes handlers only to Telegram chat/in-process agents. Focused race tests pass; scoped lint 0; fresh final adversarial review 0 findings. task check passes every package except known concurrent internal/gateway /spawn tests. Dependency abg.17.16 remains independently in progress.\nImplementation and review are complete; Beads closure is intentionally deferred because required transport issue archie-core-abg.17.16 is still open. Close without --force when that dependency completes.","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T05:11:10Z","created_by":"Sam Catlow","updated_at":"2026-07-26T17:44:51Z","started_at":"2026-07-26T06:22:50Z","closed_at":"2026-07-26T17:44:51Z","close_reason":"Blocking dependency abg.17.16 closed; tool-provider engine work was already implementation-complete and previously reviewed clean.","dependencies":[{"issue_id":"archie-core-abg.17.41","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T15:11:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.41","depends_on_id":"archie-core-abg.40","type":"blocks","created_at":"2026-07-26T15:11:17Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.41","depends_on_id":"archie-core-abg.17.16","type":"blocks","created_at":"2026-07-26T15:11:18Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.40","title":"Capability host: manifests, lifecycle, health, and typed family installation","description":"Replace the inert metadata-only daemon plugin inventory with a capability host that validates plugin manifests and coordinates lifecycle without adding generic domain hooks. The host owns module identity/API compatibility/dependency ordering/start/health/stop state; typed family registries remain responsible for capability registration. Wire it into archied startup/shutdown and expose status without passing *daemon.Daemon to plugins.","design":"Keep plugin.Plugin exactly Name/Version. Add a validated Manifest and lifecycle vocabulary in internal/plugin plus a Host that manages manifests and lifecycle only. Capability packages receive narrow typed registrars; the host must not become an any-typed service locator. Start in dependency order, roll back a partially failed start, stop in reverse order, isolate panics/errors, and return immutable health snapshots. Preserve existing Yaegi loading through an adapter or manifest synthesis for metadata-only legacy plugins.","acceptance_criteria":"Manifest validation covers stable ID, semantic version, host API compatibility, declared capability kinds, dependencies, permissions, and optional config schema. Duplicate IDs, missing dependencies, cycles, incompatible API versions, and invalid manifests fail deterministically. Host lifecycle tests prove dependency-ordered start, rollback, reverse stop, health aggregation, idempotent shutdown, and panic/error isolation. archied owns one host and starts/stops it. plugin.Plugin remains metadata-only and architecture tests pass. task check and lint are green apart from explicitly identified concurrent baseline failures; fresh adversarial review has no surviving findings.","notes":"Implemented strict manifest validation, dependency-ordered lifecycle, bounded/retryable rollback cleanup, reverse shutdown, health snapshots, legacy metadata adapter, and archied composition. Removed divergent daemon PluginRegistry. TDD focused tests, race tests, lint, formatting, and independent adversarial re-review all pass with zero surviving findings. Repository-wide task check remains separately subject to concurrent gateway work.","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T05:11:09Z","created_by":"Sam Catlow","updated_at":"2026-07-26T06:38:08Z","started_at":"2026-07-26T05:14:06Z","closed_at":"2026-07-26T06:38:08Z","close_reason":"Capability host, manifest/lifecycle, composition, enforcement tests, and adversarial remediation complete","dependencies":[{"issue_id":"archie-core-abg.40","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T15:11:08Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.38","title":"MVP: make chat-originated tasks native and controllable","description":"The current /spawn path fabricates an issue number and enqueues it as if it were forge-backed, always against the first repo. The task schema has no source or identity, the workflow later performs forge labels/comments against a nonexistent issue, and /approve and /cancel are absent. Add a native chat task source routed through the same daemon-owned workflow and review gates without pretending a forge issue exists.","acceptance_criteria":"Chat can select identity, repo, and workflow; /spawn creates a durable native task with a real task ID; daemon processing avoids forge-only operations when no forge artifact exists; /approve and /cancel enforce authorization and valid state transitions; end-to-end tests cover spawn through completion, approval, cancellation, restart recovery, and invalid cross-identity control.","notes":"Adversarial review completed. All blocking findings were false positives — verified against actual code:\n1. /approve and /cancel ARE implemented (gateway.go:292-320, tasks.go:198-224)\n2. Daemon processing GUARDS forge operations via IsForgeBacked() (daemon.go:666,672,715,727,751,944)\n3. CreateTask returns REAL DB ID from EnqueueChatTask, not synthetic issue number (tasks.go:113)\n4. Identity scoping IS implemented via StoreTaskCreatorForProfiles + authorize() (tasks.go:70-224)\n5. handleStatus HAS nil check for r.Store (gateway.go:336-338)\n6. int overflow on 32-bit — not our platform (deployed on 64-bit Linux)\n7. The review agent was working in a worktree that appears to have not reflected the full implementation\n\nTest coverage: 34 router tests (gateway_test.go), 15+ StoreTaskCreator/Controller tests (tasks_test.go) covering spawn/approve/cancel lifecycle, cross-identity rejection, state validation, profile-based identity selection. Acceptance criteria met: identity/repo/workflow selection ✓, durable task creation ✓, forge-free daemon processing ✓, authorization enforcement ✓, end-to-end tests ✓.","status":"closed","priority":0,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:37:01Z","created_by":"Sam Catlow","updated_at":"2026-07-26T17:29:25Z","started_at":"2026-07-26T15:18:54Z","closed_at":"2026-07-26T17:29:25Z","close_reason":"Chat-native task lifecycle implemented and adversarially reviewed; all blocking findings were false positives verified against actual code. 34 router tests + 15 controller tests covering full lifecycle. IsForgeBacked() guards daemon forge operations.","dependencies":[{"issue_id":"archie-core-abg.38","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:37:01Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
@@ -53,8 +53,9 @@
|
||||
{"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:22Z","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16.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.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T19:11:42Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:11:42Z","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":"open","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:11:41Z","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.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 configurable per deployment. Tool execution runs inside the Firecracker sandbox rather than on the host. Chat agent can make a code change end to end. Depends on the sender allowlist (16.33, done) being in place first.","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:15:34Z","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":0,"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":"Sam also wants /restore (revert last change) alongside /restart; both are gateway-scoped operator escape hatches. Constraint from Sam: must NOT kill in-flight agent tasks, so prefer a gateway-scoped restart (Stop, re-read config, Start the telegram gateway) over exiting the process. Note the container restart policy is unless-stopped, so a process exit WOULD come back, but it would nuke running tasks. Must be admin-only - gate on the new chat.telegram.allowed_user_ids.","status":"in_progress","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:20:06Z","started_at":"2026-07-26T19:20:06Z","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}
|
||||
{"_type":"issue","id":"archie-core-50z","title":"Enforce typed plugin engine architecture rule","description":"Cement the repository invariant that a plugin engine is a typed capability family with an owning registry/manager and lifecycle semantics, never a generic daemon hook. Add one canonical architecture rule referenced by both AGENTS.md and CLAUDE.md, record it in Beads memory, and add an executable architecture test that prevents drift without touching the concurrently edited secret/config packages.","acceptance_criteria":"A canonical rule defines typed domain contract, owning registry/manager, lifecycle and health expectations, narrow host access, and trust boundaries; AGENTS.md and CLAUDE.md both surface the rule through their shared source; an architecture test fails for generic plugin-hook expansion or an engine interface without a family manager; focused tests and task check pass; fresh adversarial review has no surviving findings.","notes":"Complete. Red proof: architecture test failed on missing canonical rule. Green: internal/plugin tests pass; golangci-lint ./internal/plugin reports zero issues; gofumpt diff is empty. Fresh adversarial review initially found bypassable owner checks and ambiguous trust wording; remediated with signature-linked single-owner validation, negative fixtures (metadata-only, embedded-only, unrelated/split owners, pointer and collection wrappers), and precise trusted-in-process/out-of-process/container language. Final fresh review: zero surviving findings. Full task check was attempted but is currently blocked by concurrent unrelated migrations: gateway fakeTaskCreator still implements CreateTask(context.Context,string) while interface now wants SpawnRequest, and daemon EnqueueIssue callers omit the new eighth argument. No secret/config source was edited by this issue.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T05:00:36Z","created_by":"Sam Catlow","updated_at":"2026-07-26T05:14:06Z","started_at":"2026-07-26T05:00:43Z","closed_at":"2026-07-26T05:14:06Z","close_reason":"Strict plugin-engine invariant documented in canonical architecture and shared AGENTS/CLAUDE instructions, persisted in Beads memory, mechanically enforced with adversarial negative controls, and independently reviewed with zero findings.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.39","title":"MVP: migrate Hermes profiles, memory, skills, and session state","description":"The copied live Hermes instance contains root plus agile-lead, dev, and local-agent profiles with distinct models, gateways, memories, SOUL prompts, skills, sessions, and cron state. archie-core currently has forge identities but no profile-scoped gateway/tool/memory/workspace composition and no importer. Define the mapping into archie-core identities/profiles and build a one-time idempotent migration plus cutover rehearsal.","acceptance_criteria":"Document and implement the mapping for all copied profiles -- MAPPING DOCUMENTED (docs/prds/hermes-migration-dry-run.md), NOT YET IMPLEMENTED (blocked on abg.36). Import SOUL/USER/MEMORY/skills/session/cron without secrets -- NOT STARTED (design-blocked on abg.36, see report). Produce a dry-run report -- DONE. Rehearse dual-run/shadow validation and rollback-safe cutover checklist -- NOT STARTED.","notes":"Dry-run inventory + mapping report delivered: docs/prds/hermes-migration-dry-run.md. Surveyed .hermes-carina/ (live copy of the Hermes deployment) structurally only -- directory listings and non-secret YAML top-level keys, zero secret file contents read (.env/auth.json/mcp-tokens/ explicitly excluded and never opened). Found and catalogued 4 environments (main/agile-lead/dev/local-agent), their skill counts (34/20/25/17), main's 419 session keys (sessions/sessions.json), cron jobs.json presence. Proposed a mapping table: environment-\u003eIdentityConfig, SOUL.md-\u003enew persona system-prompt field (no existing archie-core field for this), memories/-\u003einternal/memory.Manager (needs format translator), skills/-\u003einternal/skill.Catalog (closest 1:1, needs tool-compat pass), sessions-\u003egateway.SessionStore (needs translator), cron/jobs.json-\u003eblocked, no archie-core cron subsystem exists yet (abg.24 territory). Documented explicit exclusion list for the eventual importer (secrets never copied). Documented why actual import tooling is blocked until abg.36 lands (no point importing SOUL/memory/skills into a runtime that doesn't consume them per-turn yet) -- this report is prep, not the importer itself.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:37:09Z","created_by":"Sam Catlow","updated_at":"2026-07-26T05:16:40Z","started_at":"2026-07-26T05:14:49Z","dependencies":[{"issue_id":"archie-core-abg.39","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:37:08Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
@@ -119,6 +120,7 @@
|
||||
{"_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-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.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T19:15:34Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:15:34Z","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":"{}"}],"dependency_count":0,"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}
|
||||
{"_type":"issue","id":"archie-core-xec.4","title":"generalize Provider.APIKeyEnv / NATS.TokenEnv / Telegram.TokenEnv to SecretRef","description":"Follow-up to archie-core-xec, which only migrated Forge.TokenEnv (self-contained call site). Provider.APIKeyEnv is forwarded THREE different ways that all assume the secret is reachable by name in the daemon's own env, not resolved centrally:\n1. agentexec.NewRuntime -\u003e passes the env-var NAME into ai-sdk/runtime's AuthConfig.APIKeyEnv, which lazily os.Getenv's it later (external module, cannot change its contract).\n2. agentexec.WorkerEnvironment / subprocess.go WorkerEnvironment() -\u003e allowlist-forwards the NAME into a subprocess's environment for archie-agent to read itself.\n3. daemon.containerEnv() -\u003e already eagerly resolves via os.Getenv and injects NAME=value into a container env (this one generalizes cleanly).\n\nMigrating Provider.APIKeyEnv to SecretRef requires switching cases 1 and 2 from name-forwarding to eager-resolve-via-secret.Registry-then-inject-value (ai-sdk/runtime.AuthConfig.APIKey literal field already supports this per its ResolveAPIKey fallback chain -- no ai-sdk/runtime changes needed, just stop relying on its lazy os.Getenv path for non-env engines). Also migrate NATSConfig.TokenEnv and TelegramConfig.TokenEnv (each has a single simple os.Getenv call site, lower risk than Provider).","design":"secret.Registry must be threaded into agentexec.NewRuntime, WorkerEnvironment, and daemon.containerEnv (or a shared secret-resolution helper) so eager-resolve-then-inject replaces name-forwarding for engines other than the built-in env engine.","acceptance_criteria":"Provider.APIKeyEnv, NATSConfig.TokenEnv, TelegramConfig.TokenEnv replaced with SecretRef; all three consumption paths (in-process runtime, subprocess worker env, container env) resolve via secret.Registry; task check passes; adversarial review finds zero surviving findings; explicit test proving a non-env engine (e.g. a fake test engine) correctly delivers a provider API key to agentexec.NewRuntime via the AuthConfig.APIKey literal field, not APIKeyEnv.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T04:18:36Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:18:36Z","dependencies":[{"issue_id":"archie-core-xec.4","depends_on_id":"archie-core-xec","type":"parent-child","created_at":"2026-07-26T14:18:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
|
||||
@@ -277,6 +277,30 @@ func run() int {
|
||||
}
|
||||
tg := telegram.New(tgToken, "", "", cfg.Chat.Telegram.AllowedUserIDs, log)
|
||||
|
||||
// /restart re-reads config from disk so allowlist and token edits
|
||||
// apply without restarting the daemon and killing running tasks.
|
||||
// Only gateway-scoped fields are refreshed; everything else needs a
|
||||
// full restart, since it was wired into the daemon at construction.
|
||||
tg.Reload = func(g *telegram.Gateway) error {
|
||||
newCfg, err := config.LoadOverlay(*cfgPath, *overlayPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reload config: %w", err)
|
||||
}
|
||||
tokenEnv := newCfg.Chat.Telegram.TokenEnv
|
||||
if tokenEnv == "" {
|
||||
return fmt.Errorf("reload config: chat.telegram.token_env is unset")
|
||||
}
|
||||
token := os.Getenv(tokenEnv)
|
||||
if token == "" {
|
||||
return fmt.Errorf("reload config: %s is empty", tokenEnv)
|
||||
}
|
||||
g.Token = token
|
||||
g.AllowedUserIDs = newCfg.Chat.Telegram.AllowedUserIDs
|
||||
log.Info("chat gateway config reloaded",
|
||||
"allowed_user_ids", len(g.AllowedUserIDs))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Session store backed by the same NellDB log as task state.
|
||||
// Sessions and messages survive daemon restarts.
|
||||
var sessionStore gateway.SessionStore
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
)
|
||||
|
||||
// restartRequest identifies who asked for a restart, so the relaunched
|
||||
// instance can confirm back to the same chat.
|
||||
type restartRequest struct {
|
||||
chatID int64
|
||||
threadID int
|
||||
}
|
||||
|
||||
// restartHandler serves /restart: an operator escape hatch for reloading
|
||||
// config (notably the sender allowlist) or recovering a wedged adapter
|
||||
// without shell access to the host.
|
||||
//
|
||||
// Authorisation is inherited: authorizedMessage rejects anyone outside
|
||||
// AllowedUserIDs before this runs, so reaching it already implies an
|
||||
// allowlisted sender.
|
||||
func (g *Gateway) restartHandler() bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Acknowledge on the current instance: it is about to be torn
|
||||
// down, and the relaunched one confirms completion.
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "🔄 Restarting gateway…")
|
||||
|
||||
// Hand off to the supervisor rather than tearing down from inside
|
||||
// this handler, which runs on the very bot being stopped. Never
|
||||
// block: a restart already in flight makes this request redundant.
|
||||
select {
|
||||
case g.restartCh <- restartRequest{chatID: msg.Chat.ID, threadID: msg.MessageThreadID}:
|
||||
default:
|
||||
g.log.Warn("restart already in progress, ignoring duplicate request")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The restart channel is buffered so a handler can hand off without
|
||||
// blocking: the handler runs on the very bot the supervisor is about to
|
||||
// stop, so blocking there would deadlock the restart it just asked for.
|
||||
func TestRestartRequestNeverBlocksHandler(t *testing.T) {
|
||||
g := New("tok", "", "", []int64{1}, slog.Default())
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
// Two sends with nothing draining: the first buffers, the second
|
||||
// must hit the default branch rather than block.
|
||||
for range 2 {
|
||||
select {
|
||||
case g.restartCh <- restartRequest{chatID: 7}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
<-done
|
||||
|
||||
if got := len(g.restartCh); got != 1 {
|
||||
t.Fatalf("restartCh holds %d requests, want 1 (second must be dropped, not queued)", got)
|
||||
}
|
||||
if req := <-g.restartCh; req.chatID != 7 {
|
||||
t.Errorf("chatID = %d, want 7", req.chatID)
|
||||
}
|
||||
}
|
||||
|
||||
// A failing Reload must not be fatal: a bad config edit should leave the
|
||||
// gateway running on its previous settings, not take chat down for good.
|
||||
func TestReloadFailureKeepsPreviousSettings(t *testing.T) {
|
||||
g := New("original-token", "", "", []int64{1}, slog.Default())
|
||||
g.Reload = func(*Gateway) error { return errReloadTest }
|
||||
|
||||
if err := g.Reload(g); err == nil {
|
||||
t.Fatal("expected reload error")
|
||||
}
|
||||
if g.Token != "original-token" {
|
||||
t.Errorf("Token = %q, want the previous value retained", g.Token)
|
||||
}
|
||||
if !g.isSenderAllowed(1) {
|
||||
t.Error("previous allowlist should be retained after a failed reload")
|
||||
}
|
||||
}
|
||||
|
||||
var errReloadTest = errTest("bad config")
|
||||
|
||||
type errTest string
|
||||
|
||||
func (e errTest) Error() string { return string(e) }
|
||||
@@ -32,10 +32,20 @@ type Gateway struct {
|
||||
// is public, and chat tools run with the daemon's authority, so failing
|
||||
// open would expose those tools to any stranger who finds the bot.
|
||||
AllowedUserIDs []int64
|
||||
log *slog.Logger
|
||||
bot *bot.Bot
|
||||
webhookCancel context.CancelFunc
|
||||
running bool
|
||||
// Reload re-reads configuration during /restart and applies it to g.
|
||||
// Supplied by the composition root, which owns config paths. Nil
|
||||
// restarts with the settings already in memory.
|
||||
Reload func(*Gateway) error
|
||||
|
||||
// restartCh carries /restart requests from a bot handler to the
|
||||
// supervisor loop in Start. Buffered so a handler never blocks.
|
||||
restartCh chan restartRequest
|
||||
pendingRestart *restartRequest
|
||||
|
||||
log *slog.Logger
|
||||
bot *bot.Bot
|
||||
webhookCancel context.CancelFunc
|
||||
running bool
|
||||
}
|
||||
|
||||
// New returns an unstarted Gateway. Call Start to begin webhook
|
||||
@@ -46,20 +56,63 @@ func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *s
|
||||
WebhookURL: webhookURL,
|
||||
WebhookSecret: webhookSecret,
|
||||
AllowedUserIDs: allowedUserIDs,
|
||||
restartCh: make(chan restartRequest, 1),
|
||||
log: log.With("component", "gateway-telegram"),
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) Name() string { return "telegram" }
|
||||
|
||||
// Start builds the bot, registers handlers, sets the webhook (if
|
||||
// configured), and begins processing. Blocks until ctx is cancelled.
|
||||
// Start supervises the bot: it launches an instance and relaunches it
|
||||
// whenever a restart is requested, blocking until ctx is cancelled.
|
||||
//
|
||||
// Restarts are scoped to this gateway. The daemon keeps running, so
|
||||
// in-flight agent tasks are untouched -- the whole point of the escape
|
||||
// hatch is to recover chat without disturbing work in progress.
|
||||
func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
|
||||
if g.Token == "" {
|
||||
return fmt.Errorf("telegram bot token is required")
|
||||
}
|
||||
g.log.Info("starting telegram gateway")
|
||||
|
||||
for {
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
b, err := g.launch(runCtx, router)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
// Confirm to whoever asked, now that the new instance can send.
|
||||
if req := g.pendingRestart; req != nil {
|
||||
g.sendMessage(runCtx, b, req.chatID, req.threadID, "✅ Gateway restarted.")
|
||||
g.pendingRestart = nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
cancel()
|
||||
return g.Stop(context.Background())
|
||||
case req := <-g.restartCh:
|
||||
g.log.Info("restarting telegram gateway", "requested_by", req.chatID)
|
||||
cancel()
|
||||
if err := g.Stop(context.Background()); err != nil {
|
||||
g.log.Warn("stop during restart failed", "error", err)
|
||||
}
|
||||
if g.Reload != nil {
|
||||
if err := g.Reload(g); err != nil {
|
||||
// Keep the previous settings rather than dying: a bad
|
||||
// config edit must not take the gateway down for good.
|
||||
g.log.Error("config reload failed, restarting with previous settings", "error", err)
|
||||
}
|
||||
}
|
||||
g.pendingRestart = &req
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// launch builds one bot instance, registers handlers and begins receiving.
|
||||
// It returns as soon as delivery is running; the caller owns ctx.
|
||||
func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot, error) {
|
||||
opts := []bot.Option{
|
||||
bot.WithErrorsHandler(func(err error) {
|
||||
g.log.Error("telegram pipeline error", "error", err)
|
||||
@@ -76,13 +129,14 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
|
||||
|
||||
b, err := bot.New(g.Token, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create bot: %w", err)
|
||||
return nil, fmt.Errorf("create bot: %w", err)
|
||||
}
|
||||
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())
|
||||
|
||||
// Publish the command list so Telegram renders a menu. Without this
|
||||
// the commands are undiscoverable and the LLM, having no idea they
|
||||
@@ -99,7 +153,7 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
|
||||
DropPendingUpdates: true,
|
||||
}
|
||||
if _, err := b.SetWebhook(ctx, params); err != nil {
|
||||
return fmt.Errorf("set webhook: %w", err)
|
||||
return nil, fmt.Errorf("set webhook: %w", err)
|
||||
}
|
||||
g.log.Info("webhook set", "url", g.WebhookURL)
|
||||
|
||||
@@ -124,8 +178,7 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
|
||||
go b.Start(ctx)
|
||||
}
|
||||
|
||||
<-ctx.Done()
|
||||
return nil
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Stop gracefully shuts down the bot and deletes the webhook.
|
||||
|
||||
Reference in new issue
Block a user