diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl
index d112c3076..1a5aad3ae 100644
--- a/.beads/interactions.jsonl
+++ b/.beads/interactions.jsonl
@@ -257,3 +257,19 @@
{"id":"int-255bca6bd2735fff9704e54087ad3598","kind":"field_change","created_at":"2026-08-04T15:28:28.194396619Z","actor":"Sam Catlow","issue_id":"archie-core-g4c","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass."}}
{"id":"int-bc32e8e1d480f244e4d321f6a5614514","kind":"field_change","created_at":"2026-08-04T15:28:28.367302939Z","actor":"Sam Catlow","issue_id":"archie-core-3dn","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass."}}
{"id":"int-aaac30bcbe470bad73f365ecd86530c2","kind":"field_change","created_at":"2026-08-04T15:28:28.557167416Z","actor":"Sam Catlow","issue_id":"archie-core-hiy","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass."}}
+{"id":"int-5bda94d6f0d8def3009ef445974cd3c8","kind":"field_change","created_at":"2026-08-04T18:17:25.101664074Z","actor":"Sam Catlow","issue_id":"archie-core-abg.7","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented shared Router-backed Web UI chat with streamed responses, persisted sessions, command parity, focused API tests, frontend tests/build, and task check verification. Deployment/restart intentionally not performed."}}
+{"id":"int-8ddd94fb8bb36b651a15fefe4f75cd28","kind":"field_change","created_at":"2026-08-04T18:17:25.557697898Z","actor":"Sam Catlow","issue_id":"archie-core-abg.6","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented persistent Web chat sessions/history, new/resume controls, slash-command routing, model/personality controls, focused tests, frontend tests/build, and task check verification. Deployment/restart intentionally not performed."}}
+{"id":"int-1a1ad5bf1b079993ffecc077db0857a3","kind":"field_change","created_at":"2026-08-04T18:24:04.814687364Z","actor":"Sam Catlow","issue_id":"archie-core-abg.41","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Refined Web Chat into a composer-first workspace with a compact conversation rail, centered empty state, prompt chips, quiet header controls, responsive layout, and constrained model selector. Verified with npm test, npm run build, Playwright MCP browser inspection, and task check."}}
+{"id":"int-c482fbfaa2dbfe08ecd23b4f3c4b6574","kind":"field_change","created_at":"2026-08-04T18:28:45.488043363Z","actor":"Sam Catlow","issue_id":"archie-core-abg.42","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shared the release update service between Telegram and Web Chat; added Web check, defer, and explicit install API/UI controls with snapshot validation. Verified endpoint tests, frontend tests/build, Playwright MCP rendering, and task check."}}
+{"id":"int-04e634f715d20567688d144451fd812a","kind":"field_change","created_at":"2026-08-04T18:32:01.275461123Z","actor":"Sam Catlow","issue_id":"archie-core-abg.43","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added safe Telegram-style Markdown rendering to Web Chat history and completed streamed replies, including headings, emphasis, links, lists, blockquotes, inline code, and fenced code blocks. Verified with Playwright MCP DOM assertions, npm test/build, and task check."}}
+{"id":"int-7da2e291c35effc305fb2f1564aed37c","kind":"field_change","created_at":"2026-08-04T18:35:41.764041401Z","actor":"Sam Catlow","issue_id":"archie-core-abg.44","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shared Telegram's scoped adapter restart with Web Chat via the gateway router, callback registration, non-blocking Telegram queueing, and an explicit conditional Reload Telegram control. Verified with gateway/Telegram tests, Playwright MCP interaction, frontend tests/build, and task check."}}
+{"id":"int-b57138dd266f25f31d699e39ffc044ff","kind":"field_change","created_at":"2026-08-05T00:10:51.772810903Z","actor":"Sam Catlow","issue_id":"archie-core-abg.45","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Extracted the sandbox dangerous-action contract into gateway, added Web pending approval/approve-for-24h/deny workflows for rollback and process stop, and kept the UI capability-gated. Telegram setup accepts the same authority contract. Verified endpoint/service tests, Playwright MCP approval-request rendering, frontend tests/build, and task check."}}
+{"id":"int-a284f10e8c87a7f4fa74abaac6013bdf","kind":"field_change","created_at":"2026-08-05T00:13:40.942188398Z","actor":"Sam Catlow","issue_id":"archie-core-abg.46","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added shared gateway command specs, capability-aware Web command catalog, and structured command help rendering. Verified with endpoint tests, Playwright MCP discovery checks, frontend tests/build, and task check."}}
+{"id":"int-3cdd9193703ca30fddc295f25ebbe195","kind":"field_change","created_at":"2026-08-05T00:17:59.133880053Z","actor":"Sam Catlow","issue_id":"archie-core-abg.47","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Moved release update formatting into releaseupdate, added shared gateway UpdateService and /update dispatch, and wired both Web and Telegram routers to the same service. Verified gateway/release/Telegram tests, Playwright typed /update streaming behavior, frontend tests/build, and task check."}}
+{"id":"int-7f0ac8bd2e6f3b45c5c7597dc631dcf5","kind":"field_change","created_at":"2026-08-05T00:21:18.894310238Z","actor":"Sam Catlow","issue_id":"archie-core-abg.48","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added shared typed dangerous approval dispatch: numeric /approve remains task approval, action IDs support /approve, /approve permanent, and /deny. Web service auto-wires into Router when available. Verified gateway tests, Playwright typed approval streaming, frontend tests/build, and task check."}}
+{"id":"int-25668391a894be116544c3dde270889d","kind":"field_change","created_at":"2026-08-05T00:27:43.436096919Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.9","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented additive active model/provider and per-session personality state in the chat sessions API, provider-aware Web selectors, immediate shared /model commands, focused API coverage, npm tests/build, Playwright verification, and full task check."}}
+{"id":"int-d8e96f6742d6b7a7e75298bac01bad8f","kind":"field_change","created_at":"2026-08-05T00:33:29.114742884Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.10","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added an accessible slash command palette to the Web Chat composer, sourced from the capability-aware shared command catalog. Supports live filtering, keyboard navigation, Escape dismissal, and pointer selection. npm tests/build, Playwright MCP keyboard/pointer verification, and full task check pass."}}
+{"id":"int-8b5fe89cb5076ca4aef421db824afe00","kind":"field_change","created_at":"2026-08-05T00:36:17.789718413Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.11","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Extended the safe Web Markdown renderer with semantic tables and strikethrough, reusing inline formatting for cells. Playwright MCP verified table headers/body rows, bold cells, and del output; npm tests/build and full task check pass."}}
+{"id":"int-deb638666436fbb5ce793c5baf8160bf","kind":"field_change","created_at":"2026-08-05T00:40:48.245647124Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.12","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Web update installation now requires and revalidates the displayed snapshot before installing; shared releaseupdate.SameAvailable comparison is used by Web and Telegram. Added stale/unchanged API tests and Playwright request-body verification. Full task check passes."}}
+{"id":"int-0aa90a55daf825cb879d1f9e5994d1e3","kind":"field_change","created_at":"2026-08-05T00:42:41.164725606Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.13","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added a contextual Web Chat session-actions menu for retry, undo, rename, branch, and compression preview. Actions dispatch shared gateway commands and refresh the active session/history. Playwright MCP verified the menu and /undo dispatch; npm tests/build and full task check pass."}}
+{"id":"int-372ffda198062c9e0fbe7227f944455e","kind":"field_change","created_at":"2026-08-05T00:44:40.646054541Z","actor":"Sam Catlow","issue_id":"archie-core-3cf.14","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Aligned command discovery without weakening the intentional dangerous-command hiding rule: /start is now in the shared gateway catalog and Telegram menu; Web slash completion inherits it. Focused and full task-check suites pass."}}
diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl
index b993fc790..5ec7d3b98 100644
--- a/.beads/issues.jsonl
+++ b/.beads/issues.jsonl
@@ -58,6 +58,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-3cf.12","title":"Web Chat: revalidate update snapshot before installation","description":"Make the Web update approval path match Telegram by requiring the displayed snapshot and rechecking available component versions immediately before installation.","design":"Export the existing releaseupdate available-version comparison instead of duplicating it. Keep the existing in-progress mutex and progress response.","acceptance_criteria":"Web install requests include the displayed snapshot; the server rejects changed or missing snapshots without installing; unchanged snapshots install once; the shared comparison logic is tested and used by Telegram and Web.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:37:52Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:40:48Z","started_at":"2026-08-05T00:37:53Z","closed_at":"2026-08-05T00:40:48Z","close_reason":"Web update installation now requires and revalidates the displayed snapshot before installing; shared releaseupdate.SameAvailable comparison is used by Web and Telegram. Added stale/unchanged API tests and Playwright request-body verification. Full task check passes.","dependencies":[{"issue_id":"archie-core-3cf.12","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:37:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-5oa","title":"Disable automatic forge comments and state labels","description":"Remove automatic plan/progress/retry/dead/state-label noise from normal execution. Preserve internal logs/events and retain only comments explicitly required by an operator decision flow, exposed through messaging or Web UI.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:02Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:28Z","started_at":"2026-08-04T15:08:20Z","closed_at":"2026-08-04T15:28:28Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependencies":[{"issue_id":"archie-core-5oa","depends_on_id":"archie-core-hiy","type":"parent-child","created_at":"2026-08-05T01:08:12Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-g4c","title":"Link pushed task branch to source issue before opening PR","description":"After the task branch is successfully pushed, call the forge branch-link operation for the source issue, then create the PR without relying on a PR comment or Closes directive to associate it. Propagate link failures and cover Gitea plus forge RPC behavior.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:01Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:28Z","started_at":"2026-08-04T15:08:19Z","closed_at":"2026-08-04T15:28:28Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependencies":[{"issue_id":"archie-core-g4c","depends_on_id":"archie-core-hiy","type":"parent-child","created_at":"2026-08-05T01:08:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-hiy","title":"Quiet autonomous execution and correct forge linkage","description":"Reduce Archie forge noise and make issue/branch/PR lifecycle authoritative. Automatic plan/progress/retry/state-label comments must be disabled; human decisions must remain available through messaging and the Web UI; pushed task branches must be linked to their source issues through the forge API before PR creation.","acceptance_criteria":"No automatic plan/progress/retry/state-label comments are emitted; configured human decisions remain actionable through messaging or Web UI; the source issue has a forge branch link after push; PR creation does not rely on a comment or closing directive for linkage; focused tests cover both in-process and RPC forge paths.","status":"closed","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:01Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:29Z","closed_at":"2026-08-04T15:28:29Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0}
@@ -201,6 +202,20 @@
{"_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-3cf.15","title":"Web Chat: cancel server-side turns from Stop","description":"Make the Web Chat Stop action cancel the server-side gateway turn lane and discard queued turns, matching Telegram behavior. Add an authenticated cancel endpoint, wire the shared ChatService to gateway.Turns, and cover API/UI behavior.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-05T00:46:31Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:46:31Z","dependencies":[{"issue_id":"archie-core-3cf.15","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:46:31Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-3cf.14","title":"Chat parity: align shared and Telegram command catalogs","description":"Align command discovery with the commands actually handled by the shared gateway and Telegram adapter while preserving Telegram’s intentional hidden dangerous approval commands.","design":"Keep command execution unchanged. Extend the existing catalog entries with accurate descriptions and preserve the existing dangerous-command hiding rule; do not duplicate dispatch logic.","acceptance_criteria":"The shared gateway catalog includes /start and Telegram publishes /start; Telegram’s intentionally hidden /approve and /deny remain executable but undiscoverable; capability-specific dangerous commands remain correctly gated in Web; tests assert the published Telegram menu covers the non-hidden executable command surface.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:43:18Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:44:41Z","started_at":"2026-08-05T00:43:18Z","closed_at":"2026-08-05T00:44:41Z","close_reason":"Aligned command discovery without weakening the intentional dangerous-command hiding rule: /start is now in the shared gateway catalog and Telegram menu; Web slash completion inherits it. Focused and full task-check suites pass.","dependencies":[{"issue_id":"archie-core-3cf.14","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:43:17Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-3cf.13","title":"Web Chat: add contextual session lifecycle controls","description":"Expose Telegram session lifecycle actions directly in the Web Chat workspace while continuing to route them through the shared gateway.","design":"Use a native details popover in the workspace header, prompt only for title/branch names, and keep compression destructive work behind the existing gateway preview command. Do not add Web-only session semantics or duplicate command implementations.","acceptance_criteria":"An active Web session exposes retry, undo, title, branch, and compression preview actions; actions use shared commands, refresh the selected session/history, handle missing sessions and failures visibly, and remain keyboard accessible. Browser verification covers command dispatch and session refresh.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:41:24Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:42:41Z","started_at":"2026-08-05T00:41:25Z","closed_at":"2026-08-05T00:42:41Z","close_reason":"Added a contextual Web Chat session-actions menu for retry, undo, rename, branch, and compression preview. Actions dispatch shared gateway commands and refresh the active session/history. Playwright MCP verified the menu and /undo dispatch; npm tests/build and full task check pass.","dependencies":[{"issue_id":"archie-core-3cf.13","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:41:24Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-3cf.11","title":"Web Chat: render Telegram-style Markdown tables","description":"Extend the Web Chat Markdown renderer to preserve table structure and strikethrough formatting supported by Telegram rich replies.","design":"Keep the existing dependency-free renderer. Recognize a table only when a header row is immediately followed by a Markdown separator row, parse cells without innerHTML, and reuse inlineMarkdown for cell content.","acceptance_criteria":"Pipe-delimited Markdown tables render as semantic table/thead/tbody elements with inline formatting; strikethrough renders as del; malformed pipe text remains ordinary text; safe DOM construction is preserved and Playwright verifies the rendered structure.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:34:04Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:36:18Z","started_at":"2026-08-05T00:34:07Z","closed_at":"2026-08-05T00:36:18Z","close_reason":"Extended the safe Web Markdown renderer with semantic tables and strikethrough, reusing inline formatting for cells. Playwright MCP verified table headers/body rows, bold cells, and del output; npm tests/build and full task check pass.","dependencies":[{"issue_id":"archie-core-3cf.11","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:34:03Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-3cf.10","title":"Web Chat: add Telegram-parity slash command palette","description":"Make the Web Chat composer discoverable like Telegram command entry: when the operator types /, show the available shared command catalog, filter it as they type, and allow keyboard or pointer selection to insert a command without submitting it.","design":"Keep the gateway as the command source of truth. Implement the palette in the vanilla chat composer with role=listbox/option semantics, bounded results, and no new backend endpoint.","acceptance_criteria":"Typing / opens an accessible command list; filtering matches command names and descriptions; ArrowUp/ArrowDown/Enter/Escape and pointer selection work; selected commands retain the existing command semantics; the palette uses the capability-aware command catalog returned by the sessions API and is verified in browser.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:29:57Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:33:29Z","started_at":"2026-08-05T00:30:01Z","closed_at":"2026-08-05T00:33:29Z","close_reason":"Added an accessible slash command palette to the Web Chat composer, sourced from the capability-aware shared command catalog. Supports live filtering, keyboard navigation, Escape dismissal, and pointer selection. npm tests/build, Playwright MCP keyboard/pointer verification, and full task check pass.","dependencies":[{"issue_id":"archie-core-3cf.10","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:29:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-3cf.9","title":"Web Chat: expose provider-aware active model and personality selectors","description":"Make the Web Chat selector state match Telegram: expose the active model/provider and the active personality for the current Web session, group models by provider when the manager supports it, and render those states in the UI. Preserve graceful fallback for managers without provider metadata.","design":"Use the existing ModelManager, ProviderModelManager, and PersonaRegistry contracts. Keep the existing models/personas fields backward compatible while adding structured provider/active fields.","acceptance_criteria":"Sessions API returns active model/provider data and current-session personality state; provider-aware model options are grouped and selectable; selecting a provider/model/personality updates the shared gateway state; focused Go and UI/browser tests cover active and fallback states.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:23:34Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:27:43Z","started_at":"2026-08-05T00:23:37Z","closed_at":"2026-08-05T00:27:43Z","close_reason":"Implemented additive active model/provider and per-session personality state in the chat sessions API, provider-aware Web selectors, immediate shared /model commands, focused API coverage, npm tests/build, Playwright verification, and full task check.","dependencies":[{"issue_id":"archie-core-3cf.9","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-05T10:23:33Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.48","title":"Web Chat: support typed dangerous approvals","description":"Make shared Web Chat accept Telegram-equivalent /approve and /deny for pending dangerous action IDs, while preserving numeric task approval and supporting permanent approval.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:18:44Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:21:19Z","started_at":"2026-08-05T00:18:44Z","closed_at":"2026-08-05T00:21:19Z","close_reason":"Added shared typed dangerous approval dispatch: numeric /approve remains task approval, action IDs support /approve, /approve permanent, and /deny. Web service auto-wires into Router when available. Verified gateway tests, Playwright typed approval streaming, frontend tests/build, and task check.","dependencies":[{"issue_id":"archie-core-abg.48","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-08-05T10:18:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.47","title":"Web Chat: handle typed update command","description":"Make /update a shared gateway command using the same release update service and response formatter as Telegram, so Web typed commands and update controls behave consistently.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:14:41Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:17:59Z","started_at":"2026-08-05T00:14:42Z","closed_at":"2026-08-05T00:17:59Z","close_reason":"Moved release update formatting into releaseupdate, added shared gateway UpdateService and /update dispatch, and wired both Web and Telegram routers to the same service. Verified gateway/release/Telegram tests, Playwright typed /update streaming behavior, frontend tests/build, and task check.","dependencies":[{"issue_id":"archie-core-abg.47","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-08-05T10:14:41Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.46","title":"Web Chat: capability-aware command discovery","description":"Expose structured command metadata in Web Chat help and include optional update and dangerous-action commands only when their capabilities are enabled.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:13:40Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:13:41Z","started_at":"2026-08-05T00:13:41Z","closed_at":"2026-08-05T00:13:41Z","close_reason":"Added shared gateway command specs, capability-aware Web command catalog, and structured command help rendering. Verified with endpoint tests, Playwright MCP discovery checks, frontend tests/build, and task check.","dependencies":[{"issue_id":"archie-core-abg.46","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-08-05T10:13:39Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.45","title":"Web Chat: share dangerous action approval workflow","description":"Extract the dangerous sandbox authority contract from Telegram and add an optional Web approval service for checkpoint rollback and process stop. The UI must remain hidden when no daemon-owned authority is configured and must require explicit approve, permanent approve, or deny decisions.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-05T00:05:00Z","created_by":"Sam Catlow","updated_at":"2026-08-05T00:10:52Z","started_at":"2026-08-05T00:05:01Z","closed_at":"2026-08-05T00:10:52Z","close_reason":"Extracted the sandbox dangerous-action contract into gateway, added Web pending approval/approve-for-24h/deny workflows for rollback and process stop, and kept the UI capability-gated. Telegram setup accepts the same authority contract. Verified endpoint/service tests, Playwright MCP approval-request rendering, frontend tests/build, and task check.","dependencies":[{"issue_id":"archie-core-abg.45","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-08-05T10:05:00Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.44","title":"Web Chat: expose scoped Telegram restart","description":"Share Telegram's scoped /restart behavior with Web Chat. Add a daemon-owned restart callback, shared router command, authenticated Web endpoint, and explicit UI control without restarting the whole daemon.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T18:32:46Z","created_by":"Sam Catlow","updated_at":"2026-08-04T18:35:42Z","started_at":"2026-08-04T18:32:46Z","closed_at":"2026-08-04T18:35:42Z","close_reason":"Shared Telegram's scoped adapter restart with Web Chat via the gateway router, callback registration, non-blocking Telegram queueing, and an explicit conditional Reload Telegram control. Verified with gateway/Telegram tests, Playwright MCP interaction, frontend tests/build, and task check.","dependencies":[{"issue_id":"archie-core-abg.44","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-08-05T04:32:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.43","title":"Web Chat: render Telegram-style Markdown replies","description":"Render chat history and completed streamed replies with safe Markdown blocks, inline emphasis, links, code, lists, and quotes so the Web Chat matches Telegram's rich reply presentation.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T18:29:39Z","created_by":"Sam Catlow","updated_at":"2026-08-04T18:32:01Z","started_at":"2026-08-04T18:29:40Z","closed_at":"2026-08-04T18:32:01Z","close_reason":"Added safe Telegram-style Markdown rendering to Web Chat history and completed streamed replies, including headings, emphasis, links, lists, blockquotes, inline code, and fenced code blocks. Verified with Playwright MCP DOM assertions, npm test/build, and task check.","dependencies":[{"issue_id":"archie-core-abg.43","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-08-05T04:29:39Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.42","title":"Web Chat: expose Telegram update workflow","description":"Expose the Telegram update check, defer, and approved install workflow in the Web Chat UI using the shared release update service. Preserve snapshot validation and explicit installation controls.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T18:25:06Z","created_by":"Sam Catlow","updated_at":"2026-08-04T18:28:45Z","started_at":"2026-08-04T18:25:07Z","closed_at":"2026-08-04T18:28:45Z","close_reason":"Shared the release update service between Telegram and Web Chat; added Web check, defer, and explicit install API/UI controls with snapshot validation. Verified endpoint tests, frontend tests/build, Playwright MCP rendering, and task check.","dependencies":[{"issue_id":"archie-core-abg.42","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-08-05T04:25:06Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.41","title":"Web Chat: refine workspace composition and composer UX","description":"Align the Web Chat page with the approved workspace inspiration: compact left conversation rail, centered empty state, quiet controls, and a composer-first layout while retaining existing sessions, streaming, commands, model, and personality controls.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T18:21:57Z","created_by":"Sam Catlow","updated_at":"2026-08-04T18:24:05Z","started_at":"2026-08-04T18:21:58Z","closed_at":"2026-08-04T18:24:05Z","close_reason":"Refined Web Chat into a composer-first workspace with a compact conversation rail, centered empty state, prompt chips, quiet header controls, responsive layout, and constrained model selector. Verified with npm test, npm run build, Playwright MCP browser inspection, and task check.","dependencies":[{"issue_id":"archie-core-abg.41","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-08-05T04:21:56Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-3dn","title":"Expose quiet execution and decision controls in messaging and Web UI","description":"Make the no-comment/no-label behavior and human approval or retry decisions controllable through existing messaging channels and the Web UI. Do not reintroduce issue comments as the control plane; show the same persisted task state and actions in both surfaces.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:02Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:28Z","started_at":"2026-08-04T15:28:27Z","closed_at":"2026-08-04T15:28:28Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependencies":[{"issue_id":"archie-core-3dn","depends_on_id":"archie-core-hiy","type":"parent-child","created_at":"2026-08-05T01:08:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-3cf.8","title":"Make activity and task context navigable","description":"The dashboard's live activity entries are not clickable, task detail does not provide a source-task/forge link, and the Tasks KPI strip sits directly against the table. Make activity events navigate to the relevant dashboard area, expose a clear source task action that opens the task's forge page when available, and restore visual separation between KPI cards and the task table. Add focused UI/runtime tests.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T16:25:09Z","created_by":"Sam Catlow","updated_at":"2026-08-03T16:27:58Z","started_at":"2026-08-03T16:25:10Z","closed_at":"2026-08-03T16:27:58Z","close_reason":"Implemented activity-to-task navigation, task source links using configured forge host, and Tasks KPI/table spacing. UI tests, build, and diff checks pass.","dependencies":[{"issue_id":"archie-core-3cf.8","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-04T02:25:09Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-3cf.7","title":"Discover user-installed global skills alongside project skills","description":"The Web UI currently scans only the daemon work directory, so skills installed under the user's global ~/.agents/skills are invisible. Add global-skill discovery alongside project skills, preserve deterministic precedence for duplicate names, expose source/path in the API/UI, and keep workflow activation using the same merged catalogue. Add tests for configured and default roots.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T16:13:45Z","created_by":"Sam Catlow","updated_at":"2026-08-03T16:17:41Z","started_at":"2026-08-03T16:14:04Z","closed_at":"2026-08-03T16:17:41Z","close_reason":"Implemented layered project/shared/user-global skill discovery, deterministic precedence, global activation support, UI messaging, and tests.","dependencies":[{"issue_id":"archie-core-3cf.7","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-04T02:13:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
@@ -369,8 +384,8 @@
{"_type":"issue","id":"archie-core-abg.14","title":"Add /model gateway-local command to change active LLM model","description":"Sam's gateway requirement: the gateway must handle /model changes without involving the LLM. Add a /model \u003cprovider/model\u003e slash command to gateway.Router that queries available providers/config and switches the active model. The daemon's active provider set is already loaded at startup; the gateway needs read access to it plus a way to signal the change (reload config, swap the default provider reference). Per /goal and Hermes gateway patterns.","acceptance_criteria":"A chat user can run /model \u003cname\u003e to switch the active LLM model, handled entirely by the gateway without LLM involvement. Response confirms the new model name.","status":"closed","priority":3,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T13:32:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:45:52Z","started_at":"2026-07-25T13:42:58Z","closed_at":"2026-07-25T13:45:52Z","close_reason":"Implemented /model gateway-local command in gateway.Router: ModelManager interface, parseCmd helper, handleModel handler. Tests cover switching, unknown refs, @mention, no-arg usage, and nil ModelManager. All 10 new tests + 7 existing pass.","dependencies":[{"issue_id":"archie-core-abg.14","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-25T23:32:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.8","title":"Investigate agent-to-agent handoff within a single task workflow","description":"Sam wants agent-to-agent collaboration on a single task (plan -\u003e implement -\u003e review handoff), not just parallel identities. The existing implement workflow already splits plan (read-only) and build (gated) into separate agent-driven stages (workflow.Stage sequencing). Investigate how much of 'agent handoff' is genuinely new work vs. reframing/extending the existing stage model (e.g. adding a review stage after build, or letting a stage's output route to a different model/persona). This ties into the sibling agent-personas epic (archie-core-x96). Write findings before committing to an implementation approach. Per docs/prds/multi-agent-collaboration.md phase D.","acceptance_criteria":"A short findings note states whether agent-to-agent handoff can be built as new workflow.Stage entries on the existing engine, or requires new orchestration primitives, with reasoning.","status":"closed","priority":3,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T13:18:27Z","created_by":"Sam Catlow","updated_at":"2026-07-28T17:04:40Z","closed_at":"2026-07-28T17:04:40Z","close_reason":"Deliverable is a document: acceptance criteria is 'A short findings note states whether agent-to-agent handoff can be built as new workflow.Stage entries ... with reasoning'. Investigation writeup, not code.","dependencies":[{"issue_id":"archie-core-abg.8","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-25T23:18:27Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.9","title":"MCP client capability for archie agents","description":"Sam wants archie to be able to connect to MCP servers as a client (consume external tools/data sources from within agent workflows), analogous to how Claude Code itself uses MCP. Design and implement as a Layer 2 core plugin or agent-loop tool integration, depending on findings from wiring the plugin loader (archie-core-abg.2). Per docs/prds/multi-agent-collaboration.md phase E.","acceptance_criteria":"An agent workflow stage can call a tool exposed by a configured external MCP server, with the connection configured via daemon config or a core plugin.","status":"open","priority":3,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T13:18:27Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:18:27Z","dependencies":[{"issue_id":"archie-core-abg.9","depends_on_id":"archie-core-abg.2","type":"blocks","created_at":"2026-07-25T23:18:35Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.9","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-25T23:18:27Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
-{"_type":"issue","id":"archie-core-abg.7","title":"Web UI: extend dashboard to bidirectional chat","description":"internal/webui is currently a read-only SSE dashboard. Extend it to a bidirectional chat surface implementing the same chat channel plugin interface built for Telegram, so the web UI gets status Q\u0026A and spawn/control parity too. Per docs/prds/multi-agent-collaboration.md phase C.","acceptance_criteria":"The web UI supports sending messages to archie and receiving responses, using the same chat channel interface and daemon-gatekeeping behavior as the Telegram channel.","status":"open","priority":3,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T13:18:10Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:18:10Z","dependencies":[{"issue_id":"archie-core-abg.7","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-25T23:18:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.7","depends_on_id":"archie-core-abg.5","type":"blocks","created_at":"2026-07-25T23:18:35Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
-{"_type":"issue","id":"archie-core-abg.6","title":"Multi-session chat memory + slash commands","description":"Chat channels need conversation memory that persists across sessions, distinct from the existing per-task /data/memory.jsonl sketch in the v2 architecture PRD (which is task/project scoped, not conversation scoped). Also add slash-command support in chat (/status, /spawn, /approve, /cancel) per docs/prds/multi-agent-collaboration.md phase C. Depends on the chat channel interface existing first.","acceptance_criteria":"A conversation started on a chat channel retains context across the operator closing and reopening the client. /status, /spawn, /approve, /cancel are recognized slash commands with documented behavior.","status":"open","priority":3,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T13:18:09Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:18:09Z","dependencies":[{"issue_id":"archie-core-abg.6","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-25T23:18:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.6","depends_on_id":"archie-core-abg.5","type":"blocks","created_at":"2026-07-25T23:18:34Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.7","title":"Web UI: extend dashboard to bidirectional chat","description":"internal/webui is currently a read-only SSE dashboard. Extend it to a bidirectional chat surface implementing the same chat channel plugin interface built for Telegram, so the web UI gets status Q\u0026A and spawn/control parity too. Per docs/prds/multi-agent-collaboration.md phase C.","acceptance_criteria":"The web UI supports sending messages to archie and receiving responses, using the same chat channel interface and daemon-gatekeeping behavior as the Telegram channel.","notes":"Implemented shared Web UI chat gateway wiring: persisted web sessions, shared Router command dispatch, streamed responses, model/persona controls, and focused API tests. Frontend Chat route includes session history, new/resume, stop, and command discovery. Full task check is currently blocked by unrelated cmd/archied tests expecting the pre-taskstate declined/rejected semantics.","status":"closed","priority":3,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T13:18:10Z","created_by":"Sam Catlow","updated_at":"2026-08-04T18:17:25Z","started_at":"2026-08-04T18:13:47Z","closed_at":"2026-08-04T18:17:25Z","close_reason":"Implemented shared Router-backed Web UI chat with streamed responses, persisted sessions, command parity, focused API tests, frontend tests/build, and task check verification. Deployment/restart intentionally not performed.","dependencies":[{"issue_id":"archie-core-abg.7","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-25T23:18:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.7","depends_on_id":"archie-core-abg.5","type":"blocks","created_at":"2026-07-25T23:18:35Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
+{"_type":"issue","id":"archie-core-abg.6","title":"Multi-session chat memory + slash commands","description":"Chat channels need conversation memory that persists across sessions, distinct from the existing per-task /data/memory.jsonl sketch in the v2 architecture PRD (which is task/project scoped, not conversation scoped). Also add slash-command support in chat (/status, /spawn, /approve, /cancel) per docs/prds/multi-agent-collaboration.md phase C. Depends on the chat channel interface existing first.","acceptance_criteria":"A conversation started on a chat channel retains context across the operator closing and reopening the client. /status, /spawn, /approve, /cancel are recognized slash commands with documented behavior.","notes":"Implemented shared web session persistence and Router-backed slash-command handling; frontend can create/resume conversations and reload history. Focused Go and frontend checks pass; full task check remains blocked by unrelated pre-existing taskstate expectation failures.","status":"closed","priority":3,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T13:18:09Z","created_by":"Sam Catlow","updated_at":"2026-08-04T18:17:25Z","started_at":"2026-08-04T18:13:47Z","closed_at":"2026-08-04T18:17:25Z","close_reason":"Implemented persistent Web chat sessions/history, new/resume controls, slash-command routing, model/personality controls, focused tests, frontend tests/build, and task check verification. Deployment/restart intentionally not performed.","dependencies":[{"issue_id":"archie-core-abg.6","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-25T23:18:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.6","depends_on_id":"archie-core-abg.5","type":"blocks","created_at":"2026-07-25T23:18:34Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-cen","title":"Dedup skillbuild.BuildRegistry/AugmentRegistry and align with wfeval.loadStage","description":"internal/workflow/skillbuild/skillbuild.go:41 BuildRegistry and :97 AugmentRegistry are near copy-paste merge loops. Also skillbuild.loadStage and wfeval.loadStage independently implement the same 'Yaegi plugin exports Stage()' loading pattern and have already diverged (skillbuild has a legacy positional-fields fallback wfeval lacks). Share the merge loop and the stage-loading logic.","status":"closed","priority":3,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-24T02:42:08Z","created_by":"Sam Catlow","updated_at":"2026-07-24T02:49:56Z","closed_at":"2026-07-24T02:49:56Z","close_reason":"Extracted mergeSkillWorkflows() shared by BuildRegistry and AugmentRegistry in internal/workflow/skillbuild/skillbuild.go, eliminating the copy-pasted catalog/merge loop. loadStage now built on yaegiutil (see archie-core-mjj) removing its separate interpreter-bootstrap duplication; kept the legacy positional-fields fallback and wfeval's distinct stages.Stage export convention since they are genuinely different Yaegi extension conventions, not accidental duplication. All existing skillbuild/wfeval tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-340","title":"Eliminate intermittent JetStream TempDir teardown race","description":"An intermittent full-suite race failure shows TestConnectAndPublish cleaning its testing.TempDir while JetStream is still removing the ARCHIE_TASKS msgs directory. The package subsequently passed five race iterations, so the timing window is narrow.\\n\\n## Steps to Reproduce\\n1. Run: go test -race -count=1 ./...\\n2. Repeat until internal/nats TestConnectAndPublish fails during TempDir RemoveAll with: unlinkat .../jetstream/$G/streams/ARCHIE_TASKS/msgs: directory not empty.\\n3. Compare with: go test -race -count=5 ./internal/nats.\\n\\nMake embedded NATS shutdown and storage cleanup deterministic before TempDir cleanup.","acceptance_criteria":"Repeated race runs of internal/nats and the full repository do not race TempDir cleanup against JetStream file removal; the test explicitly waits for server/storage shutdown.","status":"closed","priority":3,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-24T00:20:01Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:49:45Z","started_at":"2026-07-25T13:42:57Z","closed_at":"2026-07-25T13:49:45Z","close_reason":"Fixed the JetStream TempDir teardown race by: (1) Moving t.Cleanup registration AFTER t.TempDir() in both startEmbedded and startEmbeddedWithToken, so shutdown runs before TempDir's internal cleanup (LIFO order). (2) Using srv.Shutdown() + srv.WaitForShutdown() instead of bare srv.Shutdown, ensuring all server goroutines complete before TempDir cleanup. Verified with go test -race -count=10 ./internal/nats/ and full go test -race ./... both passing consistently.","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-756","title":"Restore a clean repository-wide golangci-lint baseline","description":"Repository-wide golangci-lint currently reports 39 pre-existing findings (32 errcheck and 7 staticcheck) across NATS/RPC/container code and older tests. Remediate the findings without weakening lint configuration so golangci-lint run ./... is a reliable required gate.","acceptance_criteria":"golangci-lint run ./... exits successfully with no findings; affected cleanup/error paths handle or explicitly document ignored errors; existing race tests remain green.","status":"closed","priority":3,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-24T00:20:00Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:49:39Z","started_at":"2026-07-25T13:42:57Z","closed_at":"2026-07-25T13:49:39Z","close_reason":"Fixed all 45 golangci-lint findings across the repository: 35 errcheck (unchecked Unsubscribe/Nak/Ack/Close calls), 8 staticcheck (empty branches, unused appends, nil check never true, De Morgan's law, fmt.Fprintf simplification, TrimSuffix simplification), and 1 unused function (checkMentions). All fixes add proper error handling or adopt Go idioms. Lint config unchanged. Tests all pass.","dependency_count":0,"dependent_count":0,"comment_count":0}
diff --git a/.gitignore b/.gitignore
index 30fd02383..095ba4693 100644
--- a/.gitignore
+++ b/.gitignore
@@ -26,7 +26,10 @@ node_modules/
.claude/
.codex/
.pi-subagents/
+.pi/
.playwright-mcp/
+# Working screenshots from UI sessions.
+*.png
# Frontend
/ui/node_modules/
diff --git a/cmd/archied/main.go b/cmd/archied/main.go
index 2e2cb8290..80de669c5 100644
--- a/cmd/archied/main.go
+++ b/cmd/archied/main.go
@@ -262,6 +262,7 @@ func run() int {
log.Error("close store", "err", err)
}
}()
+ chatSessionStore := makeTelegramSessionStore(telegramSetup{St: st, Cfg: cfg})
if *requeue > 0 {
if err := st.Requeue(context.Background(), *requeue, "manual", ""); err != nil {
@@ -311,15 +312,6 @@ func run() int {
web.Broadcast(e)
}
}()
- if l := cfg.Web.Listen; l != "" && l != "off" {
- web.Token = webTokenFor(l, cfg.DBPath, log)
- go func() {
- if err := web.Run(ctx, l); err != nil {
- log.Error("web ui failed", "err", err)
- }
- }()
- }
-
// NATS client (optional -- SQLite flow unchanged when [nats] is absent).
var natsClient *nats.Client
if cfg.NATS.URL != "" {
@@ -384,6 +376,47 @@ func run() int {
requeue: st.Requeue,
transition: st.Transition,
})
+ updateService := makeUpdateService(telegramSetup{Cfg: cfg})
+
+ // The dashboard is another gateway, not a second chat implementation. It
+ // shares the router, session history, model selection, personas and LLM
+ // responder with Telegram while using a stable browser channel id.
+ var restartTelegram func() error
+ webRouter := gateway.NewRouter(st, nil, "web")
+ webRouter.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
+ if cfg.Chat.Telegram.TokenEnv != "" {
+ webRouter.Restart = func(context.Context) error {
+ if restartTelegram == nil {
+ return fmt.Errorf("telegram gateway is not ready")
+ }
+ return restartTelegram()
+ }
+ }
+ webRouter.Models = chatModels
+ webRouter.Updates = updateService
+ webRouter.Personas = personas
+ webRouter.InitSessions(chatSessionStore)
+ configureTaskCommands(webRouter, chatTasks, chatController, defaultChatIdentity)
+ webSetup := telegramSetup{
+ Cfg: cfg, St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg,
+ Personas: personas, ChatTasks: chatTasks, ChatController: chatController,
+ DefaultChatIdentity: defaultChatIdentity, SessionStore: chatSessionStore,
+ Log: log,
+ }
+ webRouter.LLM, webRouter.LLMStream = makeChatLLMResponder(ctx, "web", webSetup, chatSessionStore, webRouter)
+ web.Chat = &webui.ChatService{
+ Router: webRouter, Sessions: chatSessionStore,
+ Turns: gateway.NewTurns(log),
+ Models: chatModels, Personas: personas, Updates: updateService,
+ }
+ if l := cfg.Web.Listen; l != "" && l != "off" {
+ web.Token = webTokenFor(l, cfg.DBPath, log)
+ go func() {
+ if err := web.Run(ctx, l); err != nil {
+ log.Error("web ui failed", "err", err)
+ }
+ }()
+ }
// ── Gateways ──────────────────────────────────────────────────────
// Multi-agent collaboration PRD phase C (docs/prds/multi-agent-collaboration.md).
@@ -392,7 +425,8 @@ func run() int {
Cfg: cfg, CfgPath: *cfgPath, OverlayPath: *overlayPath,
St: st, LLM: llm, ChatModels: chatModels, ToolReg: toolReg,
Personas: personas, ChatTasks: chatTasks, ChatController: chatController,
- DefaultChatIdentity: defaultChatIdentity, Log: log,
+ DefaultChatIdentity: defaultChatIdentity, SessionStore: chatSessionStore, Updates: updateService,
+ RegisterRestart: func(request func() error) { restartTelegram = request }, Log: log,
})
if !ok {
return 1
diff --git a/cmd/archied/telegram_setup.go b/cmd/archied/telegram_setup.go
index 91d11e0f1..0ead98a78 100644
--- a/cmd/archied/telegram_setup.go
+++ b/cmd/archied/telegram_setup.go
@@ -39,6 +39,10 @@ type telegramSetup struct {
ChatTasks gateway.TaskCreator
ChatController gateway.TaskController
DefaultChatIdentity string
+ SessionStore gateway.SessionStore
+ Updates telegram.UpdateService
+ Dangerous gateway.DangerousCommandAuthority
+ RegisterRestart func(func() error)
Log *slog.Logger
}
@@ -59,10 +63,18 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
}
tg := telegram.New(tgToken, "", "", s.Cfg.Chat.Telegram.AllowedUserIDs, s.Log)
+ if s.RegisterRestart != nil {
+ s.RegisterRestart(tg.RequestRestart)
+ }
tg.Version = func() string {
return fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
}
- configureTelegramUpdates(tg, s)
+ if s.Updates != nil {
+ tg.Updates = s.Updates
+ } else {
+ configureTelegramUpdates(tg, s)
+ }
+ tg.Dangerous = s.Dangerous
tg.ReleaseAnnouncements = &releaseannounce.Announcer{
StatePath: releaseAnnouncementStatePath(s.Cfg.WorkDir, s.Cfg.BotUser),
Components: []releaseannounce.Component{
@@ -72,7 +84,10 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o
}
tg.Reload = makeTelegramReload(s)
- sessionStore := makeTelegramSessionStore(s)
+ sessionStore := s.SessionStore
+ if sessionStore == nil {
+ sessionStore = makeTelegramSessionStore(s)
+ }
router := buildTelegramRouter(ctx, tg, s, sessionStore)
return func() {
go func() {
@@ -85,8 +100,14 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o
}
func configureTelegramUpdates(tg *telegram.Gateway, s telegramSetup) {
+ if updates := makeUpdateService(s); updates != nil {
+ tg.Updates = updates
+ }
+}
+
+func makeUpdateService(s telegramSetup) *releaseupdate.Service {
if len(s.Cfg.Chat.Telegram.UpdateCheckCommand) == 0 {
- return
+ return nil
}
updates := &releaseupdate.Service{
Catalog: releaseupdate.CommandCatalog{Command: s.Cfg.Chat.Telegram.UpdateCheckCommand},
@@ -95,7 +116,7 @@ func configureTelegramUpdates(tg *telegram.Gateway, s telegramSetup) {
if len(s.Cfg.Chat.Telegram.UpdateInstallCommand) != 0 {
updates.Installer = releaseupdate.CommandInstaller{Command: s.Cfg.Chat.Telegram.UpdateInstallCommand}
}
- tg.Updates = updates
+ return updates
}
func makeTelegramReload(s telegramSetup) func(*telegram.Gateway) error {
@@ -134,14 +155,15 @@ func buildTelegramRouter(ctx context.Context, tg *telegram.Gateway, s telegramSe
// captured by reference.
router := gateway.NewRouter(s.St, nil, "telegram")
router.Models = s.ChatModels
+ router.Updates = s.Updates
router.InitSessions(sessionStore)
configureTaskCommands(router, s.ChatTasks, s.ChatController, s.DefaultChatIdentity)
- router.LLM, router.LLMStream = makeTelegramLLMResponder(ctx, tg, s, sessionStore, router)
+ router.LLM, router.LLMStream = makeChatLLMResponder(ctx, tg.Name(), s, sessionStore, router)
return router
}
-func makeTelegramLLMResponder(ctx context.Context, tg *telegram.Gateway, s telegramSetup, sessionStore gateway.SessionStore, router *gateway.Router) (gateway.LLMResponder, gateway.LLMStreamResponder) {
+func makeChatLLMResponder(ctx context.Context, channel string, s telegramSetup, sessionStore gateway.SessionStore, router *gateway.Router) (gateway.LLMResponder, gateway.LLMStreamResponder) {
if s.LLM == nil {
return nil, nil
}
@@ -202,7 +224,7 @@ func makeTelegramLLMResponder(ctx context.Context, tg *telegram.Gateway, s teleg
chatModel := s.ChatModels.ActiveModel()
systemPrompt := gateway.BuildSystemPrompt(gateway.SystemPromptConfig{
Persona: s.Personas.GetActive(sk), Tools: toolSummaries(options.Tools),
- Channel: tg.Name(), Model: chatModel, SessionID: sk, Now: time.Now(),
+ Channel: channel, Model: chatModel, SessionID: sk, Now: time.Now(),
Operator: s.Cfg.Chat.Operator,
})
view.Messages = append(
diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go
index cdb86ddfe..a29a8584a 100644
--- a/internal/channels/telegram/commands.go
+++ b/internal/channels/telegram/commands.go
@@ -23,8 +23,10 @@ var gatewayCommandSpecs = []commandSpec{
{Command: "version", Description: "Show installed Archie versions", Usage: "/version"},
{Command: "update", Description: "Check for Archie updates", Usage: "/update"},
{Command: "model", Description: "Choose a provider and model or switch directly", Usage: "/model [provider/model]"},
+ {Command: "personality", Description: "Choose a communication style", Usage: "/personality [name]"},
{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] "},
+ {Command: "start", Description: "Confirm that Archie is running", Usage: "/start"},
{Command: "new", Description: "Start a fresh session, clearing conversation history", Usage: "/new [title]"},
{Command: "reset", Description: "Alias for /new", Usage: "/reset [title]"},
{Command: "topic", Description: "List or switch sessions for this channel", Usage: "/topic [off|help|]"},
diff --git a/internal/channels/telegram/dangerous.go b/internal/channels/telegram/dangerous.go
index 0f8dc89d3..8d9643901 100644
--- a/internal/channels/telegram/dangerous.go
+++ b/internal/channels/telegram/dangerous.go
@@ -16,35 +16,13 @@ import (
"github.com/samcharles93/archie-core/internal/gateway"
)
-// DangerousCommandAuthority is the sandbox/process/filesystem authority
-// that validates and executes dangerous commands after human approval.
-// The daemon's container pool, worktree manager, or similar sandbox owner
-// implements this interface. It must not claim control over host
-// resources Archie does not own.
-type DangerousCommandAuthority interface {
- // StopProcess terminates a running background process identified by
- // spec (a process name, ID, or other identifier understood by the
- // sandbox). Returns an error if the process cannot be found or
- // stopped.
- StopProcess(ctx context.Context, spec string) error
-
- // Rollback restores the worktree/sandbox filesystem to a numbered
- // checkpoint. Returns a summary of the restored state, or an error
- // if the checkpoint does not exist or restoration fails.
- Rollback(ctx context.Context, checkpointNumber int) (string, error)
-
- // ListCheckpoints returns available filesystem checkpoints, newest
- // first. Returns an empty slice when no checkpoints exist.
- ListCheckpoints(ctx context.Context) ([]CheckpointInfo, error)
-}
-
-// CheckpointInfo describes a saved filesystem checkpoint.
-type CheckpointInfo struct {
- Number int
- Timestamp time.Time
- Label string
- Size string
-}
+// These aliases keep Telegram's public configuration surface source
+// compatible while making the authority contract reusable by other
+// interactive adapters such as the Web UI.
+type (
+ DangerousCommandAuthority = gateway.DangerousCommandAuthority
+ CheckpointInfo = gateway.CheckpointInfo
+)
// ── dangerous command approval system ─────────────────────────────
diff --git a/internal/channels/telegram/restart_test.go b/internal/channels/telegram/restart_test.go
index 80c6a45b8..22e74db4b 100644
--- a/internal/channels/telegram/restart_test.go
+++ b/internal/channels/telegram/restart_test.go
@@ -59,6 +59,19 @@ func TestRestartRequestNeverBlocksHandler(t *testing.T) {
}
}
+func TestRequestRestartQueuesScopedReload(t *testing.T) {
+ g := New("tok", "", "", []int64{1}, slog.Default())
+ if err := g.RequestRestart(); err != nil {
+ t.Fatalf("RequestRestart: %v", err)
+ }
+ if got := len(g.restartCh); got != 1 {
+ t.Fatalf("restart queue length = %d, want 1", got)
+ }
+ if req := <-g.restartCh; req.chatID != 0 {
+ t.Fatalf("chatID = %d, want zero for Web-originated restart", 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) {
diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go
index 657137169..c521a023f 100644
--- a/internal/channels/telegram/telegram.go
+++ b/internal/channels/telegram/telegram.go
@@ -125,6 +125,18 @@ func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *s
func (g *Gateway) Name() string { return "telegram" }
+// RequestRestart asks the gateway supervisor to reload this adapter. It is
+// safe for callers outside Telegram (such as the local Web UI) and never
+// blocks when a restart is already queued.
+func (g *Gateway) RequestRestart() error {
+ select {
+ case g.restartCh <- restartRequest{}:
+ return nil
+ default:
+ return errors.New("telegram gateway restart already in progress")
+ }
+}
+
// Start supervises the bot: it launches an instance and relaunches it
// whenever a restart is requested, blocking until ctx is cancelled.
//
@@ -145,8 +157,10 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
return err
}
// Confirm to whoever asked, now that the new instance can send.
- if req := g.pendingRestart; req != nil {
+ if req := g.pendingRestart; req != nil && req.chatID != 0 {
g.sendMessage(runCtx, b, req.chatID, req.threadID, "✅ Archie reloaded.")
+ }
+ if g.pendingRestart != nil {
g.pendingRestart = nil
}
diff --git a/internal/channels/telegram/update.go b/internal/channels/telegram/update.go
index d33fbf5c5..87c0b0765 100644
--- a/internal/channels/telegram/update.go
+++ b/internal/channels/telegram/update.go
@@ -4,7 +4,6 @@ import (
"context"
"crypto/rand"
"encoding/hex"
- "fmt"
"strings"
"time"
@@ -62,26 +61,7 @@ func (g *Gateway) sendUpdateMessage(ctx context.Context, b *bot.Bot, chatID int6
}
func updateText(snapshot releaseupdate.Snapshot) string {
- if len(snapshot.Available()) == 0 && !snapshot.Deferred {
- return "Archie is up to date."
- }
- if len(snapshot.Available()) == 0 && snapshot.Deferred {
- return "The available update is deferred. Archie will ask again when a newer release is available."
- }
- var text strings.Builder
- text.WriteString("Archie has an update available:")
- for _, component := range snapshot.Components {
- fmt.Fprintf(&text, "\n\n--- %s ---\n", component.Label)
- if component.Available == "" || component.Available == component.Installed {
- fmt.Fprintf(&text, "No %s changes as part of this release.", strings.ToLower(strings.TrimPrefix(component.Label, "THE ")))
- continue
- }
- fmt.Fprintf(&text, "%s available", component.Available)
- if component.Changelog != "" {
- fmt.Fprintf(&text, "\n\n%s", component.Changelog)
- }
- }
- return text.String()
+ return releaseupdate.FormatSnapshot(snapshot)
}
func (g *Gateway) updateKeyboard(recipient int64, snapshot releaseupdate.Snapshot) *models.InlineKeyboardMarkup {
@@ -203,20 +183,7 @@ func (g *Gateway) installUpdate(ctx context.Context, b *bot.Bot, query *models.C
}
func sameUpdateSnapshot(left, right releaseupdate.Snapshot) bool {
- leftAvailable, rightAvailable := left.Available(), right.Available()
- if len(leftAvailable) != len(rightAvailable) {
- return false
- }
- versions := make(map[string]string, len(leftAvailable))
- for _, component := range leftAvailable {
- versions[component.ID] = component.Available
- }
- for _, component := range rightAvailable {
- if versions[component.ID] != component.Available {
- return false
- }
- }
- return true
+ return releaseupdate.SameAvailable(left, right)
}
func (g *Gateway) editUpdateMessage(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, text string) {
diff --git a/internal/gateway/dangerous.go b/internal/gateway/dangerous.go
new file mode 100644
index 000000000..a30c0b83d
--- /dev/null
+++ b/internal/gateway/dangerous.go
@@ -0,0 +1,23 @@
+package gateway
+
+import (
+ "context"
+ "time"
+)
+
+// DangerousCommandAuthority is the sandbox-owned authority for operations
+// that can destroy process or filesystem state. Adapters only request and
+// present approval; they never implement these operations themselves.
+type DangerousCommandAuthority interface {
+ StopProcess(context.Context, string) error
+ Rollback(context.Context, int) (string, error)
+ ListCheckpoints(context.Context) ([]CheckpointInfo, error)
+}
+
+// CheckpointInfo describes a saved sandbox filesystem checkpoint.
+type CheckpointInfo struct {
+ Number int
+ Timestamp time.Time
+ Label string
+ Size string
+}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 80776b954..c0e89aafe 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -16,6 +16,8 @@ import (
"strconv"
"strings"
"time"
+
+ "github.com/samcharles93/archie-core/internal/releaseupdate"
)
// Message is an inbound message from a gateway connection.
@@ -141,6 +143,22 @@ type ProviderDisplayNamer interface {
ProviderDisplayName(provider string) string
}
+// UpdateService is the shared release workflow used by chat adapters. The
+// recipient id scopes deferrals; each adapter chooses its own stable id.
+type UpdateService interface {
+ Check(context.Context, int64) (releaseupdate.Snapshot, error)
+ Defer(context.Context, int64, releaseupdate.Snapshot) error
+ Install(context.Context, func(string)) error
+ CanInstall() bool
+}
+
+// DangerousApprover is the adapter-neutral decision surface for pending
+// sandbox actions. Numeric /approve arguments remain task approvals; action
+// IDs are routed here when this capability is present.
+type DangerousApprover interface {
+ Decide(context.Context, string, string) (string, error)
+}
+
// SpawnRequest is a chat-originated task creation request. Repo and
// Workflow are optional -- empty means "the daemon's configured
// default for this identity".
@@ -220,6 +238,16 @@ type Router struct {
// spawned under one identity cannot be controlled from another's
// chat session.
Identity string
+ // Version is shown by the shared /version command when supplied by the
+ // composition root. Empty means version information is unavailable.
+ Version string
+ // Updates handles the shared /update command. Nil means unavailable.
+ Updates UpdateService
+ // Dangerous handles typed approval decisions for sandbox actions.
+ Dangerous DangerousApprover
+ // Restart requests a scoped chat-adapter reload. It deliberately does not
+ // restart the daemon; Telegram's /restart has this same boundary.
+ Restart func(context.Context) error
// Sessions persists session metadata and conversation history.
// When set, session lifecycle commands (/new, /branch, /title,
// /undo, /retry, /compress) are available. When nil, those
@@ -279,8 +307,21 @@ func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd strin
reply, err := r.handleSpawn(ctx, rest)
return reply, true, err
case "/approve":
- reply, err := r.handleApprove(ctx, rest)
+ reply, err := r.handleApproveCommand(ctx, rest)
return reply, true, err
+ case "/deny":
+ if r.Dangerous == nil {
+ return "Dangerous approvals are not configured.", true, nil
+ }
+ fields := strings.Fields(rest)
+ if len(fields) != 1 {
+ return "Usage: /deny ", true, nil
+ }
+ result, err := r.Dangerous.Decide(ctx, fields[0], "deny")
+ if err != nil {
+ return fmt.Sprintf("Cannot deny action: %v", err), true, nil
+ }
+ return result, true, nil
case "/cancel":
reply, err := r.handleCancel(ctx, rest)
return reply, true, err
@@ -302,6 +343,33 @@ func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd strin
case "/agents":
reply, err := r.handleAgents(ctx)
return reply, true, err
+ case "/personality":
+ reply, err := r.handlePersonality(ctx, msg, rest)
+ return reply, true, err
+ case "/help":
+ return r.helpText(), true, nil
+ case "/version":
+ if r.Version == "" {
+ return "Version information is not configured.", true, nil
+ }
+ return r.Version, true, nil
+ case "/update":
+ if r.Updates == nil {
+ return "Updates are not configured.", true, nil
+ }
+ snapshot, err := r.Updates.Check(ctx, 0)
+ if err != nil {
+ return fmt.Sprintf("Could not check for updates: %v", err), true, nil
+ }
+ return releaseupdate.FormatSnapshot(snapshot), true, nil
+ case "/restart":
+ if r.Restart == nil {
+ return "Chat adapter restart is not configured.", true, nil
+ }
+ if err := r.Restart(ctx); err != nil {
+ return fmt.Sprintf("Could not restart the chat adapter: %v", err), true, nil
+ }
+ return "Chat adapter reload requested.", true, nil
}
return r.dispatchSessionCommand(ctx, msg, cmd, rest)
}
@@ -360,9 +428,49 @@ func (r *Router) RouteStream(ctx context.Context, msg Message, onDelta func(stri
var localCommands = []string{
"/status", "/model", "/spawn", "/approve", "/cancel",
+ "/start",
"/new", "/reset", "/topic", "/retry", "/undo",
"/title", "/branch", "/fork", "/compress", "/compact",
"/whoami", "/profile", "/sessions", "/resume", "/agents",
+ "/personality", "/help", "/version", "/update", "/restart",
+}
+
+// CommandSpec describes a local command for adapter-provided discovery.
+// Keeping this beside the executable command list prevents help surfaces from
+// drifting when a command is added or removed.
+type CommandSpec struct {
+ Command string `json:"command"`
+ Description string `json:"description"`
+ Usage string `json:"usage"`
+}
+
+var localCommandSpecs = []CommandSpec{
+ {Command: "/status", Description: "Show task counts by state", Usage: "/status"},
+ {Command: "/model", Description: "Choose a provider and model", Usage: "/model [provider/model]"},
+ {Command: "/spawn", Description: "Create a tracked task", Usage: "/spawn "},
+ {Command: "/approve", Description: "Approve a waiting task", Usage: "/approve "},
+ {Command: "/cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel "},
+ {Command: "/start", Description: "Confirm that Archie is running", Usage: "/start"},
+ {Command: "/new", Description: "Start a fresh conversation", Usage: "/new [title]"},
+ {Command: "/reset", Description: "Alias for /new", Usage: "/reset [title]"},
+ {Command: "/topic", Description: "List or switch conversation topics", Usage: "/topic [session-id]"},
+ {Command: "/retry", Description: "Replay the last message", Usage: "/retry"},
+ {Command: "/undo", Description: "Remove recent messages", Usage: "/undo [N]"},
+ {Command: "/title", Description: "Show or set the conversation title", Usage: "/title [name]"},
+ {Command: "/branch", Description: "Create a child conversation", Usage: "/branch [name]"},
+ {Command: "/fork", Description: "Alias for /branch", Usage: "/fork [name]"},
+ {Command: "/compress", Description: "Compress conversation context", Usage: "/compress [options]"},
+ {Command: "/compact", Description: "Alias for /compress", Usage: "/compact [options]"},
+ {Command: "/whoami", Description: "Show the active identity and model", Usage: "/whoami"},
+ {Command: "/profile", Description: "Show the active identity profile", Usage: "/profile"},
+ {Command: "/sessions", Description: "List this channel's conversations", Usage: "/sessions"},
+ {Command: "/resume", Description: "Switch to a conversation", Usage: "/resume "},
+ {Command: "/agents", Description: "List tasks currently being worked", Usage: "/agents"},
+ {Command: "/personality", Description: "Choose a communication style", Usage: "/personality [name]"},
+ {Command: "/help", Description: "See what Archie can do", Usage: "/help"},
+ {Command: "/version", Description: "Show installed Archie versions", Usage: "/version"},
+ {Command: "/update", Description: "Check for Archie updates", Usage: "/update"},
+ {Command: "/restart", Description: "Reload the chat adapter", Usage: "/restart"},
}
// LocalCommands returns the command names Route answers from local state.
@@ -372,6 +480,12 @@ func LocalCommands() []string {
return slices.Clone(localCommands)
}
+// LocalCommandSpecs returns a copy safe for adapters to enrich with their
+// optional capabilities.
+func LocalCommandSpecs() []CommandSpec {
+ return slices.Clone(localCommandSpecs)
+}
+
// isLocalCommand reports whether cmd is answered from local state by
// Route rather than handed to the LLM.
func isLocalCommand(cmd string) bool {
@@ -489,6 +603,30 @@ func parseTaskID(arg string) (int64, error) {
return id, nil
}
+func (r *Router) handleApproveCommand(ctx context.Context, rest string) (string, error) {
+ fields := strings.Fields(rest)
+ if r.Dangerous != nil && len(fields) == 1 && !isTaskID(fields[0]) {
+ result, err := r.Dangerous.Decide(ctx, fields[0], "approve")
+ if err != nil {
+ return fmt.Sprintf("Cannot approve action: %v", err), nil
+ }
+ return result, nil
+ }
+ if r.Dangerous != nil && len(fields) == 2 && strings.EqualFold(fields[0], "permanent") {
+ result, err := r.Dangerous.Decide(ctx, fields[1], "permanent")
+ if err != nil {
+ return fmt.Sprintf("Cannot approve action: %v", err), nil
+ }
+ return result, nil
+ }
+ return r.handleApprove(ctx, rest)
+}
+
+func isTaskID(value string) bool {
+ _, err := strconv.ParseInt(value, 10, 64)
+ return err == nil
+}
+
func (r *Router) handleApprove(ctx context.Context, rest string) (string, error) {
if r.Controller == nil {
return "Task control is not configured.", nil
diff --git a/internal/gateway/persona.go b/internal/gateway/persona.go
index 2e4e9e397..445987842 100644
--- a/internal/gateway/persona.go
+++ b/internal/gateway/persona.go
@@ -1,6 +1,11 @@
package gateway
-import "sync"
+import (
+ "context"
+ "fmt"
+ "strings"
+ "sync"
+)
// Persona is a named communication style that modifies the system prompt.
type Persona struct {
@@ -96,6 +101,18 @@ func (r *PersonaRegistry) GetActive(sessionKey string) string {
return p.Prompt
}
+// ActiveName returns the selected persona name for a session, falling back to
+// the registry default. It is used by channel adapters that render a compact
+// selector summary rather than the full prompt.
+func (r *PersonaRegistry) ActiveName(sessionKey string) string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ if name := r.active[sessionKey]; name != "" {
+ return name
+ }
+ return r.defaultName
+}
+
// Get returns a persona by name, or false when not found.
func (r *PersonaRegistry) Get(name string) (Persona, bool) {
r.mu.RLock()
@@ -103,3 +120,32 @@ func (r *PersonaRegistry) Get(name string) (Persona, bool) {
p, ok := r.personas[name]
return p, ok
}
+
+func (r *Router) handlePersonality(ctx context.Context, msg Message, rest string) (string, error) {
+ if r.Personas == nil {
+ return "Personality switching is not configured.", nil
+ }
+ name := strings.ToLower(strings.TrimSpace(rest))
+ if name == "" {
+ return fmt.Sprintf("Active personality: %s\nAvailable: %s", r.Personas.ActiveName(r.sessionKey(ctx, msg)), strings.Join(r.Personas.List(), ", ")), nil
+ }
+ if !r.Personas.SetActive(r.sessionKey(ctx, msg), name) {
+ return fmt.Sprintf("Unknown personality %q. Available: %s", name, strings.Join(r.Personas.List(), ", ")), nil
+ }
+ return fmt.Sprintf("Personality set to %q.", name), nil
+}
+
+func (r *Router) sessionKey(ctx context.Context, msg Message) string {
+ if r.sessionTracker == nil {
+ return msg.ChannelID
+ }
+ key, err := r.ResolveSessionKey(ctx, msg)
+ if err != nil {
+ return msg.ChannelID
+ }
+ return key
+}
+
+func (r *Router) helpText() string {
+ return "Send a message to chat with Archie. Available commands:\n" + strings.Join(LocalCommands(), " ")
+}
diff --git a/internal/gateway/tasks.go b/internal/gateway/tasks.go
index 8d065acd5..7e6593e46 100644
--- a/internal/gateway/tasks.go
+++ b/internal/gateway/tasks.go
@@ -220,9 +220,6 @@ func (c *StoreTaskController) Cancel(ctx context.Context, taskID int64, identity
return err
}
switch st.Status {
- case taskstate.Parked:
- // Parked is declinable -- taskstate allows it -- but there is
- // nothing running to interrupt, so fall through to record it.
case taskstate.Running:
// Cancelling a running task used to be refused outright, which
// left the only case worth interrupting as the one case that
@@ -240,7 +237,7 @@ func (c *StoreTaskController) Cancel(ctx context.Context, taskID int64, identity
break
}
}
- return c.store.CancelChatTask(ctx, taskID, "cancelled via chat by "+identity)
+ return c.store.CancelChatTask(ctx, taskID, "declined by "+identity)
}
// StopRunning interrupts every task executing for identity.
diff --git a/internal/gateway/web_parity_test.go b/internal/gateway/web_parity_test.go
new file mode 100644
index 000000000..a1e365895
--- /dev/null
+++ b/internal/gateway/web_parity_test.go
@@ -0,0 +1,74 @@
+package gateway
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/samcharles93/archie-core/internal/releaseupdate"
+)
+
+type parityUpdateStub struct{}
+
+func (parityUpdateStub) Check(context.Context, int64) (releaseupdate.Snapshot, error) {
+ return releaseupdate.Snapshot{Components: []releaseupdate.Component{{ID: "gateway", Label: "THE GATEWAY", Installed: "v1", Available: "v2"}}}, nil
+}
+func (parityUpdateStub) Defer(context.Context, int64, releaseupdate.Snapshot) error { return nil }
+func (parityUpdateStub) Install(context.Context, func(string)) error { return nil }
+func (parityUpdateStub) CanInstall() bool { return true }
+
+type parityDangerousStub struct{ decisions []string }
+
+func (s *parityDangerousStub) Decide(_ context.Context, id, decision string) (string, error) {
+ s.decisions = append(s.decisions, id+":"+decision)
+ return "dangerous decision applied", nil
+}
+
+func TestSharedRouterWebParityCommands(t *testing.T) {
+ t.Parallel()
+ r := NewRouter(nil, nil, "web")
+ r.Version = "Archie\nGateway: test\nRuntime: test"
+ restarted := false
+ r.Restart = func(context.Context) error { restarted = true; return nil }
+ r.Updates = parityUpdateStub{}
+ dangerous := &parityDangerousStub{}
+ r.Dangerous = dangerous
+ r.Personas = NewPersonaRegistry(DefaultPersonas())
+ sessions := NewSessionStoreMemory("test")
+ t.Cleanup(func() { _ = sessions.Close() })
+ r.InitSessions(sessions)
+ msg := Message{ChannelID: "browser", From: "web"}
+
+ reply, err := r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/version"})
+ if err != nil || reply != r.Version {
+ t.Fatalf("/version = %q, %v", reply, err)
+ }
+ reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/personality concise"})
+ if err != nil || !strings.Contains(reply, `"concise"`) {
+ t.Fatalf("/personality concise = %q, %v", reply, err)
+ }
+ reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/help"})
+ if err != nil || !strings.Contains(reply, "/personality") || !strings.Contains(reply, "/resume") {
+ t.Fatalf("/help = %q, %v", reply, err)
+ }
+ reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/restart"})
+ if err != nil || !restarted || !strings.Contains(reply, "reload requested") {
+ t.Fatalf("/restart = %q, restarted=%v, err=%v", reply, restarted, err)
+ }
+ reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/update"})
+ if err != nil || !strings.Contains(reply, "v2 available") {
+ t.Fatalf("/update = %q, err=%v", reply, err)
+ }
+ reply, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/approve action-1"})
+ if err != nil || !strings.Contains(reply, "decision applied") || len(dangerous.decisions) != 1 || dangerous.decisions[0] != "action-1:approve" {
+ t.Fatalf("typed /approve = %q, decisions=%v, err=%v", reply, dangerous.decisions, err)
+ }
+ _, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/approve permanent action-2"})
+ if err != nil || len(dangerous.decisions) != 2 || dangerous.decisions[1] != "action-2:permanent" {
+ t.Fatalf("permanent /approve decisions=%v, err=%v", dangerous.decisions, err)
+ }
+ _, err = r.Route(context.Background(), Message{ChannelID: msg.ChannelID, Text: "/deny action-3"})
+ if err != nil || len(dangerous.decisions) != 3 || dangerous.decisions[2] != "action-3:deny" {
+ t.Fatalf("/deny decisions=%v, err=%v", dangerous.decisions, err)
+ }
+}
diff --git a/internal/releaseupdate/format.go b/internal/releaseupdate/format.go
new file mode 100644
index 000000000..63a5ea553
--- /dev/null
+++ b/internal/releaseupdate/format.go
@@ -0,0 +1,32 @@
+package releaseupdate
+
+import (
+ "fmt"
+ "strings"
+)
+
+// FormatSnapshot returns the concise human-facing update status shared by
+// chat adapters. It deliberately includes unchanged components when an
+// update exists so operators can see exactly what will and will not change.
+func FormatSnapshot(snapshot Snapshot) string {
+ if len(snapshot.Available()) == 0 && !snapshot.Deferred {
+ return "Archie is up to date."
+ }
+ if len(snapshot.Available()) == 0 && snapshot.Deferred {
+ return "The available update is deferred. Archie will ask again when a newer release is available."
+ }
+ var text strings.Builder
+ text.WriteString("Archie has an update available:")
+ for _, component := range snapshot.Components {
+ fmt.Fprintf(&text, "\n\n--- %s ---\n", component.Label)
+ if component.Available == "" || component.Available == component.Installed {
+ fmt.Fprintf(&text, "No %s changes as part of this release.", strings.ToLower(strings.TrimPrefix(component.Label, "THE ")))
+ continue
+ }
+ fmt.Fprintf(&text, "%s available", component.Available)
+ if component.Changelog != "" {
+ fmt.Fprintf(&text, "\n\n%s", component.Changelog)
+ }
+ }
+ return text.String()
+}
diff --git a/internal/releaseupdate/service.go b/internal/releaseupdate/service.go
index 8e907c532..4a777bf1f 100644
--- a/internal/releaseupdate/service.go
+++ b/internal/releaseupdate/service.go
@@ -49,6 +49,26 @@ func (s Snapshot) Available() []Component {
return available
}
+// SameAvailable reports whether two snapshots offer the same component
+// versions. Metadata such as changelogs may change without changing the
+// release the operator is approving, so only installable versions matter.
+func SameAvailable(left, right Snapshot) bool {
+ leftAvailable, rightAvailable := left.Available(), right.Available()
+ if len(leftAvailable) != len(rightAvailable) {
+ return false
+ }
+ versions := make(map[string]string, len(leftAvailable))
+ for _, component := range leftAvailable {
+ versions[component.ID] = component.Available
+ }
+ for _, component := range rightAvailable {
+ if versions[component.ID] != component.Available {
+ return false
+ }
+ }
+ return true
+}
+
// Service persists a user's decision to defer an exact available version. A
// later version is deliberately shown again rather than being silently hidden.
type Service struct {
@@ -109,7 +129,7 @@ func (s *Service) Defer(ctx context.Context, recipient int64, expected Snapshot)
if state[key] == nil {
state[key] = make(map[string]string)
}
- if !sameAvailable(snapshot, expected) {
+ if !SameAvailable(snapshot, expected) {
return errors.New("available releases changed; check again")
}
for _, component := range expected.Available() {
@@ -118,23 +138,6 @@ func (s *Service) Defer(ctx context.Context, recipient int64, expected Snapshot)
return saveDeferrals(s.StatePath, state)
}
-func sameAvailable(left, right Snapshot) bool {
- leftAvailable, rightAvailable := left.Available(), right.Available()
- if len(leftAvailable) != len(rightAvailable) {
- return false
- }
- versions := make(map[string]string, len(leftAvailable))
- for _, component := range leftAvailable {
- versions[component.ID] = component.Available
- }
- for _, component := range rightAvailable {
- if versions[component.ID] != component.Available {
- return false
- }
- }
- return true
-}
-
func (s *Service) Install(ctx context.Context, progress func(string)) error {
if s.Installer == nil {
return errors.New("update installation is not configured")
diff --git a/internal/releaseupdate/service_test.go b/internal/releaseupdate/service_test.go
index f2377613b..e3ee7c12f 100644
--- a/internal/releaseupdate/service_test.go
+++ b/internal/releaseupdate/service_test.go
@@ -3,6 +3,7 @@ package releaseupdate
import (
"context"
"path/filepath"
+ "strings"
"testing"
)
@@ -60,6 +61,30 @@ func TestServiceInstallForwardsProgressAndFailure(t *testing.T) {
}
}
+func TestFormatSnapshotReportsAvailableAndUnchangedComponents(t *testing.T) {
+ got := FormatSnapshot(Snapshot{Components: []Component{
+ {Label: "THE GATEWAY", Installed: "v1", Available: "v2", Changelog: "- safer updates"},
+ {Label: "THE RUNTIME", Installed: "v1"},
+ }})
+ for _, want := range []string{"Archie has an update available", "v2 available", "safer updates", "No runtime changes"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("formatted snapshot missing %q: %s", want, got)
+ }
+ }
+}
+
+func TestSameAvailableIgnoresMetadataAndDetectsVersionChanges(t *testing.T) {
+ left := Snapshot{Components: []Component{{ID: "gateway", Installed: "v1", Available: "v2", Changelog: "old"}}}
+ right := Snapshot{Components: []Component{{ID: "gateway", Installed: "v1", Available: "v2", Changelog: "new"}}}
+ if !SameAvailable(left, right) {
+ t.Fatal("matching available versions should be equal")
+ }
+ right.Components[0].Available = "v3"
+ if SameAvailable(left, right) {
+ t.Fatal("changed available versions should not be equal")
+ }
+}
+
type catalogStub struct{ snapshot Snapshot }
func (s *catalogStub) Check(context.Context) (Snapshot, error) { return s.snapshot, nil }
diff --git a/internal/webui/api_chat.go b/internal/webui/api_chat.go
new file mode 100644
index 000000000..5a5db0ea7
--- /dev/null
+++ b/internal/webui/api_chat.go
@@ -0,0 +1,548 @@
+package webui
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+ "sync"
+
+ "github.com/google/uuid"
+
+ "github.com/samcharles93/archie-core/internal/gateway"
+ "github.com/samcharles93/archie-core/internal/releaseupdate"
+)
+
+// ChatService is the shared conversational surface exposed to the dashboard.
+// It deliberately contains the gateway Router rather than duplicating command
+// dispatch in the HTTP layer.
+type ChatService struct {
+ Router *gateway.Router
+ Sessions gateway.SessionStore
+ Turns *gateway.Turns
+ Models gateway.ModelManager
+ Personas *gateway.PersonaRegistry
+ Updates ChatUpdateService
+ Dangerous *DangerousService
+ updateMu sync.Mutex
+ updateInProgress bool
+}
+
+// ChatUpdateService is the shared release workflow used by chat gateways.
+// The web adapter uses recipient zero for the locally authenticated operator.
+type ChatUpdateService interface {
+ Check(context.Context, int64) (releaseupdate.Snapshot, error)
+ Defer(context.Context, int64, releaseupdate.Snapshot) error
+ Install(context.Context, func(string)) error
+ CanInstall() bool
+}
+
+type chatMessageRequest struct {
+ ChannelID string `json:"channel_id"`
+ SourceID string `json:"source_id"`
+ Text string `json:"text"`
+}
+
+type chatPersonaRequest struct {
+ SessionID string `json:"session_id"`
+ Name string `json:"name"`
+}
+
+type chatCancelRequest struct {
+ SessionID string `json:"session_id"`
+}
+
+type chatUpdateRequest struct {
+ Snapshot releaseupdate.Snapshot `json:"snapshot"`
+}
+
+type dangerousRequest struct {
+ Spec string `json:"spec"`
+}
+
+type dangerousDecisionRequest struct {
+ Decision string `json:"decision"`
+}
+
+func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
+ if s.Chat == nil || s.Chat.Router == nil || s.Chat.Sessions == nil {
+ http.Error(w, "chat is not configured", http.StatusNotImplemented)
+ return nil, false
+ }
+ if s.Chat.Router.Updates == nil && s.Chat.Updates != nil {
+ s.Chat.Router.Updates = s.Chat.Updates
+ }
+ if s.Chat.Router.Dangerous == nil && s.Chat.Dangerous != nil {
+ s.Chat.Router.Dangerous = s.Chat.Dangerous
+ }
+ return s.Chat, true
+}
+
+func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ sessions, err := chat.Sessions.List(r.Context())
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ out := make([]gateway.SessionContext, 0, len(sessions))
+ for _, session := range sessions {
+ if session.Source.Platform == "web" {
+ out = append(out, session)
+ }
+ }
+ writeJSON(w, map[string]any{
+ "sessions": out,
+ "models": modelNames(chat.Models),
+ "models_by_provider": modelsByProvider(chat.Models),
+ "providers": modelProviders(chat.Models),
+ "active_model": activeModel(chat.Models),
+ "active_provider": activeProvider(chat.Models),
+ "personas": personaNames(chat.Personas),
+ "active_personas": activePersonas(chat.Personas, out),
+ "commands": chatCommandSpecs(chat),
+ "restart_available": chat.Router.Restart != nil,
+ "dangerous_available": chat.Dangerous != nil,
+ })
+}
+
+func chatCommandSpecs(chat *ChatService) []gateway.CommandSpec {
+ specs := gateway.LocalCommandSpecs()
+ if chat.Dangerous != nil {
+ specs = append(specs,
+ gateway.CommandSpec{Command: "/rollback", Description: "Request approval to restore a filesystem checkpoint", Usage: "/rollback [number]"},
+ gateway.CommandSpec{Command: "/stop", Description: "Request approval to terminate a background process", Usage: "/stop "},
+ gateway.CommandSpec{Command: "/deny", Description: "Deny a pending dangerous action", Usage: "/deny "},
+ )
+ }
+ return specs
+}
+
+func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ sessionID := r.PathValue("id")
+ session, err := chat.Sessions.Get(r.Context(), sessionID)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if session == nil || session.Source.Platform != "web" {
+ http.Error(w, "session not found", http.StatusNotFound)
+ return
+ }
+ messages, err := chat.Sessions.RecentMessages(r.Context(), sessionID, 200)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ writeJSON(w, messages)
+}
+
+func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (gateway.Message, bool) {
+ var req chatMessageRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, "invalid chat message", http.StatusBadRequest)
+ return gateway.Message{}, false
+ }
+ req.Text = strings.TrimSpace(req.Text)
+ if req.Text == "" || req.ChannelID == "" {
+ http.Error(w, "text and channel_id are required", http.StatusBadRequest)
+ return gateway.Message{}, false
+ }
+ if req.SourceID == "" {
+ req.SourceID = newChatSourceID()
+ }
+ return gateway.Message{
+ SourceID: req.SourceID, ChannelID: req.ChannelID,
+ ThreadID: "", From: "web", Text: req.Text,
+ }, true
+}
+
+func (s *Server) handleChatMessage(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ msg, ok := s.decodeChatMessage(w, r)
+ if !ok {
+ return
+ }
+ reply, err := chat.Router.Route(r.Context(), msg)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ sessionID, err := chat.Router.ResolveSessionKey(r.Context(), msg)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ writeJSON(w, map[string]string{"reply": reply, "session_id": sessionID})
+}
+
+func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ msg, ok := s.decodeChatMessage(w, r)
+ if !ok {
+ return
+ }
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ http.Error(w, "streaming unsupported", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("X-Accel-Buffering", "no")
+ writeChatEvent := func(kind, text, sessionID string) {
+ payload, _ := json.Marshal(map[string]string{"type": kind, "text": text, "session_id": sessionID})
+ _, _ = fmt.Fprintf(w, "data: %s\n\n", payload)
+ flusher.Flush()
+ }
+ sessionID, err := chat.Router.ResolveSessionKey(r.Context(), msg)
+ if err != nil {
+ writeChatEvent("error", err.Error(), "")
+ return
+ }
+ writeChatEvent("started", "", sessionID)
+ var reply string
+ if chat.Turns == nil {
+ reply, err = chat.Router.RouteStream(r.Context(), msg, func(delta string) {
+ writeChatEvent("delta", delta, sessionID)
+ })
+ } else {
+ type turnResult struct {
+ reply string
+ err error
+ }
+ events := make(chan string, 32)
+ result := make(chan turnResult, 1)
+ chat.Turns.Submit(r.Context(), sessionID, func(turnCtx context.Context) {
+ turnReply, turnErr := chat.Router.RouteStream(turnCtx, msg, func(delta string) {
+ select {
+ case events <- delta:
+ case <-r.Context().Done():
+ }
+ })
+ result <- turnResult{reply: turnReply, err: turnErr}
+ })
+ for {
+ select {
+ case delta := <-events:
+ writeChatEvent("delta", delta, sessionID)
+ case turn := <-result:
+ for {
+ select {
+ case delta := <-events:
+ writeChatEvent("delta", delta, sessionID)
+ default:
+ goto drained
+ }
+ }
+ drained:
+ reply, err = turn.reply, turn.err
+ goto turnDone
+ case <-r.Context().Done():
+ chat.Turns.Stop(sessionID)
+ return
+ }
+ }
+ turnDone:
+ }
+ if err != nil {
+ writeChatEvent("error", err.Error(), sessionID)
+ return
+ }
+ if resolved, resolveErr := chat.Router.ResolveSessionKey(r.Context(), msg); resolveErr == nil {
+ sessionID = resolved
+ }
+ writeChatEvent("done", reply, sessionID)
+}
+
+func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ if chat.Turns == nil {
+ http.Error(w, "chat cancellation is not configured", http.StatusNotImplemented)
+ return
+ }
+ var req chatCancelRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.SessionID == "" {
+ http.Error(w, "session_id is required", http.StatusBadRequest)
+ return
+ }
+ session, err := chat.Sessions.Get(r.Context(), req.SessionID)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if session == nil || session.Source.Platform != "web" {
+ http.Error(w, "session not found", http.StatusNotFound)
+ return
+ }
+ cancelled, dropped := chat.Turns.Stop(req.SessionID)
+ writeJSON(w, map[string]any{"cancelled": cancelled, "dropped": dropped})
+}
+
+func (s *Server) handleChatPersona(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ if chat.Personas == nil {
+ http.Error(w, "personality switching is not configured", http.StatusNotImplemented)
+ return
+ }
+ var req chatPersonaRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.SessionID == "" || req.Name == "" {
+ http.Error(w, "session_id and name are required", http.StatusBadRequest)
+ return
+ }
+ if session, err := chat.Sessions.Get(r.Context(), req.SessionID); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ } else if session == nil || session.Source.Platform != "web" {
+ http.Error(w, "session not found", http.StatusNotFound)
+ return
+ }
+ if !chat.Personas.SetActive(req.SessionID, strings.ToLower(req.Name)) {
+ http.Error(w, fmt.Sprintf("unknown personality %q", req.Name), http.StatusBadRequest)
+ return
+ }
+ writeJSON(w, map[string]any{"ok": true, "name": strings.ToLower(req.Name)})
+}
+
+func (s *Server) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ if chat.Updates == nil {
+ http.Error(w, "updates are not configured", http.StatusNotImplemented)
+ return
+ }
+ snapshot, err := chat.Updates.Check(r.Context(), 0)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadGateway)
+ return
+ }
+ writeJSON(w, map[string]any{
+ "snapshot": snapshot,
+ "available": snapshot.Available(),
+ "can_install": chat.Updates.CanInstall(),
+ })
+}
+
+func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ if chat.Updates == nil {
+ http.Error(w, "updates are not configured", http.StatusNotImplemented)
+ return
+ }
+ var req chatUpdateRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, "invalid update snapshot", http.StatusBadRequest)
+ return
+ }
+ if err := chat.Updates.Defer(r.Context(), 0, req.Snapshot); err != nil {
+ http.Error(w, err.Error(), http.StatusConflict)
+ return
+ }
+ writeJSON(w, map[string]bool{"ok": true})
+}
+
+func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ if chat.Updates == nil || !chat.Updates.CanInstall() {
+ http.Error(w, "update installation is not configured", http.StatusNotImplemented)
+ return
+ }
+ var req chatUpdateRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || len(req.Snapshot.Available()) == 0 {
+ http.Error(w, "the displayed update snapshot is required", http.StatusBadRequest)
+ return
+ }
+ fresh, err := chat.Updates.Check(r.Context(), 0)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadGateway)
+ return
+ }
+ if !releaseupdate.SameAvailable(fresh, req.Snapshot) {
+ http.Error(w, "available releases changed; check again", http.StatusConflict)
+ return
+ }
+ chat.updateMu.Lock()
+ if chat.updateInProgress {
+ chat.updateMu.Unlock()
+ http.Error(w, "an update is already in progress", http.StatusConflict)
+ return
+ }
+ chat.updateInProgress = true
+ chat.updateMu.Unlock()
+ defer func() {
+ chat.updateMu.Lock()
+ chat.updateInProgress = false
+ chat.updateMu.Unlock()
+ }()
+
+ progress := make([]string, 0, 4)
+ err = chat.Updates.Install(r.Context(), func(message string) { progress = append(progress, message) })
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadGateway)
+ return
+ }
+ writeJSON(w, map[string]any{"ok": true, "progress": progress})
+}
+
+func (s *Server) handleChatDangerousState(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ if chat.Dangerous == nil {
+ http.Error(w, "dangerous sandbox actions are not configured", http.StatusNotImplemented)
+ return
+ }
+ checkpoints, err := chat.Dangerous.Checkpoints(r.Context())
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadGateway)
+ return
+ }
+ writeJSON(w, map[string]any{"checkpoints": checkpoints, "pending": chat.Dangerous.Pending()})
+}
+
+func (s *Server) handleChatDangerousRequest(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ if chat.Dangerous == nil {
+ http.Error(w, "dangerous sandbox actions are not configured", http.StatusNotImplemented)
+ return
+ }
+ var req dangerousRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Spec) == "" {
+ http.Error(w, "spec is required", http.StatusBadRequest)
+ return
+ }
+ action, result, executed, err := chat.Dangerous.Request(r.Context(), r.PathValue("kind"), req.Spec)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ writeJSON(w, map[string]any{"action": action, "result": result, "executed": executed})
+}
+
+func (s *Server) handleChatDangerousDecision(w http.ResponseWriter, r *http.Request) {
+ chat, ok := s.chatReady(w)
+ if !ok {
+ return
+ }
+ if chat.Dangerous == nil {
+ http.Error(w, "dangerous sandbox actions are not configured", http.StatusNotImplemented)
+ return
+ }
+ var req dangerousDecisionRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Decision) == "" {
+ http.Error(w, "decision is required", http.StatusBadRequest)
+ return
+ }
+ result, err := chat.Dangerous.Decide(r.Context(), r.PathValue("id"), req.Decision)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusConflict)
+ return
+ }
+ writeJSON(w, map[string]any{"ok": true, "result": result})
+}
+
+func modelNames(models gateway.ModelManager) []string {
+ if models == nil {
+ return []string{}
+ }
+ return models.Models()
+}
+
+func activeModel(models gateway.ModelManager) string {
+ if models == nil {
+ return ""
+ }
+ return models.ActiveModel()
+}
+
+func activeProvider(models gateway.ModelManager) string {
+ manager, ok := models.(gateway.ProviderModelManager)
+ if !ok {
+ return ""
+ }
+ return manager.ActiveProvider()
+}
+
+func modelProviders(models gateway.ModelManager) []string {
+ manager, ok := models.(gateway.ProviderModelManager)
+ if !ok {
+ return []string{}
+ }
+ return manager.Providers()
+}
+
+func modelsByProvider(models gateway.ModelManager) map[string][]string {
+ if models == nil {
+ return map[string][]string{}
+ }
+ if manager, ok := models.(gateway.ProviderModelManager); ok {
+ groups := make(map[string][]string, len(manager.Providers()))
+ for _, provider := range manager.Providers() {
+ groups[provider] = manager.ModelsForProvider(provider)
+ }
+ return groups
+ }
+ groups := make(map[string][]string)
+ for _, model := range models.Models() {
+ provider, _, ok := strings.Cut(model, "/")
+ if !ok {
+ provider = ""
+ }
+ groups[provider] = append(groups[provider], model)
+ }
+ return groups
+}
+
+func activePersonas(personas *gateway.PersonaRegistry, sessions []gateway.SessionContext) map[string]string {
+ active := make(map[string]string, len(sessions))
+ if personas == nil {
+ return active
+ }
+ for _, session := range sessions {
+ active[session.SessionID] = personas.ActiveName(session.SessionID)
+ }
+ return active
+}
+
+func personaNames(personas *gateway.PersonaRegistry) []string {
+ if personas == nil {
+ return []string{}
+ }
+ return personas.List()
+}
+
+func newChatSourceID() string {
+ return "web-" + uuid.NewString()
+}
diff --git a/internal/webui/api_chat_test.go b/internal/webui/api_chat_test.go
new file mode 100644
index 000000000..0ec0f991b
--- /dev/null
+++ b/internal/webui/api_chat_test.go
@@ -0,0 +1,627 @@
+package webui
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/samcharles93/archie-core/internal/gateway"
+ "github.com/samcharles93/archie-core/internal/releaseupdate"
+)
+
+type chatStatusStub struct{}
+
+func (chatStatusStub) StatusCounts(context.Context) (map[string]int, error) {
+ return map[string]int{"queued": 2}, nil
+}
+
+type chatProviderModelStub struct {
+ active string
+}
+
+func (s *chatProviderModelStub) Models() []string {
+ return []string{"openai/gpt-5", "openrouter/sonnet"}
+}
+
+func (s *chatProviderModelStub) ActiveModel() string { return s.active }
+
+func (s *chatProviderModelStub) SetActiveModel(context.Context, string) error { return nil }
+
+func (*chatProviderModelStub) Providers() []string { return []string{"openai", "openrouter"} }
+
+func (s *chatProviderModelStub) ActiveProvider() string {
+ provider, _, _ := strings.Cut(s.active, "/")
+ return provider
+}
+
+func (s *chatProviderModelStub) ModelsForProvider(provider string) []string {
+ var models []string
+ for _, model := range s.Models() {
+ if strings.HasPrefix(model, provider+"/") {
+ models = append(models, model)
+ }
+ }
+ return models
+}
+
+func (*chatProviderModelStub) SetActiveProvider(context.Context, string) error { return nil }
+
+type chatUpdateStub struct {
+ snapshot releaseupdate.Snapshot
+ deferred releaseupdate.Snapshot
+ installed bool
+}
+
+type webDangerousStub struct {
+ rollbackCalls []int
+ stopCalls []string
+}
+
+func (s *webDangerousStub) StopProcess(_ context.Context, spec string) error {
+ s.stopCalls = append(s.stopCalls, spec)
+ return nil
+}
+
+func (s *webDangerousStub) Rollback(_ context.Context, checkpoint int) (string, error) {
+ s.rollbackCalls = append(s.rollbackCalls, checkpoint)
+ return "rollback complete", nil
+}
+
+func (*webDangerousStub) ListCheckpoints(context.Context) ([]gateway.CheckpointInfo, error) {
+ return []gateway.CheckpointInfo{{Number: 3, Label: "after tests"}}, nil
+}
+
+func (s *chatUpdateStub) Check(context.Context, int64) (releaseupdate.Snapshot, error) {
+ return s.snapshot, nil
+}
+
+func (s *chatUpdateStub) Defer(_ context.Context, _ int64, snapshot releaseupdate.Snapshot) error {
+ s.deferred = snapshot
+ return nil
+}
+
+func (s *chatUpdateStub) Install(_ context.Context, progress func(string)) error {
+ s.installed = true
+ progress("install started")
+ return nil
+}
+func (*chatUpdateStub) CanInstall() bool { return true }
+
+func TestChatSessionAndMessageEndpoints(t *testing.T) {
+ t.Parallel()
+ sessions := gateway.NewSessionStoreMemory("test")
+ t.Cleanup(func() { _ = sessions.Close() })
+ router := gateway.NewRouter(chatStatusStub{}, nil, "web")
+ router.InitSessions(sessions)
+ server := &Server{Chat: &ChatService{Router: router, Sessions: sessions}}
+ session := gateway.SessionContext{
+ SessionID: "session-1",
+ Source: gateway.SessionSource{Platform: "web", ChannelID: "browser-1"},
+ CreatedAt: time.Now().UTC(), LastActiveAt: time.Now().UTC(),
+ }
+ if err := sessions.Save(context.Background(), session); err != nil {
+ t.Fatal(err)
+ }
+ if err := sessions.SaveMessage(context.Background(), session.SessionID, gateway.Message{From: "web", Text: "hello"}); err != nil {
+ t.Fatal(err)
+ }
+
+ t.Run("sessions", func(t *testing.T) {
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/sessions", nil)
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code != http.StatusOK {
+ t.Fatalf("status = %d, body = %s", res.Code, res.Body)
+ }
+ var got struct {
+ Sessions []gateway.SessionContext `json:"sessions"`
+ }
+ if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if len(got.Sessions) != 1 || got.Sessions[0].SessionID != session.SessionID {
+ t.Fatalf("sessions = %#v", got.Sessions)
+ }
+ })
+
+ t.Run("messages", func(t *testing.T) {
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/sessions/session-1/messages", nil)
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code != http.StatusOK {
+ t.Fatalf("status = %d, body = %s", res.Code, res.Body)
+ }
+ var got []gateway.Message
+ if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != 1 || got[0].Text != "hello" {
+ t.Fatalf("messages = %#v", got)
+ }
+ })
+
+ t.Run("shared router command", func(t *testing.T) {
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/message", bytes.NewBufferString(`{"channel_id":"browser-1","text":"/status"}`))
+ req.Header.Set("Content-Type", "application/json")
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code != http.StatusOK {
+ t.Fatalf("status = %d, body = %s", res.Code, res.Body)
+ }
+ var got struct {
+ Reply string `json:"reply"`
+ }
+ if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.Reply == "" {
+ t.Fatal("shared router returned an empty status reply")
+ }
+ })
+}
+
+func TestChatSessionsExposeActiveSelectorState(t *testing.T) {
+ sessions := gateway.NewSessionStoreMemory("selector-state")
+ t.Cleanup(func() { _ = sessions.Close() })
+ router := gateway.NewRouter(chatStatusStub{}, nil, "web")
+ router.InitSessions(sessions)
+ models := &chatProviderModelStub{active: "openrouter/sonnet"}
+ router.Models = models
+ server := &Server{Chat: &ChatService{
+ Router: router,
+ Models: models,
+ Sessions: sessions,
+ Personas: gateway.NewPersonaRegistry(gateway.DefaultPersonas()),
+ }}
+ session := gateway.SessionContext{
+ SessionID: "selector-session",
+ Source: gateway.SessionSource{Platform: "web", ChannelID: "selector-browser"},
+ }
+ if err := sessions.Save(context.Background(), session); err != nil {
+ t.Fatal(err)
+ }
+ if !server.Chat.Personas.SetActive(session.SessionID, "concise") {
+ t.Fatal("set active persona failed")
+ }
+
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, httptest.NewRequest(http.MethodGet, "/api/chat/sessions", nil))
+ if res.Code != http.StatusOK {
+ t.Fatalf("status = %d, body = %s", res.Code, res.Body)
+ }
+ var got struct {
+ ActiveModel string `json:"active_model"`
+ ActiveProvider string `json:"active_provider"`
+ Providers []string `json:"providers"`
+ Models map[string][]string `json:"models_by_provider"`
+ Personas map[string]string `json:"active_personas"`
+ }
+ if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.ActiveModel != "openrouter/sonnet" || got.ActiveProvider != "openrouter" {
+ t.Fatalf("active model state = %#v", got)
+ }
+ if !slices.Equal(got.Providers, []string{"openai", "openrouter"}) || !slices.Equal(got.Models["openrouter"], []string{"openrouter/sonnet"}) {
+ t.Fatalf("provider model state = %#v / %#v", got.Providers, got.Models)
+ }
+ if got.Personas[session.SessionID] != "concise" {
+ t.Fatalf("active personas = %#v", got.Personas)
+ }
+}
+
+func TestChatUpdateEndpoints(t *testing.T) {
+ updates := &chatUpdateStub{snapshot: releaseupdate.Snapshot{Components: []releaseupdate.Component{{ID: "gateway", Label: "Gateway", Installed: "1.0", Available: "1.1"}}}}
+ sessions := gateway.NewSessionStoreMemory("test")
+ t.Cleanup(func() { _ = sessions.Close() })
+ router := gateway.NewRouter(chatStatusStub{}, nil, "web")
+ server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Updates: updates}}
+
+ get := httptest.NewRecorder()
+ server.Handler().ServeHTTP(get, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/update", nil))
+ if get.Code != http.StatusOK || !bytes.Contains(get.Body.Bytes(), []byte(`"can_install":true`)) {
+ t.Fatalf("update status = %d, body = %s", get.Code, get.Body.String())
+ }
+
+ body, _ := json.Marshal(chatUpdateRequest{Snapshot: updates.snapshot})
+ deferRes := httptest.NewRecorder()
+ server.Handler().ServeHTTP(deferRes, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/update/defer", bytes.NewReader(body)))
+ if deferRes.Code != http.StatusOK || len(updates.deferred.Components) != 1 {
+ t.Fatalf("update defer = %d, body = %s", deferRes.Code, deferRes.Body.String())
+ }
+
+ installBody, _ := json.Marshal(chatUpdateRequest{Snapshot: updates.snapshot})
+ installRes := httptest.NewRecorder()
+ server.Handler().ServeHTTP(installRes, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/update/install", bytes.NewReader(installBody)))
+ if installRes.Code != http.StatusOK || !updates.installed {
+ t.Fatalf("update install = %d, body = %s", installRes.Code, installRes.Body.String())
+ }
+
+ updates.installed = false
+ displayed := releaseupdate.Snapshot{Components: append([]releaseupdate.Component(nil), updates.snapshot.Components...)}
+ updates.snapshot.Components[0].Available = "1.2"
+ staleBody, _ := json.Marshal(chatUpdateRequest{Snapshot: displayed})
+ staleRes := httptest.NewRecorder()
+ server.Handler().ServeHTTP(staleRes, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/update/install", bytes.NewReader(staleBody)))
+ if staleRes.Code != http.StatusConflict || updates.installed {
+ t.Fatalf("stale update install = %d, body = %s, installed = %v", staleRes.Code, staleRes.Body.String(), updates.installed)
+ }
+}
+
+func TestChatDangerousApprovalEndpoints(t *testing.T) {
+ sessions := gateway.NewSessionStoreMemory("test")
+ t.Cleanup(func() { _ = sessions.Close() })
+ authority := &webDangerousStub{}
+ router := gateway.NewRouter(chatStatusStub{}, nil, "web")
+ server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Dangerous: NewDangerousService(authority)}}
+
+ state := httptest.NewRecorder()
+ server.Handler().ServeHTTP(state, httptest.NewRequest(http.MethodGet, "/api/chat/dangerous", nil))
+ if state.Code != http.StatusOK || !bytes.Contains(state.Body.Bytes(), []byte(`"Number":3`)) {
+ t.Fatalf("dangerous state = %d, body = %s", state.Code, state.Body.String())
+ }
+
+ request := httptest.NewRecorder()
+ server.Handler().ServeHTTP(request, httptest.NewRequest(http.MethodPost, "/api/chat/dangerous/rollback", bytes.NewBufferString(`{"spec":"3"}`)))
+ if request.Code != http.StatusOK || len(authority.rollbackCalls) != 0 {
+ t.Fatalf("rollback request = %d, body = %s, calls=%v", request.Code, request.Body.String(), authority.rollbackCalls)
+ }
+ var pending struct {
+ Action DangerousActionView `json:"action"`
+ }
+ if err := json.Unmarshal(request.Body.Bytes(), &pending); err != nil {
+ t.Fatal(err)
+ }
+
+ decisionBody := bytes.NewBufferString(`{"decision":"approve"}`)
+ decision := httptest.NewRecorder()
+ server.Handler().ServeHTTP(decision, httptest.NewRequest(http.MethodPost, "/api/chat/dangerous/"+pending.Action.ID+"/decision", decisionBody))
+ if decision.Code != http.StatusOK || len(authority.rollbackCalls) != 1 || authority.rollbackCalls[0] != 3 {
+ t.Fatalf("rollback decision = %d, body = %s, calls=%v", decision.Code, decision.Body.String(), authority.rollbackCalls)
+ }
+}
+
+func TestChatCommandCatalogIncludesEnabledCapabilities(t *testing.T) {
+ sessions := gateway.NewSessionStoreMemory("test")
+ t.Cleanup(func() { _ = sessions.Close() })
+ router := gateway.NewRouter(chatStatusStub{}, nil, "web")
+ server := &Server{Chat: &ChatService{
+ Router: router, Sessions: sessions,
+ Updates: &chatUpdateStub{}, Dangerous: NewDangerousService(&webDangerousStub{}),
+ }}
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, httptest.NewRequest(http.MethodGet, "/api/chat/sessions", nil))
+ if res.Code != http.StatusOK {
+ t.Fatalf("catalog status = %d, body = %s", res.Code, res.Body.String())
+ }
+ var body struct {
+ Commands []gateway.CommandSpec `json:"commands"`
+ }
+ if err := json.Unmarshal(res.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ found := map[string]bool{}
+ for _, command := range body.Commands {
+ found[command.Command] = true
+ }
+ for _, command := range []string{"/update", "/rollback", "/stop"} {
+ if !found[command] {
+ t.Errorf("command catalog missing enabled %s", command)
+ }
+ }
+}
+
+func TestChatCancelEndpointStopsSessionTurn(t *testing.T) {
+ sessions := gateway.NewSessionStoreMemory("cancel")
+ t.Cleanup(func() { _ = sessions.Close() })
+ router := gateway.NewRouter(chatStatusStub{}, nil, "web")
+ router.InitSessions(sessions)
+ turns := gateway.NewTurns(slog.Default())
+ server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Turns: turns}}
+ if err := sessions.Save(context.Background(), gateway.SessionContext{
+ SessionID: "session-1", Source: gateway.SessionSource{Platform: "web", ChannelID: "browser-1"},
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ started := make(chan struct{})
+ stopped := make(chan struct{})
+ turns.Submit(context.Background(), "session-1", func(ctx context.Context) {
+ close(started)
+ <-ctx.Done()
+ close(stopped)
+ })
+ <-started
+
+ req := httptest.NewRequest(http.MethodPost, "/api/chat/cancel", strings.NewReader(`{"session_id":"session-1"}`))
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code != http.StatusOK {
+ t.Fatalf("status = %d, body = %s", res.Code, res.Body.String())
+ }
+ select {
+ case <-stopped:
+ case <-time.After(time.Second):
+ t.Fatal("cancel endpoint did not stop the turn")
+ }
+ var body struct {
+ Cancelled bool `json:"cancelled"`
+ }
+ if err := json.Unmarshal(res.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ if !body.Cancelled {
+ t.Fatal("cancel endpoint reported no cancelled turn")
+ }
+}
+
+// chatTestServer builds the fixture the chat endpoint tests share: a web
+// gateway router on an in-memory session store.
+func chatTestServer(t *testing.T) (*Server, gateway.SessionStore) {
+ t.Helper()
+ sessions := gateway.NewSessionStoreMemory("test")
+ t.Cleanup(func() { _ = sessions.Close() })
+ router := gateway.NewRouter(chatStatusStub{}, nil, "web")
+ router.InitSessions(sessions)
+ return &Server{Chat: &ChatService{Router: router, Sessions: sessions}}, sessions
+}
+
+func saveWebSession(t *testing.T, sessions gateway.SessionStore, id string) {
+ t.Helper()
+ if err := sessions.Save(context.Background(), gateway.SessionContext{
+ SessionID: id,
+ Source: gateway.SessionSource{Platform: "web", ChannelID: "browser-" + id},
+ CreatedAt: time.Now().UTC(),
+ LastActiveAt: time.Now().UTC(),
+ }); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestChatEndpointsRequireToken proves the whole chat surface sits behind the
+// same token gate as the rest of the dashboard, not a parallel auth story.
+func TestChatEndpointsRequireToken(t *testing.T) {
+ server := &Server{Token: "secret"}
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/sessions", nil)
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want 401 for a tokenless request", res.Code)
+ }
+
+ req = httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/sessions", nil)
+ req.Header.Set("Authorization", "Bearer secret")
+ res = httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code == http.StatusUnauthorized {
+ t.Fatal("valid bearer token was rejected")
+ }
+ if res.Code != http.StatusNotImplemented {
+ t.Fatalf("status = %d, want 501 (chat unconfigured) past the token gate", res.Code)
+ }
+}
+
+// TestChatEndpointsUnavailableWithoutChatService proves every chat route
+// degrades to 501 rather than panicking when the daemon runs without chat.
+func TestChatEndpointsUnavailableWithoutChatService(t *testing.T) {
+ server := &Server{}
+ cases := []struct {
+ method, path, body string
+ }{
+ {http.MethodGet, "/api/chat/sessions", ""},
+ {http.MethodGet, "/api/chat/sessions/s-1/messages", ""},
+ {http.MethodPost, "/api/chat/message", `{"channel_id":"c","text":"hi"}`},
+ {http.MethodPost, "/api/chat/stream", `{"channel_id":"c","text":"hi"}`},
+ {http.MethodPost, "/api/chat/persona", `{"session_id":"s","name":"concise"}`},
+ {http.MethodPost, "/api/chat/update/install", ""},
+ }
+ for _, tc := range cases {
+ var body io.Reader
+ if tc.body != "" {
+ body = strings.NewReader(tc.body)
+ }
+ req := httptest.NewRequestWithContext(context.Background(), tc.method, tc.path, body)
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code != http.StatusNotImplemented {
+ t.Errorf("%s %s = %d, want 501", tc.method, tc.path, res.Code)
+ }
+ }
+}
+
+// TestChatMessageDecodeErrors proves malformed or incomplete chat messages are
+// refused at the boundary, before any router state is touched.
+func TestChatMessageDecodeErrors(t *testing.T) {
+ server, _ := chatTestServer(t)
+ cases := []struct {
+ name, body string
+ }{
+ {"malformed json", `{`},
+ {"blank text", `{"channel_id":"c","text":" "}`},
+ {"missing channel_id", `{"text":"hi"}`},
+ }
+ for _, tc := range cases {
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/message", strings.NewReader(tc.body))
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code != http.StatusBadRequest {
+ t.Errorf("%s: status = %d, want 400", tc.name, res.Code)
+ }
+ }
+}
+
+// TestChatSessionsFiltersNonWeb proves the dashboard only lists and serves
+// browser-originated sessions: a Telegram session is invisible to it and its
+// transcript is not reachable by guessing the id.
+func TestChatSessionsFiltersNonWeb(t *testing.T) {
+ server, sessions := chatTestServer(t)
+ saveWebSession(t, sessions, "web-1")
+ if err := sessions.Save(context.Background(), gateway.SessionContext{
+ SessionID: "tg-1",
+ Source: gateway.SessionSource{Platform: "telegram", ChannelID: "42"},
+ CreatedAt: time.Now().UTC(),
+ LastActiveAt: time.Now().UTC(),
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/sessions", nil))
+ if res.Code != http.StatusOK {
+ t.Fatalf("sessions status = %d, body = %s", res.Code, res.Body)
+ }
+ var got struct {
+ Sessions []gateway.SessionContext `json:"sessions"`
+ }
+ if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if len(got.Sessions) != 1 || got.Sessions[0].SessionID != "web-1" {
+ t.Fatalf("sessions = %#v, want only the web session", got.Sessions)
+ }
+
+ res = httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/sessions/tg-1/messages", nil))
+ if res.Code != http.StatusNotFound {
+ t.Fatalf("telegram transcript status = %d, want 404", res.Code)
+ }
+}
+
+// chatSSEEvent is one parsed `data: {...}` frame from the stream endpoint.
+type chatSSEEvent struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ SessionID string `json:"session_id"`
+}
+
+func parseChatSSE(t *testing.T, body string) []chatSSEEvent {
+ t.Helper()
+ var events []chatSSEEvent
+ for frame := range strings.SplitSeq(body, "\n\n") {
+ line := strings.TrimSpace(frame)
+ if line == "" {
+ continue
+ }
+ if !strings.HasPrefix(line, "data: ") {
+ t.Fatalf("malformed SSE frame: %q", frame)
+ }
+ var ev chatSSEEvent
+ if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &ev); err != nil {
+ t.Fatalf("invalid SSE payload %q: %v", line, err)
+ }
+ events = append(events, ev)
+ }
+ return events
+}
+
+// TestChatStreamEndsWithDone proves the stream endpoint answers a local
+// command through the shared router and frames the reply as a single done
+// event carrying the session the turn ran in.
+func TestChatStreamEndsWithDone(t *testing.T) {
+ server, _ := chatTestServer(t)
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/stream",
+ strings.NewReader(`{"channel_id":"browser-1","text":"/status"}`))
+ req.Header.Set("Content-Type", "application/json")
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code != http.StatusOK {
+ t.Fatalf("status = %d, body = %s", res.Code, res.Body)
+ }
+ if ct := res.Header().Get("Content-Type"); !strings.Contains(ct, "text/event-stream") {
+ t.Fatalf("Content-Type = %q, want text/event-stream", ct)
+ }
+ events := parseChatSSE(t, res.Body.String())
+ if len(events) == 0 || events[len(events)-1].Type != "done" {
+ t.Fatalf("events = %#v, want a final done event", events)
+ }
+ last := events[len(events)-1]
+ if last.Text == "" {
+ t.Fatal("done event carried an empty reply")
+ }
+ if last.SessionID == "" {
+ t.Fatal("done event carried no session_id")
+ }
+}
+
+// TestChatStreamDeltas proves a real streaming responder's deltas are emitted
+// as SSE delta events before the final done event.
+func TestChatStreamDeltas(t *testing.T) {
+ server, sessions := chatTestServer(t)
+ var gotDeltas []string
+ server.Chat.Router.LLMStream = func(_ context.Context, _ gateway.Message, onDelta func(string)) (string, error) {
+ onDelta("part one")
+ onDelta("part two")
+ return "full reply", nil
+ }
+ saveWebSession(t, sessions, "web-1")
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/stream",
+ strings.NewReader(`{"channel_id":"browser-web-1","text":"hello"}`))
+ req.Header.Set("Content-Type", "application/json")
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ if res.Code != http.StatusOK {
+ t.Fatalf("status = %d, body = %s", res.Code, res.Body)
+ }
+ events := parseChatSSE(t, res.Body.String())
+ for _, ev := range events {
+ if ev.Type == "delta" {
+ gotDeltas = append(gotDeltas, ev.Text)
+ }
+ }
+ if len(gotDeltas) != 2 || gotDeltas[0] != "part one" || gotDeltas[1] != "part two" {
+ t.Fatalf("deltas = %#v", gotDeltas)
+ }
+ if events[len(events)-1].Type != "done" || events[len(events)-1].Text != "full reply" {
+ t.Fatalf("final event = %#v, want done/full reply", events[len(events)-1])
+ }
+}
+
+// TestChatPersonaEndpoint proves the persona surface: switching to a known
+// persona works, an unknown name is refused, a non-web session is invisible,
+// and an unconfigured registry degrades to 501.
+func TestChatPersonaEndpoint(t *testing.T) {
+ server, sessions := chatTestServer(t)
+ server.Chat.Personas = gateway.NewPersonaRegistry(gateway.DefaultPersonas())
+ saveWebSession(t, sessions, "web-1")
+
+ post := func(body string) *httptest.ResponseRecorder {
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/persona", strings.NewReader(body))
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ return res
+ }
+
+ if res := post(`{"session_id":"web-1","name":"concise"}`); res.Code != http.StatusOK {
+ t.Fatalf("known persona: status = %d, body = %s", res.Code, res.Body)
+ }
+ if res := post(`{"session_id":"web-1","name":"does-not-exist"}`); res.Code != http.StatusBadRequest {
+ t.Fatalf("unknown persona: status = %d, body = %s", res.Code, res.Body)
+ }
+ if res := post(`{"session_id":"tg-1","name":"concise"}`); res.Code != http.StatusNotFound {
+ t.Fatalf("non-web session: status = %d, body = %s", res.Code, res.Body)
+ }
+ if res := post(`{"session_id":"","name":"concise"}`); res.Code != http.StatusBadRequest {
+ t.Fatalf("blank session: status = %d, body = %s", res.Code, res.Body)
+ }
+
+ nilServer, nilSessions := chatTestServer(t)
+ saveWebSession(t, nilSessions, "web-1")
+ if res := postTo(nilServer, `{"session_id":"web-1","name":"concise"}`); res.Code != http.StatusNotImplemented {
+ t.Fatalf("nil personas: status = %d, body = %s", res.Code, res.Body)
+ }
+}
+
+func postTo(server *Server, body string) *httptest.ResponseRecorder {
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/persona", strings.NewReader(body))
+ res := httptest.NewRecorder()
+ server.Handler().ServeHTTP(res, req)
+ return res
+}
diff --git a/internal/webui/dangerous.go b/internal/webui/dangerous.go
new file mode 100644
index 000000000..441de5fdf
--- /dev/null
+++ b/internal/webui/dangerous.go
@@ -0,0 +1,155 @@
+package webui
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+
+ "github.com/samcharles93/archie-core/internal/gateway"
+)
+
+const (
+ dangerousApprovalLifetime = 10 * time.Minute
+ permanentApprovalLifetime = 24 * time.Hour
+)
+
+// DangerousService adapts the daemon-owned sandbox authority to an
+// interactive approval workflow. It intentionally has no host process or
+// filesystem access of its own.
+type DangerousService struct {
+ Authority gateway.DangerousCommandAuthority
+
+ mu sync.Mutex
+ actions map[string]dangerousAction
+ permanent map[string]time.Time
+}
+
+type dangerousAction struct {
+ ID string
+ Kind string
+ Spec string
+ Description string
+ ExpiresAt time.Time
+}
+
+type DangerousActionView struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ Description string `json:"description"`
+ ExpiresAt time.Time `json:"expires_at"`
+}
+
+func NewDangerousService(authority gateway.DangerousCommandAuthority) *DangerousService {
+ return &DangerousService{
+ Authority: authority,
+ actions: make(map[string]dangerousAction),
+ permanent: make(map[string]time.Time),
+ }
+}
+
+func (s *DangerousService) enabled() error {
+ if s == nil || s.Authority == nil {
+ return errors.New("dangerous sandbox actions are not configured")
+ }
+ return nil
+}
+
+func (s *DangerousService) Checkpoints(ctx context.Context) ([]gateway.CheckpointInfo, error) {
+ if err := s.enabled(); err != nil {
+ return nil, err
+ }
+ return s.Authority.ListCheckpoints(ctx)
+}
+
+func (s *DangerousService) Pending() []DangerousActionView {
+ if s == nil {
+ return nil
+ }
+ now := time.Now()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ views := make([]DangerousActionView, 0, len(s.actions))
+ for id, action := range s.actions {
+ if !action.ExpiresAt.After(now) {
+ delete(s.actions, id)
+ continue
+ }
+ views = append(views, DangerousActionView{
+ ID: action.ID, Kind: action.Kind, Description: action.Description, ExpiresAt: action.ExpiresAt,
+ })
+ }
+ return views
+}
+
+// Request creates a pending action unless the local operator has granted a
+// still-valid permanent approval for this operation family.
+func (s *DangerousService) Request(ctx context.Context, kind, spec string) (DangerousActionView, string, bool, error) {
+ if err := s.enabled(); err != nil {
+ return DangerousActionView{}, "", false, err
+ }
+ kind = strings.ToLower(strings.TrimSpace(kind))
+ spec = strings.TrimSpace(spec)
+ if kind != "rollback" && kind != "stop" || spec == "" {
+ return DangerousActionView{}, "", false, errors.New("invalid dangerous action")
+ }
+ description := fmt.Sprintf("%s %s", kind, spec)
+ s.mu.Lock()
+ now := time.Now()
+ if expires := s.permanent[kind]; expires.After(now) {
+ s.mu.Unlock()
+ result, err := s.execute(ctx, kind, spec)
+ return DangerousActionView{Kind: kind, Description: description, ExpiresAt: expires}, result, true, err
+ }
+ id := uuid.NewString()
+ action := dangerousAction{ID: id, Kind: kind, Spec: spec, Description: description, ExpiresAt: now.Add(dangerousApprovalLifetime)}
+ s.actions[id] = action
+ s.mu.Unlock()
+ return DangerousActionView{ID: id, Kind: kind, Description: description, ExpiresAt: action.ExpiresAt}, "", false, nil
+}
+
+func (s *DangerousService) Decide(ctx context.Context, id, decision string) (string, error) {
+ if err := s.enabled(); err != nil {
+ return "", err
+ }
+ s.mu.Lock()
+ action, ok := s.actions[id]
+ if ok {
+ delete(s.actions, id)
+ }
+ s.mu.Unlock()
+ if !ok || !action.ExpiresAt.After(time.Now()) {
+ return "", errors.New("dangerous action is expired or unknown")
+ }
+ switch strings.ToLower(strings.TrimSpace(decision)) {
+ case "deny":
+ return "Command denied.", nil
+ case "approve":
+ return s.execute(ctx, action.Kind, action.Spec)
+ case "permanent":
+ s.mu.Lock()
+ s.permanent[action.Kind] = time.Now().Add(permanentApprovalLifetime)
+ s.mu.Unlock()
+ return s.execute(ctx, action.Kind, action.Spec)
+ default:
+ return "", errors.New("decision must be approve, permanent, or deny")
+ }
+}
+
+func (s *DangerousService) execute(ctx context.Context, kind, spec string) (string, error) {
+ if kind == "stop" {
+ if err := s.Authority.StopProcess(ctx, spec); err != nil {
+ return "", err
+ }
+ return "Process stopped.", nil
+ }
+ var checkpoint int
+ if _, err := fmt.Sscan(spec, &checkpoint); err != nil || checkpoint <= 0 {
+ return "", errors.New("checkpoint must be a positive number")
+ }
+ return s.Authority.Rollback(ctx, checkpoint)
+}
diff --git a/internal/webui/server.go b/internal/webui/server.go
index 7ea50c5b4..dbbda2aef 100644
--- a/internal/webui/server.go
+++ b/internal/webui/server.go
@@ -35,6 +35,10 @@ type Server struct {
// unavailable rather than failing when it is nil.
Memory *memory.Manager
+ // Chat exposes the same gateway router used by the conversational
+ // channels. Optional: the dashboard simply omits chat when it is nil.
+ Chat *ChatService
+
// Token gates access. Empty means no check, which is how loopback binds
// stay frictionless -- see IsLoopback.
Token string
@@ -93,6 +97,18 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/config", s.handleConfig)
mux.HandleFunc("GET /api/logs", s.handleLogs)
mux.HandleFunc("GET /api/memory", s.handleMemory)
+ mux.HandleFunc("GET /api/chat/sessions", s.handleChatSessions)
+ mux.HandleFunc("GET /api/chat/sessions/{id}/messages", s.handleChatMessages)
+ mux.HandleFunc("POST /api/chat/message", s.handleChatMessage)
+ mux.HandleFunc("POST /api/chat/stream", s.handleChatStream)
+ mux.HandleFunc("POST /api/chat/cancel", s.handleChatCancel)
+ mux.HandleFunc("POST /api/chat/persona", s.handleChatPersona)
+ mux.HandleFunc("GET /api/chat/update", s.handleChatUpdate)
+ mux.HandleFunc("POST /api/chat/update/defer", s.handleChatUpdateDefer)
+ mux.HandleFunc("POST /api/chat/update/install", s.handleChatUpdateInstall)
+ mux.HandleFunc("GET /api/chat/dangerous", s.handleChatDangerousState)
+ mux.HandleFunc("POST /api/chat/dangerous/{kind}", s.handleChatDangerousRequest)
+ mux.HandleFunc("POST /api/chat/dangerous/{id}/decision", s.handleChatDangerousDecision)
mux.HandleFunc("GET /events", s.handleSSE)
mux.Handle("GET /", s.assets())
return s.requireToken(mux)
diff --git a/ui/dist/assets/index.css b/ui/dist/assets/index.css
index 6d42fa845..2516e011c 100644
--- a/ui/dist/assets/index.css
+++ b/ui/dist/assets/index.css
@@ -1 +1 @@
-:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);padding-right:var(--sp-4);font-weight:500}.nav-item .nav-label{display:none}.nav-item[aria-current=page] .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{display:none}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row,.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-actions{gap:var(--sp-1);white-space:nowrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:180px;color:var(--danger);font-size:var(--text-xs);white-space:normal}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-4) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.cfg-rows{gap:var(--sp-2);flex-direction:column;display:flex}.cfg-row{justify-content:space-between;align-items:baseline;gap:var(--sp-4);padding:var(--sp-2) 0;border-bottom:1px solid var(--border);display:flex}.cfg-row:last-child{border-bottom:0}.cfg-label{font-size:var(--text-sm);color:var(--fg-muted)}.cfg-value{font-size:var(--text-sm);color:var(--fg);text-align:right}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}
+:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);padding-right:var(--sp-4);font-weight:500}.nav-item .nav-label{display:none}.nav-item[aria-current=page] .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{display:none}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row,.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-actions{gap:var(--sp-1);white-space:nowrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:180px;color:var(--danger);font-size:var(--text-xs);white-space:normal}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-4) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.cfg-rows{gap:var(--sp-2);flex-direction:column;display:flex}.cfg-row{justify-content:space-between;align-items:baseline;gap:var(--sp-4);padding:var(--sp-2) 0;border-bottom:1px solid var(--border);display:flex}.cfg-row:last-child{border-bottom:0}.cfg-label{font-size:var(--text-sm);color:var(--fg-muted)}.cfg-value{font-size:var(--text-sm);color:var(--fg);text-align:right}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.chat-page{min-height:calc(100vh - 5rem)}.chat-topbar{justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;display:flex}.chat-kicker,.chat-workspace-label{color:var(--fg-muted);letter-spacing:.12em;font-size:.68rem;font-weight:700}.chat-topbar-actions{align-items:center;gap:.55rem;display:flex}.chat-topbar-actions .chat-select{min-width:0;max-width:14rem}.chat-update-panel{border:1px solid var(--border);color:var(--fg-muted);border-radius:.75rem;justify-content:space-between;align-items:center;gap:1rem;margin:0 0 .75rem;padding:.7rem .9rem;font-size:.8rem;display:flex}.chat-update-panel>div:first-child{gap:.2rem;display:grid}.chat-update-panel strong{color:var(--fg)}.chat-update-actions{flex-shrink:0;gap:.45rem;display:flex}.chat-dangerous-panel{border:1px solid color-mix(in srgb, var(--danger) 45%, var(--border));border-radius:.75rem;margin:0 0 .75rem;padding:.8rem .9rem}.chat-dangerous-head,.chat-dangerous-controls,.chat-dangerous-pending{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-dangerous-head{margin-bottom:.7rem}.chat-dangerous-controls{flex-wrap:wrap;align-items:stretch}.chat-dangerous-controls>div{flex:18rem;gap:.45rem;display:flex}.chat-dangerous-input{background:var(--surface-hover);min-width:0;color:var(--fg);border:1px solid var(--border-strong);font:inherit;border-radius:.5rem;flex:1;padding:.5rem .65rem}.chat-dangerous-pending-list{gap:.45rem;margin-top:.75rem;display:grid}.chat-dangerous-pending{border-top:1px solid var(--border);color:var(--fg-muted);padding-top:.55rem;font-size:.8rem}.chat-layout{grid-template-columns:242px minmax(0,1fr);gap:.75rem;min-height:72vh;display:grid}.chat-sidebar,.chat-workspace{background:var(--surface);border:1px solid var(--border);border-radius:1rem}.chat-sidebar{padding:.8rem}.chat-sidebar-head,.chat-toolbar,.chat-compose-actions{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-session-list{gap:.35rem;margin-top:1rem;display:grid}.chat-session{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.65rem;gap:.25rem;padding:.7rem;display:grid}.chat-session:hover,.chat-session.active{background:var(--surface-hover);color:var(--fg);border-color:var(--border-strong)}.chat-session span{font-size:.72rem}.chat-workspace{grid-template-rows:auto minmax(0,1fr) auto;min-width:0;display:grid;overflow:hidden}.chat-workspace-head{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;padding:.85rem 1.1rem;display:flex}.chat-session-tools{color:var(--fg-muted);margin-left:.6rem;font-size:.78rem;position:relative}.chat-session-tools summary{cursor:pointer}.chat-session-tool-list{z-index:2;background:var(--surface);border:1px solid var(--border-strong);border-radius:.65rem;flex-wrap:wrap;gap:.35rem;width:min(22rem,72vw);padding:.55rem;display:flex;position:absolute;top:calc(100% + .45rem);right:0;box-shadow:0 .7rem 2rem #0000004d}.chat-select{background:var(--surface-hover);color:var(--fg);border:1px solid var(--border-strong);border-radius:.5rem;padding:.5rem .65rem}.chat-transcript{align-content:start;gap:1rem;padding:1.25rem;display:grid;overflow:auto}.chat-empty-state{text-align:center;place-self:center;width:min(100%,40rem);padding:3rem 1rem}.chat-empty-mark{border:1px solid var(--border-strong);width:2.6rem;height:2.6rem;color:var(--accent);border-radius:.8rem;place-items:center;margin:0 auto 1rem;font-weight:700;display:grid}.chat-empty-state h2{letter-spacing:-.04em;margin:0;font-size:clamp(1.5rem,3vw,2.25rem)}.chat-empty-state p{color:var(--fg-muted);margin:.6rem 0 1.4rem}.chat-prompt-grid{flex-wrap:wrap;justify-content:center;gap:.5rem;display:flex}.chat-prompt{border:1px solid var(--border);background:var(--surface-hover);color:var(--fg-muted);cursor:pointer;border-radius:999px;padding:.55rem .75rem}.chat-prompt:hover{color:var(--fg);border-color:var(--border-strong)}.chat-bubble-row{display:flex}.chat-bubble-row.user{justify-content:flex-end}.chat-bubble{background:var(--surface-hover);border-radius:.85rem;max-width:min(78ch,86%);padding:.8rem 1rem;line-height:1.5}.chat-bubble-row.user .chat-bubble{background:color-mix(in srgb, var(--accent) 18%, var(--surface))}.chat-bubble-meta{color:var(--fg-muted);margin-bottom:.3rem;font-size:.7rem}.chat-bubble-text{white-space:pre-wrap;overflow-wrap:anywhere}.chat-bubble-text p{margin:0 0 .7rem}.chat-bubble-text p:last-child{margin-bottom:0}.chat-bubble-text h1,.chat-bubble-text h2,.chat-bubble-text h3{letter-spacing:-.02em;margin:.2rem 0 .6rem;line-height:1.2}.chat-bubble-text h1{font-size:1.25rem}.chat-bubble-text h2{font-size:1.1rem}.chat-bubble-text h3{font-size:1rem}.chat-bubble-text ul,.chat-bubble-text ol{margin:.25rem 0 .75rem;padding-left:1.35rem}.chat-bubble-text blockquote{border-left:3px solid var(--accent);color:var(--fg-muted);margin:.5rem 0;padding:.35rem .75rem}.chat-bubble-text code{background:color-mix(in srgb, var(--fg) 10%, transparent);border-radius:.3rem;padding:.1rem .3rem;font-size:.9em}.chat-bubble-text pre{border:1px solid var(--border);background:color-mix(in srgb, var(--surface) 75%, #000);border-radius:.5rem;margin:.6rem 0;padding:.75rem;overflow:auto}.chat-bubble-text pre code{background:0 0;padding:0}.chat-bubble-text a{color:var(--accent)}.chat-bubble-text table{border-collapse:collapse;width:100%;margin:.7rem 0;font-size:.92em}.chat-bubble-text th,.chat-bubble-text td{text-align:left;border:1px solid var(--border);padding:.45rem .6rem}.chat-bubble-text th{color:var(--fg);background:color-mix(in srgb, var(--surface) 70%, transparent);font-weight:700}.chat-compose{border-top:1px solid var(--border);padding:.85rem 1rem 1rem}.chat-composer-shell{background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:.9rem;padding:.7rem .8rem .55rem;position:relative}.chat-composer{resize:vertical;box-sizing:border-box;width:100%;min-height:3.3rem;color:var(--fg);font:inherit;background:0 0;border:0;padding:.25rem 0}.chat-composer:focus{outline:0}.chat-command-menu{z-index:3;background:var(--surface);border:1px solid var(--border-strong);border-radius:.7rem;gap:.15rem;max-height:18rem;padding:.35rem;display:grid;position:absolute;bottom:calc(100% - .25rem);left:.8rem;right:.8rem;overflow:auto;box-shadow:0 .7rem 2rem #0000004d}.chat-command-option{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.45rem;grid-template-columns:minmax(8rem,14rem) 1fr;align-items:center;gap:.65rem;padding:.5rem .6rem;display:grid}.chat-command-option:hover,.chat-command-option[aria-selected=true]{color:var(--fg);background:var(--surface-hover);border-color:var(--border)}.chat-command-option code{color:var(--fg)}.chat-compose-actions{margin-top:.55rem}.chat-hint,.chat-empty{color:var(--fg-muted);font-size:.78rem}.chat-command-help{color:var(--fg-muted);margin-right:auto;font-size:.78rem}.chat-command-help summary{cursor:pointer}.chat-command-list{min-width:min(34rem,70vw);max-width:40rem;padding-top:.4rem;line-height:1.45}.chat-command-item{grid-template-columns:minmax(10rem,16rem) 1fr;gap:.7rem;padding:.3rem 0;display:grid}.chat-command-item code{color:var(--fg)}@media (width<=760px){.chat-topbar,.chat-topbar-actions{flex-direction:column;align-items:flex-start}.chat-layout{grid-template-columns:1fr}.chat-sidebar{max-height:14rem;overflow:auto}}@media (width<=520px){.chat-update-panel{flex-direction:column;align-items:flex-start}}
diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js
index 5eeb132b3..7b7639180 100644
--- a/ui/dist/assets/index.js
+++ b/ui/dist/assets/index.js
@@ -1,9 +1,15 @@
-(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n!==void 0&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,help:``};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=c[e]||c.dashboard,r}async function u(e){let t=await fetch(e,{headers:{Accept:`application/json`},signal:AbortSignal.timeout(15e3)});if(t.status===401)throw new p(`unauthorised`,401);if(!t.ok)throw new p(`${t.status} ${t.statusText}`,t.status);return t.json()}function d(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function f(e){try{let t=(await e.text()).trim();if(t)return t.split(`
-`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),config:()=>u(`/api/config`),logs:e=>u(`/api/logs`+d(e)),memory:()=>u(`/api/memory`)};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&_(o,u===!1?`var(--danger)`:`var(--ok)`))}function _(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=``,u}function v({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`var(--danger)`,o=r/2,s=r/2,c=2*Math.PI*62*(240/360),l=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${o+62*Math.cos(n)} ${s+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${o+62*Math.cos(r)} ${s+62*Math.sin(r)}`].join(` `)},u=e(`svg.gauge`,{viewBox:`0 0 ${r} ${r*.78}`,role:`img`,"aria-label":`${n}: ${i}%`});return u.innerHTML=`
+(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n!==void 0&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,help:``};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=c[e]||c.dashboard,r}async function u(e){let t=await fetch(e,{headers:{Accept:`application/json`},signal:AbortSignal.timeout(15e3)});if(t.status===401)throw new p(`unauthorised`,401);if(!t.ok)throw new p(`${t.status} ${t.statusText}`,t.status);return t.json()}function d(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function f(e){try{let t=(await e.text()).trim();if(t)return t.split(`
+`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),config:()=>u(`/api/config`),logs:e=>u(`/api/logs`+d(e)),memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&_(o,u===!1?`var(--danger)`:`var(--ok)`))}function _(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=``,u}function v({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`var(--danger)`,o=r/2,s=r/2,c=2*Math.PI*62*(240/360),l=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${o+62*Math.cos(n)} ${s+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${o+62*Math.cos(r)} ${s+62*Math.sin(r)}`].join(` `)},u=e(`svg.gauge`,{viewBox:`0 0 ${r} ${r*.78}`,role:`img`,"aria-label":`${n}: ${i}%`});return u.innerHTML=`
`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function y(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}function b(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),_=e(`h1.hero-title`,C()),v=r(`connecting`,`idle`),y=[],b=new Map;D(),k();let S=h(e=>{y.unshift(e),y.splice(50),O()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,S);function D(){n(t,e(`div.hero`,e(`div`,_,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),O()}function O(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>x(e,b)))}async function k(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);O(),A(e),_.textContent=t?.operator?`${C()}, ${t.operator}`:C(),j(e),M(t),N(e,n),P(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Retry`))}}function A(t){let r=t?.statuses||{},i=(r.parked||0)+(r.waiting_human||0),a=r.running||0;n(p,i>0&&e(`a.btn.btn-attention`,{href:`#/tasks`},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:`#/tasks`},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Refresh`))}function j(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,g({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),g({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),g({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),g({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:E(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function M(t){let r=!t?.steps?.length;if(d.classList.toggle(`dash-top-standalone`,r),r)return n(c);let i=t.steps.filter(e=>!e.done);if(i.length){let r=Math.round((t.steps.length-i.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(F))));return}d.classList.remove(`dash-top-standalone`),n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`span.setup-pct`,l(`check`,{size:16})))))}function N(e,t){w(u,e,t)}function P(e){T(f,e)}function F(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function x(t,n){let r=S(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function S(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function C(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function w(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),v({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function T(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),y([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function E(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}var D={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function O(e){return D[e]||e||`Unknown`}function k(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{h=e.target.value.trim().toLowerCase(),k()}}),d=e(`select.task-filter`,{onchange:e=>{p=e.target.value,k()}},e(`option`,{value:``},`All statuses`),...Object.entries(D).map(([t,n])=>e(`option`,{value:t},n))),f=[],p=``,h=``,_=Number(t.get(`task`)),v=Number.isFinite(_)&&_>0?_:null,y=``,b=new Map,x=new Map,S=new Set;C(),w();function C(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:w},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,u,d)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function w(){try{[f,y]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),T(),k(),v&&f.some(e=>String(e.id)===String(v))&&R(v)}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function T(){let e=f.length,t={};for(let e of f)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,g({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),g({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),g({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),g({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function E(){return f.filter(e=>p&&e.status!==p?!1:!h||`${e.title} ${e.repo}`.toLowerCase().includes(h))}function k(){let t=E();if(!f.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),v===e.id&&l.append(I(e))}function A(t){return e(`tr.task-row`,{onclick:()=>{v=v===t.id?null:t.id,k(),v===t.id&&R(t.id)}},e(`td.mono`,P(t)??`${t.owner}/${t.repo}`),e(`td.mono`,F(t)??`#${t.issue_number}`),e(`td.strong`,t.title||`(untitled)`),e(`td`,r(O(t.status),i(t.status))),e(`td`,t.workflow||`—`),e(`td`,t.stage||`—`),e(`td`,{title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,j(t)))}function j(t){let n=x.get(t.id),r=n?e(`span.task-action-error`,n):null,i=S.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a);return t.status===`waiting_human`?e(`div.task-actions`,r,a(`button.btn.btn-small`,`approve`,`Approve`),a(`button.btn.btn-small.btn-quiet`,`reject`,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue and cannot be undone from here.`)):t.status===`parked`?e(`div.task-actions`,r,a(`button.btn.btn-small`,`retry`,`Retry`)):r||`—`}async function M(e,t){x.delete(e),S.add(e),k();try{await m.taskAction(e,t),S.delete(e),await w()}catch(t){S.delete(e),x.set(e,t.message||`Action failed`),k()}}function N(e){return!y||!e.owner||!e.repo?null:`${y.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function P(t){let n=N(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function F(t){let n=N(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function I(t){let n=b.get(t.id);return e(`tr.task-timeline-row`,e(`td`,{colspan:8},t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>R(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(L)):s(`No events yet`,`This task has not recorded any transitions.`)))}function L(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function R(e){try{let t=await m.task(e);b.set(e,t||[])}catch{b.set(e,null)}k()}return o}function A(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var j={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function M(e){return j[e]?j[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function N(e,t){return t?Math.round(e/t*100):0}function P(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function F(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function I(){let t=e(`div`),r=e(`div`),i=e(`div`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),r,i)}async function o(){try{let e=await m.workflows();c(e?.workflows||[]),l(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function c(t){if(!t.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>{let n=N(t.merged,t.runs);return e(`tr`,e(`td.strong`,M(t.workflow)),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),P(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function l(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,M(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,F(t.avg_ms)),P(N(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,M(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),P(N(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function L(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),t.configured?r(`connected`,`ok`):r(`not configured`,`idle`)),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail))}return t}function R(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},`Refresh`))),r)}async function a(){try{o(await m.config())}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}function o(t){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}n(r,ee(t.identity),te(t.repositories),re(t.models,t.providers),ae(t.budgets),V(t.agent),U(t.storage,t.containers),G(t.web))}return t}function z(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function B(t,n){return e(`div.cfg-row`,e(`span.cfg-label`,t),e(`span.cfg-value.mono`,n??`—`))}function ee(t){return t?z(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.cfg-rows`,B(`Bot account`,t.bot_user),B(`Commit author email`,t.bot_email),B(`Pickup label`,t.label),B(`Forge type`,t.forge_type),B(`Forge host`,t.forge_host),B(`Max diff size (lines)`,t.diff_cap_lines))):z(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function te(t){return t?.length?z(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,ne(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):z(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function ne(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function re(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.cfg-rows`,...i.map(([e,t])=>B(ie(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return z(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ie(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function ae(t){return t?z(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.cfg-rows`,B(`Max steps`,t.max_steps||`Unlimited`),B(`Max tokens`,t.max_tokens||`Unlimited`),B(`Wall clock`,t.wall_clock),B(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`))):z(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function V(t){return t?z(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.cfg-rows`,B(`Execution mode`,H(t.mode)),B(`Worker command`,t.command),B(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):z(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function H(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function U(t,n){let r=[];return t&&r.push(e(`h3.cfg-subhead`,`Paths`),e(`div.cfg-rows`,B(`Work directory`,t.work_dir),B(`Task database`,t.db_path),B(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`),B(`Daemon plugin directory`,t.plugin_dir||`None`),B(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`))),n&&r.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.cfg-rows`,B(`Sandboxing enabled`,n.enabled?`Yes`:`No`),B(`Agent image`,n.image||`Not set`),B(`Max concurrent tasks`,n.max_concurrency||`Unlimited`),B(`Container max lifetime`,n.max_uptime),B(`Persistent volume retention`,n.volume_ttl),B(`How images are refreshed`,W(n.pull_policy)),B(`Docker network`,n.network||`Auto-detected`))),r.length||r.push(s(`Not available`)),z(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...r)}function W(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function G(t){return t?z(`Dashboard`,`This dashboard's own listen address.`,e(`div.cfg-rows`,B(`Listen address`,t.listen===`off`?`Disabled`:t.listen))):z(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var K=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function q(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function oe(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=e(`select.log-select`,{onchange:e=>v({level:e.target.value})},...K.map(t=>e(`option`,{value:t.value},t.label))),f=e(`select.log-select`,{onchange:e=>v({component:e.target.value})}),p=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:ue(e=>v({q:e.target.value}),250)}),g=e(`button.btn`,{onclick:y},`Pause`);b(),x();let _=h(e=>C(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,_);function v(e){c={...c,...e},x()}function y(){l=!l,g.textContent=l?`Resume`:`Pause`,g.classList.toggle(`btn-primary`,l)}function b(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,g,e(`button.btn`,{onclick:x},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,d,f,p),e(`div.log-status`,o,a)),i))}async function x(){n(i,e(`div.log-loading`,`Loading…`));try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});if(e.disabled){n(i,s(`File logging is off`,`Set [log] file in your config to keep a durable record. Live lines below still stream while this page is open.`)),o.textContent=``;return}S(e.components||[]),o.textContent=e.truncated?`showing the most recent matches from ${e.file}`:e.file||``;let t=e.entries||[];if(!t.length){n(i,s(`Nothing matches`,`Try a wider level or clear the search.`));return}n(i,...t.map(J)),i.scrollTop=i.scrollHeight}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function S(t){if(le(t,u))return;u=t;let r=c.component;n(f,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),f.value=r}function C(e){if(l)return;let t={time:e.at||new Date().toISOString(),level:e.level||`INFO`,msg:e.detail||e.message||e.kind||`event`,fields:e.task_id?{task:e.task_id}:null};if(!w(t))return;let n=i.scrollHeight-i.scrollTop-i.clientHeight<40;for(i.querySelector(`.empty, .log-loading`)&&i.replaceChildren(),i.append(J({...t,message:t.msg}));i.children.length>1e3;)i.firstElementChild.remove();n&&(i.scrollTop=i.scrollHeight)}function w(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.msg} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function J(t){let n=t.fields||{};return e(`div.log-row.log-${q(t.level)}`,e(`span.log-time.mono`,ce(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(se(n))))))}function se(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function ce(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function le(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function ue(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function de(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(fe)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function fe(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Y(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Y(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var X=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:b},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:k},{path:`/logs`,label:`Logs`,icon:`logs`,view:oe},{path:`/skills`,label:`Skills`,icon:`skills`,view:A},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:I},{path:`/memory`,label:`Memory`,icon:`memory`,view:de},{path:`/channels`,label:`Channels`,icon:`channels`,view:L},{path:`/settings`,label:`Configuration`,icon:`settings`,view:R}],Z=`archie.theme`;function Q(e){document.documentElement.dataset.theme=e,localStorage.setItem(Z,e)}function $(){return localStorage.getItem(Z)||`dark`}function pe(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...X.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Q($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=X.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur())}});return{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,e(`div.topbar-search`,l(`search`,{size:15}),o),e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function me(){Q($());let t=e(`main.main`),r=pe(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=X.find(e=>e.path===i)||X[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):he(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function he(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}me();
\ No newline at end of file
+ class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function y(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}function b(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),_=e(`h1.hero-title`,C()),v=r(`connecting`,`idle`),y=[],b=new Map;D(),k();let S=h(e=>{y.unshift(e),y.splice(50),O()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,S);function D(){n(t,e(`div.hero`,e(`div`,_,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),O()}function O(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>x(e,b)))}async function k(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);O(),A(e),_.textContent=t?.operator?`${C()}, ${t.operator}`:C(),j(e),M(t),N(e,n),P(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Retry`))}}function A(t){let r=t?.statuses||{},i=(r.parked||0)+(r.waiting_human||0),a=r.running||0;n(p,i>0&&e(`a.btn.btn-attention`,{href:`#/tasks`},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:`#/tasks`},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Refresh`))}function j(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,g({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),g({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),g({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),g({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:E(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function M(t){let r=!t?.steps?.length;if(d.classList.toggle(`dash-top-standalone`,r),r)return n(c);let i=t.steps.filter(e=>!e.done);if(i.length){let r=Math.round((t.steps.length-i.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(F))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`span.setup-pct`,l(`check`,{size:16})))))}function N(e,t){w(u,e,t)}function P(e){T(f,e)}function F(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function x(t,n){let r=S(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function S(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function C(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function w(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),v({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function T(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),y([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function E(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}var D={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function O(e){return D[e]||e||`Unknown`}function k(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{h=e.target.value.trim().toLowerCase(),k()}}),d=e(`select.task-filter`,{onchange:e=>{p=e.target.value,k()}},e(`option`,{value:``},`All statuses`),...Object.entries(D).map(([t,n])=>e(`option`,{value:t},n))),f=[],p=``,h=``,_=Number(t.get(`task`)),v=Number.isFinite(_)&&_>0?_:null,y=``,b=new Map,x=new Map,S=new Set;C(),w();function C(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:w},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,u,d)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function w(){try{[f,y]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),T(),k(),v&&f.some(e=>String(e.id)===String(v))&&R(v)}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function T(){let e=f.length,t={};for(let e of f)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,g({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),g({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),g({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),g({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function E(){return f.filter(e=>p&&e.status!==p?!1:!h||`${e.title} ${e.repo}`.toLowerCase().includes(h))}function k(){let t=E();if(!f.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),v===e.id&&l.append(I(e))}function A(t){return e(`tr.task-row`,{onclick:()=>{v=v===t.id?null:t.id,k(),v===t.id&&R(t.id)}},e(`td.mono`,P(t)??`${t.owner}/${t.repo}`),e(`td.mono`,F(t)??`#${t.issue_number}`),e(`td.strong`,t.title||`(untitled)`),e(`td`,r(O(t.status),i(t.status))),e(`td`,t.workflow||`—`),e(`td`,t.stage||`—`),e(`td`,{title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,j(t)))}function j(t){let n=x.get(t.id),r=n?e(`span.task-action-error`,n):null,i=S.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a);return t.status===`waiting_human`?e(`div.task-actions`,r,a(`button.btn.btn-small`,`approve`,`Approve`),a(`button.btn.btn-small.btn-quiet`,`reject`,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue and cannot be undone from here.`)):t.status===`parked`?e(`div.task-actions`,r,a(`button.btn.btn-small`,`retry`,`Retry`)):r||`—`}async function M(e,t){x.delete(e),S.add(e),k();try{await m.taskAction(e,t),S.delete(e),await w()}catch(t){S.delete(e),x.set(e,t.message||`Action failed`),k()}}function N(e){return!y||!e.owner||!e.repo?null:`${y.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function P(t){let n=N(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function F(t){let n=N(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function I(t){let n=b.get(t.id);return e(`tr.task-timeline-row`,e(`td`,{colspan:8},t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>R(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(L)):s(`No events yet`,`This task has not recorded any transitions.`)))}function L(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function R(e){try{let t=await m.task(e);b.set(e,t||[])}catch{b.set(e,null)}k()}return o}function A(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var j={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function M(e){return j[e]?j[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function N(e,t){return t?Math.round(e/t*100):0}function P(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function F(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function I(){let t=e(`div`),r=e(`div`),i=e(`div`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),r,i)}async function o(){try{let e=await m.workflows();c(e?.workflows||[]),l(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function c(t){if(!t.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>{let n=N(t.merged,t.runs);return e(`tr`,e(`td.strong`,M(t.workflow)),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),P(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function l(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,M(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,F(t.avg_ms)),P(N(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,M(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),P(N(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function L(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),t.configured?r(`connected`,`ok`):r(`not configured`,`idle`)),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail))}return t}function R(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},`Refresh`))),r)}async function a(){try{o(await m.config())}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}function o(t){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}n(r,V(t.identity),H(t.repositories),W(t.models,t.providers),K(t.budgets),q(t.agent),ee(t.storage,t.containers),ne(t.web))}return t}function z(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function B(t,n){return e(`div.cfg-row`,e(`span.cfg-label`,t),e(`span.cfg-value.mono`,n??`—`))}function V(t){return t?z(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.cfg-rows`,B(`Bot account`,t.bot_user),B(`Commit author email`,t.bot_email),B(`Pickup label`,t.label),B(`Forge type`,t.forge_type),B(`Forge host`,t.forge_host),B(`Max diff size (lines)`,t.diff_cap_lines))):z(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function H(t){return t?.length?z(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,U(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):z(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function U(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function W(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.cfg-rows`,...i.map(([e,t])=>B(G(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return z(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function G(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function K(t){return t?z(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.cfg-rows`,B(`Max steps`,t.max_steps||`Unlimited`),B(`Max tokens`,t.max_tokens||`Unlimited`),B(`Wall clock`,t.wall_clock),B(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`))):z(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function q(t){return t?z(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.cfg-rows`,B(`Execution mode`,J(t.mode)),B(`Worker command`,t.command),B(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):z(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function J(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function ee(t,n){let r=[];return t&&r.push(e(`h3.cfg-subhead`,`Paths`),e(`div.cfg-rows`,B(`Work directory`,t.work_dir),B(`Task database`,t.db_path),B(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`),B(`Daemon plugin directory`,t.plugin_dir||`None`),B(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`))),n&&r.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.cfg-rows`,B(`Sandboxing enabled`,n.enabled?`Yes`:`No`),B(`Agent image`,n.image||`Not set`),B(`Max concurrent tasks`,n.max_concurrency||`Unlimited`),B(`Container max lifetime`,n.max_uptime),B(`Persistent volume retention`,n.volume_ttl),B(`How images are refreshed`,te(n.pull_policy)),B(`Docker network`,n.network||`Auto-detected`))),r.length||r.push(s(`Not available`)),z(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...r)}function te(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function ne(t){return t?z(`Dashboard`,`This dashboard's own listen address.`,e(`div.cfg-rows`,B(`Listen address`,t.listen===`off`?`Disabled`:t.listen))):z(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var re=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function ie(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function ae(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=e(`select.log-select`,{onchange:e=>v({level:e.target.value})},...re.map(t=>e(`option`,{value:t.value},t.label))),f=e(`select.log-select`,{onchange:e=>v({component:e.target.value})}),p=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:ue(e=>v({q:e.target.value}),250)}),g=e(`button.btn`,{onclick:y},`Pause`);b(),x();let _=h(e=>C(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,_);function v(e){c={...c,...e},x()}function y(){l=!l,g.textContent=l?`Resume`:`Pause`,g.classList.toggle(`btn-primary`,l)}function b(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,g,e(`button.btn`,{onclick:x},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,d,f,p),e(`div.log-status`,o,a)),i))}async function x(){n(i,e(`div.log-loading`,`Loading…`));try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});if(e.disabled){n(i,s(`File logging is off`,`Set [log] file in your config to keep a durable record. Live lines below still stream while this page is open.`)),o.textContent=``;return}S(e.components||[]),o.textContent=e.truncated?`showing the most recent matches from ${e.file}`:e.file||``;let t=e.entries||[];if(!t.length){n(i,s(`Nothing matches`,`Try a wider level or clear the search.`));return}n(i,...t.map(oe)),i.scrollTop=i.scrollHeight}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function S(t){if(le(t,u))return;u=t;let r=c.component;n(f,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),f.value=r}function C(e){if(l)return;let t={time:e.at||new Date().toISOString(),level:e.level||`INFO`,msg:e.detail||e.message||e.kind||`event`,fields:e.task_id?{task:e.task_id}:null};if(!w(t))return;let n=i.scrollHeight-i.scrollTop-i.clientHeight<40;for(i.querySelector(`.empty, .log-loading`)&&i.replaceChildren(),i.append(oe({...t,message:t.msg}));i.children.length>1e3;)i.firstElementChild.remove();n&&(i.scrollTop=i.scrollHeight)}function w(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.msg} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function oe(t){let n=t.fields||{};return e(`div.log-row.log-${ie(t.level)}`,e(`span.log-time.mono`,ce(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(se(n))))))}function se(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function ce(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function le(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function ue(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function de(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(fe)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function fe(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,pe(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function pe(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var me=`archie.web.chat.channel`;function Y(){let e=localStorage.getItem(me);return e||(e=crypto.randomUUID(),localStorage.setItem(me,e)),e}function he(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function X(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i{i.length&&(n.append(e(`p`,X(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;te(`td`,X(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,X(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,X(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,X((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,X(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(`
+`)))),n}function Z(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function _e(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function ve(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?ge(r):e(`div.chat-bubble-text`,r)))}function ye(){let t=e(`div.chat-page`),r=e(`div.chat-session-list`),i=e(`div.chat-transcript`),a=e(`textarea.chat-composer`,{rows:3,placeholder:`Message Archie… (commands like /status and /new work here)`,"aria-label":`Message Archie`}),o=e(`button.btn.btn-primary`,`Send`),s=e(`button.btn`,{disabled:!0},`Stop`),c=e(`span.chat-status`,`Ready`),l=e(`select.chat-select`,{"aria-label":`Personality`}),u=e(`select.chat-select`,{"aria-label":`Provider`,hidden:!0}),d=e(`select.chat-select`,{"aria-label":`Model`}),f=e(`button.btn`,{hidden:!0,onclick:()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,K())}},`Reload Telegram`),p=``,h=[],g=!1,_=null,v=null,y={},b=[],x=[],S=0,C=e(`div.chat-empty-state`,e(`span.chat-empty-mark`,`A`),e(`h2`,`What are we working on?`),e(`p`,`Ask Archie anything, or start with one of these prompts.`),e(`div.chat-prompt-grid`,...[`Summarise active tasks`,`Show running agents`,`Check system status`].map(t=>e(`button.chat-prompt`,{onclick:()=>{a.value=t,a.focus()}},t))));function w(e){C.remove(),i.append(ve(e)),i.scrollTop=i.scrollHeight}function T(){if(r.replaceChildren(),M.hidden=!p,!h.length){r.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let t of h){let n=e(`button.chat-session`,{class:p===t.session_id?`active`:``,onclick:()=>G(t.session_id)},e(`strong`,he(t)),e(`span`,new Date(t.last_active_at).toLocaleString()));r.append(n)}}function E(t){y=t,l.replaceChildren(e(`option`,{value:``},`Personality`));for(let n of t.personas||[])l.append(e(`option`,{value:n},n));l.value=t.active_persona||``;let n=t.providers||[];u.hidden=n.length===0,u.replaceChildren(e(`option`,{value:``},`Provider`));for(let t of n)u.append(e(`option`,{value:t},t));u.value=t.active_provider||n[0]||``,D(u.value),f.hidden=!t.restart_available,A.hidden=!t.dangerous_available,t.dangerous_available&&V()}function D(t){let n=y.models_by_provider||{},r=t&&n[t]?n[t]:y.models||[];d.replaceChildren(e(`option`,{value:``},`Model`));for(let t of r)d.append(e(`option`,{value:t},t));d.value=y.active_model||``}function O(t){let n=t.commands||[];b=n.map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);let r=e(`div.chat-command-list`);n.length||r.append(e(`span`,`Send a message to begin.`));for(let t of n){let n=typeof t==`string`?{command:t,usage:t,description:``}:t;r.append(e(`div.chat-command-item`,e(`code`,n.usage||n.command),e(`span`,n.description||``)))}J.replaceChildren(e(`summary`,`Available commands (${n.length})`),r)}let k=e(`div.chat-update-panel`),A=e(`div.chat-dangerous-panel`,{hidden:!0}),j=e(`div.chat-command-menu`,{hidden:!0,role:`listbox`,"aria-label":`Commands`}),M=e(`details.chat-session-tools`,{hidden:!0});function N(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function P(){j.hidden=!0,x=[],S=0}function F(){let t=N();if(t===null){P();return}if(x=b.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!x.length){P();return}S=Math.min(S,x.length-1),j.replaceChildren(...x.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":n===S,onmousedown:e=>e.preventDefault(),onclick:()=>I(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),j.hidden=!1}function I(e){let t=x[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),P(),a.focus()}function L(t){k.replaceChildren(),v=t?.snapshot||null;let n=t?.available||[];if(!n.length){k.append(e(`span`,t?.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`));return}k.append(e(`div`,e(`strong`,`Update available`),e(`span`,n.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:async()=>{await m.chatUpdateDefer(v),L({snapshot:{deferred:!0},available:[]}),c.textContent=`Update deferred`}},`Defer`),t.can_install?e(`button.btn.btn-primary`,{onclick:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(v),c.textContent=`Update started`,R()}},`Install update`):null))}async function R(){try{L(await m.chatUpdate())}catch(t){k.replaceChildren(e(`span`,t.message||`Updates unavailable`))}}function z(t,n,r){return e(`button.btn`,{onclick:async()=>{try{await m.chatDangerousDecision(t,n),c.textContent=n===`deny`?`Action denied`:`Action approved`,await V()}catch(e){c.textContent=e.message||`Approval failed`}}},r)}function B(t){A.replaceChildren();let n=t?.checkpoints||[],r=t?.pending||[],i=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...n.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),a=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),o=(e,t)=>async()=>{if(String(t.value||t).trim())try{await m.chatDangerousRequest(e,String(t.value||t).trim()),c.textContent=`Approval requested`,await V()}catch(e){c.textContent=e.message||`Could not request action`}},s=r.length?r.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,z(t.id,`approve`,`Approve`),z(t.id,`permanent`,`Approve for 24h`),z(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];A.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,i,e(`button.btn`,{onclick:o(`rollback`,i)},`Request rollback`)),e(`div`,a,e(`button.btn`,{onclick:o(`stop`,a)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...s))}async function V(){try{B(await m.chatDangerous())}catch(t){A.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function H(){let e=await m.chatSessions();h=e.sessions||[],E(e),O(e),T(),!p&&h[0]&&await G(h[0].session_id)}async function U(e){if(p)try{c.textContent=`Working…`;let t=await m.chatMessage(Y(),e);t.session_id&&(p=t.session_id),c.textContent=t.reply||`Session updated`,await H(),p&&await G(p),M.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function W(e,t){let n=window.prompt(t);n?.trim()&&U(`${e} ${n.trim()}`)}async function G(e){p=e,T(),i.replaceChildren(),await m.chatMessage(Y(),`/resume ${e}`),l.value=y.active_personas?.[e]||y.active_persona||``;let t=await m.chatMessages(e);for(let e of t)w(e);i.children.length||i.append(C)}async function K(){let t=a.value.trim();if(!t||g)return;P(),g=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=`Thinking…`,w({from:`web`,text:t}),a.value=``;let n=e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-bubble-text`)));i.append(n);let r=n.querySelector(`.chat-bubble-text`),l;try{_=new AbortController,l=setTimeout(()=>_.abort(),12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Y(),source_id:crypto.randomUUID(),text:t}),signal:_.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let n=e.body.getReader(),i=new TextDecoder,a=``;for(;;){let{value:e,done:t}=await n.read();a+=i.decode(e||new Uint8Array,{stream:!t});let o=a.split(`
+
+`);a=o.pop()||``;for(let e of o){let t=e.split(`
+`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(p=n.session_id),n.type===`delta`&&(r.textContent+=n.text),n.type===`done`&&!r.textContent&&(r.textContent=n.text),n.type===`error`)throw Error(n.text)}if(t)break}r.isConnected&&r.replaceWith(ge(r.textContent)),c.textContent=`Ready`,await H(),p&&await G(p)}catch(e){e.name===`AbortError`?(r.textContent=`Turn stopped.`,c.textContent=`Stopped`):(r.textContent=`Unable to complete that turn: ${e.message||e}`,c.textContent=`Error`)}finally{clearTimeout(l),_=null,g=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=K,s.onclick=()=>{let e=p;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),_?.abort()},a.oninput=F,a.onkeydown=e=>{if(!j.hidden&&x.length){if(e.key===`ArrowDown`){e.preventDefault(),S=(S+1)%x.length,F();return}if(e.key===`ArrowUp`){e.preventDefault(),S=(S+x.length-1)%x.length,F();return}if(e.key===`Enter`&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),I(S);return}if(e.key===`Escape`){e.preventDefault(),P();return}}e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),K())},l.onchange=async()=>{!p||!l.value||(await m.chatPersona(p,l.value),y.active_personas={...y.active_personas||{},[p]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{D(u.value),u.value&&await q(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await q(`/model ${d.value}`)};async function q(e){try{let t=await m.chatMessage(Y(),e);c.textContent=t.reply||`Model updated`,await H()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}let J=e(`details.chat-command-help`),ee=e(`button.btn`,{onclick:R},`Check updates`),te=e(`div.chat-session-tool-list`,e(`button.btn`,{type:`button`,onclick:()=>U(`/retry`)},`Retry`),e(`button.btn`,{type:`button`,onclick:()=>U(`/undo`)},`Undo`),e(`button.btn`,{type:`button`,onclick:()=>W(`/title`,`Session title`)},`Rename`),e(`button.btn`,{type:`button`,onclick:()=>W(`/branch`,`Branch name (optional)`)},`Branch`),e(`button.btn`,{type:`button`,onclick:()=>U(`/compress --preview`)},`Preview compression`));return M.append(e(`summary`,`Session actions`),te),n(t,e(`div.chat-page-content`,e(`div.chat-topbar`,e(`div`,e(`span.chat-kicker`,`ARCHIE WORKSPACE`),e(`h1.page-title`,`Chat`)),e(`div.chat-topbar-actions`,e(`span.chat-status`,c),f,ee,l,u,d)),k,A,e(`div.chat-layout`,e(`aside.chat-sidebar`,e(`div.chat-sidebar-head`,e(`strong`,`Conversations`),e(`button.btn.btn-primary`,{onclick:()=>{a.value=`/new`,K()}},`+ New chat`)),r),e(`section.chat-workspace`,e(`div.chat-workspace-head`,e(`span.chat-workspace-label`,`PERSONAL ASSISTANT`),J,M),i,e(`div.chat-compose`,e(`div.chat-composer-shell`,a,j,e(`div.chat-compose-actions`,e(`span.chat-hint`,`⌘/Ctrl + Enter to send`),s,o))))))),i.append(C),H().catch(e=>{c.textContent=e.message||`Chat unavailable`}),R(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:b},{path:`/chat`,label:`Chat`,icon:`chat`,view:ye},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:k},{path:`/logs`,label:`Logs`,icon:`logs`,view:ae},{path:`/skills`,label:`Skills`,icon:`skills`,view:A},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:I},{path:`/memory`,label:`Memory`,icon:`memory`,view:de},{path:`/channels`,label:`Channels`,icon:`channels`,view:L},{path:`/settings`,label:`Configuration`,icon:`settings`,view:R}],be=`archie.theme`;function xe(e){document.documentElement.dataset.theme=e,localStorage.setItem(be,e)}function $(){return localStorage.getItem(be)||`dark`}function Se(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{xe($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur())}});return{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,e(`div.topbar-search`,l(`search`,{size:15}),o),e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function Ce(){xe($());let t=e(`main.main`),r=Se(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):we(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function we(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}Ce();
\ No newline at end of file
diff --git a/ui/src/base/api.js b/ui/src/base/api.js
index b132df712..deb9f6ede 100644
--- a/ui/src/base/api.js
+++ b/ui/src/base/api.js
@@ -71,6 +71,67 @@ export const api = {
config: () => req("/api/config"),
logs: (params) => req("/api/logs" + qs(params)),
memory: () => req("/api/memory"),
+ chatSessions: () => req("/api/chat/sessions"),
+ chatMessages: (id) => req(`/api/chat/sessions/${encodeURIComponent(id)}/messages`),
+ chatCancel: async (sessionID) => {
+ const res = await fetch("/api/chat/cancel", {
+ method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
+ body: JSON.stringify({ session_id: sessionID }), signal: AbortSignal.timeout(15000),
+ });
+ if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
+ return res.json();
+ },
+ chatMessage: async (channelID, text) => {
+ const res = await fetch("/api/chat/message", {
+ method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
+ body: JSON.stringify({ channel_id: channelID, source_id: crypto.randomUUID(), text }),
+ signal: AbortSignal.timeout(15000),
+ });
+ if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
+ return res.json();
+ },
+ chatPersona: async (sessionID, name) => {
+ const res = await fetch("/api/chat/persona", {
+ method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
+ body: JSON.stringify({ session_id: sessionID, name }), signal: AbortSignal.timeout(15000),
+ });
+ if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
+ return res.json();
+ },
+ chatUpdate: () => req("/api/chat/update"),
+ chatUpdateDefer: async (snapshot) => {
+ const res = await fetch("/api/chat/update/defer", {
+ method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
+ body: JSON.stringify({ snapshot }), signal: AbortSignal.timeout(15000),
+ });
+ if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
+ return res.json();
+ },
+ chatUpdateInstall: async (snapshot) => {
+ const res = await fetch("/api/chat/update/install", {
+ method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
+ body: JSON.stringify({ snapshot }), signal: AbortSignal.timeout(120000),
+ });
+ if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
+ return res.json();
+ },
+ chatDangerous: () => req("/api/chat/dangerous"),
+ chatDangerousRequest: async (kind, spec) => {
+ const res = await fetch(`/api/chat/dangerous/${encodeURIComponent(kind)}`, {
+ method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
+ body: JSON.stringify({ spec }), signal: AbortSignal.timeout(15000),
+ });
+ if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
+ return res.json();
+ },
+ chatDangerousDecision: async (id, decision) => {
+ const res = await fetch(`/api/chat/dangerous/${encodeURIComponent(id)}/decision`, {
+ method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
+ body: JSON.stringify({ decision }), signal: AbortSignal.timeout(15000),
+ });
+ if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
+ return res.json();
+ },
};
/**
diff --git a/ui/src/base/icons.js b/ui/src/base/icons.js
index 261e6e8d2..88bda69b6 100644
--- a/ui/src/base/icons.js
+++ b/ui/src/base/icons.js
@@ -9,6 +9,7 @@
const paths = {
dashboard: '',
+ chat: '',
tasks: '',
logs: '',
skills: '',
diff --git a/ui/src/chat/chat.css b/ui/src/chat/chat.css
new file mode 100644
index 000000000..e7379e0c1
--- /dev/null
+++ b/ui/src/chat/chat.css
@@ -0,0 +1,77 @@
+.chat-page { min-height: calc(100vh - 5rem); }
+.chat-topbar { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 1rem; }
+.chat-kicker, .chat-workspace-label { color: var(--fg-muted); font-size: .68rem; font-weight: 700; letter-spacing: .12em; }
+.chat-topbar-actions { display: flex; align-items: center; gap: .55rem; }
+.chat-topbar-actions .chat-select { max-width: 14rem; min-width: 0; }
+.chat-update-panel { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin: 0 0 .75rem; padding: .7rem .9rem; border: 1px solid var(--border); border-radius: .75rem; color: var(--fg-muted); font-size: .8rem; }
+.chat-update-panel > div:first-child { display: grid; gap: .2rem; }
+.chat-update-panel strong { color: var(--fg); }
+.chat-update-actions { display: flex; gap: .45rem; flex-shrink: 0; }
+.chat-dangerous-panel { margin: 0 0 .75rem; padding: .8rem .9rem; border: 1px solid color-mix(in srgb, var(--danger) 45%, var(--border)); border-radius: .75rem; }
+.chat-dangerous-head, .chat-dangerous-controls, .chat-dangerous-pending { display: flex; align-items: center; justify-content: space-between; gap: .6rem; }
+.chat-dangerous-head { margin-bottom: .7rem; }
+.chat-dangerous-controls { align-items: stretch; flex-wrap: wrap; }
+.chat-dangerous-controls > div { display: flex; gap: .45rem; flex: 1 1 18rem; }
+.chat-dangerous-input { min-width: 0; flex: 1; padding: .5rem .65rem; background: var(--surface-hover); color: var(--fg); border: 1px solid var(--border-strong); border-radius: .5rem; font: inherit; }
+.chat-dangerous-pending-list { display: grid; gap: .45rem; margin-top: .75rem; }
+.chat-dangerous-pending { padding-top: .55rem; border-top: 1px solid var(--border); color: var(--fg-muted); font-size: .8rem; }
+.chat-layout { display: grid; grid-template-columns: 242px minmax(0, 1fr); gap: .75rem; min-height: 72vh; }
+.chat-sidebar, .chat-workspace { background: var(--surface); border: 1px solid var(--border); border-radius: 1rem; }
+.chat-sidebar { padding: .8rem; }
+.chat-sidebar-head, .chat-toolbar, .chat-compose-actions { display: flex; align-items: center; justify-content: space-between; gap: .6rem; }
+.chat-session-list { display: grid; gap: .35rem; margin-top: 1rem; }
+.chat-session { display: grid; gap: .25rem; text-align: left; background: transparent; color: var(--fg-muted); border: 1px solid transparent; border-radius: .65rem; padding: .7rem; cursor: pointer; }
+.chat-session:hover, .chat-session.active { background: var(--surface-hover); color: var(--fg); border-color: var(--border-strong); }
+.chat-session span { font-size: .72rem; }
+.chat-workspace { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; overflow: hidden; min-width: 0; }
+.chat-workspace-head { display: flex; align-items: center; justify-content: space-between; padding: .85rem 1.1rem; border-bottom: 1px solid var(--border); }
+.chat-session-tools { position: relative; margin-left: .6rem; color: var(--fg-muted); font-size: .78rem; }
+.chat-session-tools summary { cursor: pointer; }
+.chat-session-tool-list { position: absolute; z-index: 2; right: 0; top: calc(100% + .45rem); display: flex; flex-wrap: wrap; gap: .35rem; width: min(22rem, 72vw); padding: .55rem; background: var(--surface); border: 1px solid var(--border-strong); border-radius: .65rem; box-shadow: 0 .7rem 2rem color-mix(in srgb, #000 30%, transparent); }
+.chat-select { background: var(--surface-hover); color: var(--fg); border: 1px solid var(--border-strong); border-radius: .5rem; padding: .5rem .65rem; }
+.chat-transcript { overflow: auto; padding: 1.25rem; display: grid; align-content: start; gap: 1rem; }
+.chat-empty-state { align-self: center; justify-self: center; width: min(100%, 40rem); padding: 3rem 1rem; text-align: center; }
+.chat-empty-mark { display: grid; place-items: center; width: 2.6rem; height: 2.6rem; margin: 0 auto 1rem; border: 1px solid var(--border-strong); border-radius: .8rem; color: var(--accent); font-weight: 700; }
+.chat-empty-state h2 { margin: 0; font-size: clamp(1.5rem, 3vw, 2.25rem); letter-spacing: -.04em; }
+.chat-empty-state p { margin: .6rem 0 1.4rem; color: var(--fg-muted); }
+.chat-prompt-grid { display: flex; justify-content: center; flex-wrap: wrap; gap: .5rem; }
+.chat-prompt { padding: .55rem .75rem; border: 1px solid var(--border); border-radius: 999px; background: var(--surface-hover); color: var(--fg-muted); cursor: pointer; }
+.chat-prompt:hover { color: var(--fg); border-color: var(--border-strong); }
+.chat-bubble-row { display: flex; }
+.chat-bubble-row.user { justify-content: flex-end; }
+.chat-bubble { max-width: min(78ch, 86%); padding: .8rem 1rem; border-radius: .85rem; background: var(--surface-hover); line-height: 1.5; }
+.chat-bubble-row.user .chat-bubble { background: color-mix(in srgb, var(--accent) 18%, var(--surface)); }
+.chat-bubble-meta { font-size: .7rem; color: var(--fg-muted); margin-bottom: .3rem; }
+.chat-bubble-text { white-space: pre-wrap; overflow-wrap: anywhere; }
+.chat-bubble-text p { margin: 0 0 .7rem; }
+.chat-bubble-text p:last-child { margin-bottom: 0; }
+.chat-bubble-text h1, .chat-bubble-text h2, .chat-bubble-text h3 { margin: .2rem 0 .6rem; line-height: 1.2; letter-spacing: -.02em; }
+.chat-bubble-text h1 { font-size: 1.25rem; }
+.chat-bubble-text h2 { font-size: 1.1rem; }
+.chat-bubble-text h3 { font-size: 1rem; }
+.chat-bubble-text ul, .chat-bubble-text ol { margin: .25rem 0 .75rem; padding-left: 1.35rem; }
+.chat-bubble-text blockquote { margin: .5rem 0; padding: .35rem .75rem; border-left: 3px solid var(--accent); color: var(--fg-muted); }
+.chat-bubble-text code { padding: .1rem .3rem; border-radius: .3rem; background: color-mix(in srgb, var(--fg) 10%, transparent); font-size: .9em; }
+.chat-bubble-text pre { margin: .6rem 0; padding: .75rem; overflow: auto; border: 1px solid var(--border); border-radius: .5rem; background: color-mix(in srgb, var(--surface) 75%, #000); }
+.chat-bubble-text pre code { padding: 0; background: transparent; }
+.chat-bubble-text a { color: var(--accent); }
+.chat-bubble-text table { width: 100%; margin: .7rem 0; border-collapse: collapse; font-size: .92em; }
+.chat-bubble-text th, .chat-bubble-text td { padding: .45rem .6rem; text-align: left; border: 1px solid var(--border); }
+.chat-bubble-text th { color: var(--fg); background: color-mix(in srgb, var(--surface) 70%, transparent); font-weight: 700; }
+.chat-compose { padding: .85rem 1rem 1rem; border-top: 1px solid var(--border); }
+.chat-composer-shell { position: relative; padding: .7rem .8rem .55rem; background: var(--surface-hover); border: 1px solid var(--border-strong); border-radius: .9rem; }
+.chat-composer { width: 100%; min-height: 3.3rem; resize: vertical; box-sizing: border-box; background: transparent; color: var(--fg); border: 0; padding: .25rem 0; font: inherit; }
+.chat-composer:focus { outline: 0; }
+.chat-command-menu { position: absolute; z-index: 3; right: .8rem; bottom: calc(100% - .25rem); left: .8rem; display: grid; gap: .15rem; max-height: 18rem; overflow: auto; padding: .35rem; background: var(--surface); border: 1px solid var(--border-strong); border-radius: .7rem; box-shadow: 0 .7rem 2rem color-mix(in srgb, #000 30%, transparent); }
+.chat-command-option { display: grid; grid-template-columns: minmax(8rem, 14rem) 1fr; gap: .65rem; align-items: center; padding: .5rem .6rem; text-align: left; color: var(--fg-muted); background: transparent; border: 1px solid transparent; border-radius: .45rem; cursor: pointer; }
+.chat-command-option:hover, .chat-command-option[aria-selected="true"] { color: var(--fg); background: var(--surface-hover); border-color: var(--border); }
+.chat-command-option code { color: var(--fg); }
+.chat-compose-actions { margin-top: .55rem; }
+.chat-hint, .chat-empty { color: var(--fg-muted); font-size: .78rem; }
+.chat-command-help { color: var(--fg-muted); font-size: .78rem; margin-right: auto; }
+.chat-command-help summary { cursor: pointer; }
+.chat-command-list { min-width: min(34rem, 70vw); max-width: 40rem; padding-top: .4rem; line-height: 1.45; }
+.chat-command-item { display: grid; grid-template-columns: minmax(10rem, 16rem) 1fr; gap: .7rem; padding: .3rem 0; }
+.chat-command-item code { color: var(--fg); }
+@media (max-width: 760px) { .chat-topbar, .chat-topbar-actions { align-items: flex-start; flex-direction: column; } .chat-layout { grid-template-columns: 1fr; } .chat-sidebar { max-height: 14rem; overflow: auto; } }
+@media (max-width: 520px) { .chat-update-panel { align-items: flex-start; flex-direction: column; } }
diff --git a/ui/src/chat/chat.js b/ui/src/chat/chat.js
new file mode 100644
index 000000000..ca5e098f2
--- /dev/null
+++ b/ui/src/chat/chat.js
@@ -0,0 +1,609 @@
+import { el, mount } from "../base/dom.js";
+import { api } from "../base/api.js";
+
+import "./chat.css";
+
+const CHANNEL_KEY = "archie.web.chat.channel";
+
+function channelID() {
+ let id = localStorage.getItem(CHANNEL_KEY);
+ if (!id) {
+ id = crypto.randomUUID();
+ localStorage.setItem(CHANNEL_KEY, id);
+ }
+ return id;
+}
+
+function sessionTitle(session) {
+ return session.title || session.branch_name || `Conversation ${session.session_id.slice(0, 8)}`;
+}
+
+function inlineMarkdown(text) {
+ const fragment = document.createDocumentFragment();
+ const pattern = /(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g;
+ let cursor = 0;
+ for (const match of text.matchAll(pattern)) {
+ if (match.index > cursor) fragment.append(document.createTextNode(text.slice(cursor, match.index)));
+ const value = match[0];
+ if (value.startsWith("~~")) fragment.append(el("del", value.slice(2, -2)));
+ else if (value.startsWith("**") || value.startsWith("__")) fragment.append(el("strong", value.slice(2, -2)));
+ else if (value.startsWith("`")) fragment.append(el("code", value.slice(1, -1)));
+ else if (value.startsWith("[")) {
+ const link = value.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);
+ fragment.append(el("a", { href: link[2], target: "_blank", rel: "noreferrer" }, link[1]));
+ } else fragment.append(el("em", value.slice(1, -1)));
+ cursor = match.index + value.length;
+ }
+ if (cursor < text.length) fragment.append(document.createTextNode(text.slice(cursor)));
+ return fragment;
+}
+
+function renderMarkdown(text) {
+ const root = el("div.chat-bubble-text");
+ const lines = String(text || "").split("\n");
+ let paragraph = [];
+ let list = null;
+ let code = null;
+ const flushParagraph = () => {
+ if (paragraph.length) {
+ root.append(el("p", inlineMarkdown(paragraph.join(" "))));
+ paragraph = [];
+ }
+ };
+ const flushList = () => {
+ if (list) root.append(list);
+ list = null;
+ };
+ for (let index = 0; index < lines.length; index++) {
+ const line = lines[index];
+ if (line.startsWith("```")) {
+ flushParagraph();
+ flushList();
+ if (code) {
+ root.append(el("pre", el("code", code.join("\n"))));
+ code = null;
+ } else code = [];
+ continue;
+ }
+ if (code) {
+ code.push(line);
+ continue;
+ }
+ const headerCells = tableCells(line);
+ const separatorCells = index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
+ if (headerCells && separatorCells && isTableSeparator(separatorCells) && headerCells.length === separatorCells.length) {
+ flushParagraph();
+ flushList();
+ const rows = [];
+ for (index += 2; index < lines.length; index++) {
+ const cells = tableCells(lines[index]);
+ if (!cells || cells.length !== headerCells.length) {
+ index--;
+ break;
+ }
+ rows.push(cells);
+ }
+ const body = el("tbody");
+ for (const row of rows) {
+ body.append(el("tr", ...row.map((cell) => el("td", inlineMarkdown(cell)))));
+ }
+ root.append(el(
+ "table",
+ el("thead", el("tr", ...headerCells.map((cell) => el("th", inlineMarkdown(cell))))),
+ body,
+ ));
+ continue;
+ }
+ if (!line.trim()) {
+ flushParagraph();
+ flushList();
+ continue;
+ }
+ const heading = line.match(/^(#{1,3})\s+(.+)$/);
+ if (heading) {
+ flushParagraph();
+ flushList();
+ root.append(el(`h${heading[1].length}`, inlineMarkdown(heading[2])));
+ continue;
+ }
+ const bullet = line.match(/^\s*[-*]\s+(.+)$/);
+ const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
+ if (bullet || ordered) {
+ flushParagraph();
+ const tag = ordered ? "ol" : "ul";
+ if (!list || list.tagName.toLowerCase() !== tag) {
+ flushList();
+ list = el(tag);
+ }
+ list.append(el("li", inlineMarkdown((bullet || ordered)[1])));
+ continue;
+ }
+ if (line.startsWith(">")) {
+ flushParagraph();
+ flushList();
+ root.append(el("blockquote", inlineMarkdown(line.replace(/^>\s?/, ""))));
+ continue;
+ }
+ paragraph.push(line);
+ }
+ flushParagraph();
+ flushList();
+ if (code) root.append(el("pre", el("code", code.join("\n"))));
+ return root;
+}
+
+function tableCells(line) {
+ const value = String(line || "").trim();
+ if (!value.includes("|")) return null;
+ const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
+ const cells = unwrapped.split("|").map((cell) => cell.trim());
+ return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
+}
+
+function isTableSeparator(cells) {
+ return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
+}
+
+function chatBubble(message) {
+ const from = message.from ?? message.From ?? "";
+ const text = message.text ?? message.Text ?? "";
+ const isAssistant = from !== "web";
+ return el(
+ `div.chat-bubble-row.${isAssistant ? "assistant" : "user"}`,
+ el(
+ "div.chat-bubble",
+ el("div.chat-bubble-meta", isAssistant ? "Archie" : "You"),
+ isAssistant ? renderMarkdown(text) : el("div.chat-bubble-text", text),
+ ),
+ );
+}
+
+export function chatPage() {
+ const root = el("div.chat-page");
+ const sessionList = el("div.chat-session-list");
+ const transcript = el("div.chat-transcript");
+ const composer = el("textarea.chat-composer", {
+ rows: 3,
+ placeholder: "Message Archie… (commands like /status and /new work here)",
+ "aria-label": "Message Archie",
+ });
+ const send = el("button.btn.btn-primary", "Send");
+ const stop = el("button.btn", { disabled: true }, "Stop");
+ const status = el("span.chat-status", "Ready");
+ const persona = el("select.chat-select", { "aria-label": "Personality" });
+ const provider = el("select.chat-select", { "aria-label": "Provider", hidden: true });
+ const model = el("select.chat-select", { "aria-label": "Model" });
+ const restart = el("button.btn", { hidden: true, onclick: () => {
+ if (!window.confirm("Reload the Telegram chat adapter?")) return;
+ composer.value = "/restart";
+ sendMessage();
+ } }, "Reload Telegram");
+ let currentSession = "";
+ let sessions = [];
+ let sending = false;
+ let activeController = null;
+ let updateSnapshot = null;
+ let selectorData = {};
+ let commandSpecs = [];
+ let commandMatches = [];
+ let commandSelection = 0;
+
+ const emptyState = el(
+ "div.chat-empty-state",
+ el("span.chat-empty-mark", "A"),
+ el("h2", "What are we working on?"),
+ el("p", "Ask Archie anything, or start with one of these prompts."),
+ el("div.chat-prompt-grid",
+ ...["Summarise active tasks", "Show running agents", "Check system status"].map((prompt) =>
+ el("button.chat-prompt", { onclick: () => { composer.value = prompt; composer.focus(); } }, prompt)),
+ ),
+ );
+
+ function appendMessage(message) {
+ emptyState.remove();
+ transcript.append(chatBubble(message));
+ transcript.scrollTop = transcript.scrollHeight;
+ }
+
+ function renderSessions() {
+ sessionList.replaceChildren();
+ sessionTools.hidden = !currentSession;
+ if (!sessions.length) {
+ sessionList.append(el("div.chat-empty", "Your conversations will appear here."));
+ return;
+ }
+ for (const session of sessions) {
+ const item = el(
+ "button.chat-session",
+ { class: currentSession === session.session_id ? "active" : "", onclick: () => selectSession(session.session_id) },
+ el("strong", sessionTitle(session)),
+ el("span", new Date(session.last_active_at).toLocaleString()),
+ );
+ sessionList.append(item);
+ }
+ }
+
+ function renderSelectors(data) {
+ selectorData = data;
+ persona.replaceChildren(el("option", { value: "" }, "Personality"));
+ for (const name of data.personas || []) persona.append(el("option", { value: name }, name));
+ persona.value = data.active_persona || "";
+ const providers = data.providers || [];
+ provider.hidden = providers.length === 0;
+ provider.replaceChildren(el("option", { value: "" }, "Provider"));
+ for (const name of providers) provider.append(el("option", { value: name }, name));
+ provider.value = data.active_provider || providers[0] || "";
+ renderModelsForProvider(provider.value);
+ restart.hidden = !data.restart_available;
+ dangerousPanel.hidden = !data.dangerous_available;
+ if (data.dangerous_available) refreshDangerous();
+ }
+
+ function renderModelsForProvider(providerName) {
+ const grouped = selectorData.models_by_provider || {};
+ const names = providerName && grouped[providerName] ? grouped[providerName] : selectorData.models || [];
+ model.replaceChildren(el("option", { value: "" }, "Model"));
+ for (const name of names) model.append(el("option", { value: name }, name));
+ model.value = selectorData.active_model || "";
+ }
+
+ function renderCommands(data) {
+ const commands = data.commands || [];
+ commandSpecs = commands.map((item) => typeof item === "string" ? { command: item, usage: item, description: "" } : item);
+ const list = el("div.chat-command-list");
+ if (!commands.length) list.append(el("span", "Send a message to begin."));
+ for (const item of commands) {
+ const spec = typeof item === "string" ? { command: item, usage: item, description: "" } : item;
+ list.append(el("div.chat-command-item", el("code", spec.usage || spec.command), el("span", spec.description || "")));
+ }
+ commandHelp.replaceChildren(el("summary", `Available commands (${commands.length})`), list);
+ }
+
+ const updatePanel = el("div.chat-update-panel");
+ const dangerousPanel = el("div.chat-dangerous-panel", { hidden: true });
+ const commandMenu = el("div.chat-command-menu", { hidden: true, role: "listbox", "aria-label": "Commands" });
+ const sessionTools = el("details.chat-session-tools", { hidden: true });
+
+ function commandQuery() {
+ const before = composer.value.slice(0, composer.selectionStart);
+ const match = before.match(/(?:^|\s)\/([^\s]*)$/);
+ return match ? match[1].toLowerCase() : null;
+ }
+
+ function hideCommandMenu() {
+ commandMenu.hidden = true;
+ commandMatches = [];
+ commandSelection = 0;
+ }
+
+ function renderCommandMenu() {
+ const query = commandQuery();
+ if (query === null) {
+ hideCommandMenu();
+ return;
+ }
+ commandMatches = commandSpecs.filter((spec) => {
+ const haystack = `${spec.command} ${spec.description}`.toLowerCase();
+ return haystack.includes(query);
+ }).slice(0, 8);
+ if (!commandMatches.length) {
+ hideCommandMenu();
+ return;
+ }
+ commandSelection = Math.min(commandSelection, commandMatches.length - 1);
+ commandMenu.replaceChildren(...commandMatches.map((spec, index) => el(
+ "button.chat-command-option",
+ {
+ type: "button",
+ role: "option",
+ "aria-selected": index === commandSelection,
+ onmousedown: (event) => event.preventDefault(),
+ onclick: () => chooseCommand(index),
+ },
+ el("code", spec.command),
+ el("span", spec.description || spec.usage || ""),
+ )));
+ commandMenu.hidden = false;
+ }
+
+ function chooseCommand(index) {
+ const spec = commandMatches[index];
+ if (!spec) return;
+ const before = composer.value.slice(0, composer.selectionStart);
+ const after = composer.value.slice(composer.selectionStart);
+ const start = before.search(/(?:^|\s)\/[^\s]*$/);
+ const tokenStart = start < 0 ? before.length : start + (before[start] === " " ? 1 : 0);
+ composer.value = `${before.slice(0, tokenStart)}${spec.command} ${after}`;
+ const cursor = tokenStart + spec.command.length + 1;
+ composer.setSelectionRange(cursor, cursor);
+ hideCommandMenu();
+ composer.focus();
+ }
+
+ function renderUpdate(data) {
+ updatePanel.replaceChildren();
+ updateSnapshot = data?.snapshot || null;
+ const available = data?.available || [];
+ if (!available.length) {
+ updatePanel.append(el("span", data?.snapshot?.deferred ? "Update deferred." : "Archie is up to date."));
+ return;
+ }
+ updatePanel.append(
+ el("div", el("strong", "Update available"), el("span", available.map((component) => `${component.Label || component.label}: ${component.Available || component.available}`).join(" · "))),
+ el("div.chat-update-actions",
+ el("button.btn", { onclick: async () => { await api.chatUpdateDefer(updateSnapshot); renderUpdate({ snapshot: { deferred: true }, available: [] }); status.textContent = "Update deferred"; } }, "Defer"),
+ data.can_install ? el("button.btn.btn-primary", { onclick: async () => { status.textContent = "Installing…"; await api.chatUpdateInstall(updateSnapshot); status.textContent = "Update started"; refreshUpdate(); } }, "Install update") : null,
+ ),
+ );
+ }
+
+ async function refreshUpdate() {
+ try {
+ renderUpdate(await api.chatUpdate());
+ } catch (err) {
+ updatePanel.replaceChildren(el("span", err.message || "Updates unavailable"));
+ }
+ }
+
+ function dangerousActionButton(id, decision, label) {
+ return el("button.btn", { onclick: async () => {
+ try {
+ await api.chatDangerousDecision(id, decision);
+ status.textContent = decision === "deny" ? "Action denied" : "Action approved";
+ await refreshDangerous();
+ } catch (err) {
+ status.textContent = err.message || "Approval failed";
+ }
+ } }, label);
+ }
+
+ function renderDangerous(data) {
+ dangerousPanel.replaceChildren();
+ const checkpoints = data?.checkpoints || [];
+ const pending = data?.pending || [];
+ const checkpoint = el("select.chat-select", { "aria-label": "Checkpoint" },
+ el("option", { value: "" }, "Select checkpoint"),
+ ...checkpoints.map((item) => el("option", { value: item.Number ?? item.number }, `${item.Number ?? item.number} — ${item.Label ?? item.label ?? "checkpoint"}`)),
+ );
+ const stopSpec = el("input.chat-dangerous-input", { placeholder: "Process name or id", "aria-label": "Process name or id" });
+ const request = (kind, spec) => async () => {
+ if (!String(spec.value || spec).trim()) return;
+ try {
+ await api.chatDangerousRequest(kind, String(spec.value || spec).trim());
+ status.textContent = "Approval requested";
+ await refreshDangerous();
+ } catch (err) {
+ status.textContent = err.message || "Could not request action";
+ }
+ };
+ const pendingRows = pending.length ? pending.map((action) => el("div.chat-dangerous-pending",
+ el("span", action.description),
+ el("div.chat-update-actions", dangerousActionButton(action.id, "approve", "Approve"), dangerousActionButton(action.id, "permanent", "Approve for 24h"), dangerousActionButton(action.id, "deny", "Deny")),
+ )) : [el("span.chat-hint", "No pending dangerous actions.")];
+ dangerousPanel.append(
+ el("div.chat-dangerous-head", el("strong", "Dangerous actions"), el("span.chat-hint", "Every action requires approval.")),
+ el("div.chat-dangerous-controls",
+ el("div", checkpoint, el("button.btn", { onclick: request("rollback", checkpoint) }, "Request rollback")),
+ el("div", stopSpec, el("button.btn", { onclick: request("stop", stopSpec) }, "Request stop")),
+ ),
+ el("div.chat-dangerous-pending-list", ...pendingRows),
+ );
+ }
+
+ async function refreshDangerous() {
+ try {
+ renderDangerous(await api.chatDangerous());
+ } catch (err) {
+ dangerousPanel.replaceChildren(el("span.chat-hint", err.message || "Dangerous actions unavailable"));
+ }
+ }
+
+ async function refreshSessions() {
+ const data = await api.chatSessions();
+ sessions = data.sessions || [];
+ renderSelectors(data);
+ renderCommands(data);
+ renderSessions();
+ if (!currentSession && sessions[0]) await selectSession(sessions[0].session_id);
+ }
+
+ async function runSessionCommand(command) {
+ if (!currentSession) return;
+ try {
+ status.textContent = "Working…";
+ const result = await api.chatMessage(channelID(), command);
+ if (result.session_id) currentSession = result.session_id;
+ status.textContent = result.reply || "Session updated";
+ await refreshSessions();
+ if (currentSession) await selectSession(currentSession);
+ sessionTools.open = false;
+ } catch (err) {
+ status.textContent = err.message || "Session action failed";
+ }
+ }
+
+ function promptSessionCommand(command, message) {
+ const value = window.prompt(message);
+ if (value?.trim()) runSessionCommand(`${command} ${value.trim()}`);
+ }
+
+ async function selectSession(id) {
+ currentSession = id;
+ renderSessions();
+ transcript.replaceChildren();
+ await api.chatMessage(channelID(), `/resume ${id}`);
+ persona.value = selectorData.active_personas?.[id] || selectorData.active_persona || "";
+ const messages = await api.chatMessages(id);
+ for (const message of messages) appendMessage(message);
+ if (!transcript.children.length) transcript.append(emptyState);
+ }
+
+ async function sendMessage() {
+ const text = composer.value.trim();
+ if (!text || sending) return;
+ hideCommandMenu();
+ sending = true;
+ send.disabled = true;
+ stop.disabled = false;
+ composer.disabled = true;
+ status.textContent = "Thinking…";
+ appendMessage({ from: "web", text });
+ composer.value = "";
+ const replyBubble = el("div.chat-bubble-row.assistant", el("div.chat-bubble", el("div.chat-bubble-meta", "Archie"), el("div.chat-bubble-text")));
+ transcript.append(replyBubble);
+ const replyText = replyBubble.querySelector(".chat-bubble-text");
+ let timeout;
+ try {
+ activeController = new AbortController();
+ timeout = setTimeout(() => activeController.abort(), 120000);
+ const response = await fetch("/api/chat/stream", {
+ method: "POST",
+ headers: { "Content-Type": "application/json", Accept: "text/event-stream" },
+ body: JSON.stringify({ channel_id: channelID(), source_id: crypto.randomUUID(), text }),
+ signal: activeController.signal,
+ });
+ if (!response.ok) throw new Error((await response.text()) || `${response.status} ${response.statusText}`);
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ for (;;) {
+ const { value, done } = await reader.read();
+ buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
+ const frames = buffer.split("\n\n");
+ buffer = frames.pop() || "";
+ for (const frame of frames) {
+ const line = frame.split("\n").find((part) => part.startsWith("data: "));
+ if (!line) continue;
+ const event = JSON.parse(line.slice(6));
+ if (event.session_id) currentSession = event.session_id;
+ if (event.type === "delta") replyText.textContent += event.text;
+ if (event.type === "done" && !replyText.textContent) replyText.textContent = event.text;
+ if (event.type === "error") throw new Error(event.text);
+ }
+ if (done) break;
+ }
+ if (replyText.isConnected) replyText.replaceWith(renderMarkdown(replyText.textContent));
+ status.textContent = "Ready";
+ await refreshSessions();
+ if (currentSession) await selectSession(currentSession);
+ } catch (err) {
+ if (err.name === "AbortError") {
+ replyText.textContent = "Turn stopped.";
+ status.textContent = "Stopped";
+ } else {
+ replyText.textContent = `Unable to complete that turn: ${err.message || err}`;
+ status.textContent = "Error";
+ }
+ } finally {
+ clearTimeout(timeout);
+ activeController = null;
+ sending = false;
+ send.disabled = false;
+ stop.disabled = true;
+ composer.disabled = false;
+ composer.focus();
+ }
+ }
+
+ send.onclick = sendMessage;
+ stop.onclick = () => {
+ const sessionID = currentSession;
+ status.textContent = "Stopping…";
+ if (sessionID) void api.chatCancel(sessionID).catch(() => {});
+ activeController?.abort();
+ };
+ composer.oninput = renderCommandMenu;
+ composer.onkeydown = (event) => {
+ if (!commandMenu.hidden && commandMatches.length) {
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ commandSelection = (commandSelection + 1) % commandMatches.length;
+ renderCommandMenu();
+ return;
+ }
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ commandSelection = (commandSelection + commandMatches.length - 1) % commandMatches.length;
+ renderCommandMenu();
+ return;
+ }
+ if (event.key === "Enter" && !event.ctrlKey && !event.metaKey) {
+ event.preventDefault();
+ chooseCommand(commandSelection);
+ return;
+ }
+ if (event.key === "Escape") {
+ event.preventDefault();
+ hideCommandMenu();
+ return;
+ }
+ }
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ sendMessage();
+ }
+ };
+ persona.onchange = async () => {
+ if (!currentSession || !persona.value) return;
+ await api.chatPersona(currentSession, persona.value);
+ selectorData.active_personas = { ...(selectorData.active_personas || {}), [currentSession]: persona.value };
+ status.textContent = `Personality: ${persona.value}`;
+ };
+ provider.onchange = async () => {
+ renderModelsForProvider(provider.value);
+ if (!provider.value) return;
+ await applyModelCommand(`/model --provider ${provider.value}`);
+ };
+ model.onchange = async () => {
+ if (model.value) await applyModelCommand(`/model ${model.value}`);
+ };
+ async function applyModelCommand(command) {
+ try {
+ const result = await api.chatMessage(channelID(), command);
+ status.textContent = result.reply || "Model updated";
+ await refreshSessions();
+ } catch (err) {
+ status.textContent = `Model update failed: ${err.message || err}`;
+ }
+ };
+
+ const commandHelp = el("details.chat-command-help");
+ const checkUpdates = el("button.btn", { onclick: refreshUpdate }, "Check updates");
+ const sessionActions = el(
+ "div.chat-session-tool-list",
+ el("button.btn", { type: "button", onclick: () => runSessionCommand("/retry") }, "Retry"),
+ el("button.btn", { type: "button", onclick: () => runSessionCommand("/undo") }, "Undo"),
+ el("button.btn", { type: "button", onclick: () => promptSessionCommand("/title", "Session title") }, "Rename"),
+ el("button.btn", { type: "button", onclick: () => promptSessionCommand("/branch", "Branch name (optional)") }, "Branch"),
+ el("button.btn", { type: "button", onclick: () => runSessionCommand("/compress --preview") }, "Preview compression"),
+ );
+ sessionTools.append(el("summary", "Session actions"), sessionActions);
+ const chatTopbar = el(
+ "div.chat-topbar",
+ el("div", el("span.chat-kicker", "ARCHIE WORKSPACE"), el("h1.page-title", "Chat")),
+ el("div.chat-topbar-actions", el("span.chat-status", status), restart, checkUpdates, persona, provider, model),
+ );
+ const chatLayout = el(
+ "div.chat-layout",
+ el("aside.chat-sidebar", el("div.chat-sidebar-head", el("strong", "Conversations"), el("button.btn.btn-primary", { onclick: () => { composer.value = "/new"; sendMessage(); } }, "+ New chat")), sessionList),
+ el(
+ "section.chat-workspace",
+ el("div.chat-workspace-head", el("span.chat-workspace-label", "PERSONAL ASSISTANT"), commandHelp, sessionTools),
+ transcript,
+ el("div.chat-compose", el("div.chat-composer-shell", composer, commandMenu, el("div.chat-compose-actions", el("span.chat-hint", "⌘/Ctrl + Enter to send"), stop, send))),
+ ),
+ );
+ mount(root, el(
+ "div.chat-page-content",
+ chatTopbar,
+ updatePanel,
+ dangerousPanel,
+ chatLayout,
+ ));
+
+ transcript.append(emptyState);
+
+ refreshSessions().catch((err) => { status.textContent = err.message || "Chat unavailable"; });
+ refreshUpdate();
+ return root;
+}
diff --git a/ui/src/main.js b/ui/src/main.js
index 8490107e6..3b8259ddb 100644
--- a/ui/src/main.js
+++ b/ui/src/main.js
@@ -9,6 +9,7 @@ import { channelsPage } from "./channels/channels.js";
import { settingsPage } from "./settings/settings.js";
import { logsPage } from "./logs/logs.js";
import { memoryPage } from "./memory/memory.js";
+import { chatPage } from "./chat/chat.js";
/**
* Routes are declared once here. Adding a section means adding a feature
@@ -20,6 +21,7 @@ import { memoryPage } from "./memory/memory.js";
*/
const routes = [
{ path: "/", label: "Dashboard", icon: "dashboard", view: dashboardPage },
+ { path: "/chat", label: "Chat", icon: "chat", view: chatPage },
{ path: "/tasks", label: "Tasks", icon: "tasks", view: tasksPage },
{ path: "/logs", label: "Logs", icon: "logs", view: logsPage },
{ path: "/skills", label: "Skills", icon: "skills", view: skillsPage },