ScuttleBot

feat: LLM gateway, admin auth, sentinel/steward/snitch bots, channel delete, scuttlectl improvements - LLM gateway: multi-backend routing (Anthropic, OpenAI, Gemini, Ollama, Bedrock) with policy store, model discovery, and /v1/llm/* endpoints - Admin auth: bcrypt account store, login endpoint, rate-limited session tokens - Bot manager: policy-driven lifecycle for system bots (start/stop on config change) - Sentinel + Steward: LLM-powered moderation — sentinel observes/reports, steward acts on policy violations - Snitch: nick-window tracking for agent activity correlation - Agent delete: DELETE /v1/agents/{nick} + scuttlectl agent delete - Channel delete: bridge LeaveChannel, DELETE /v1/channels/{channel}, scuttlectl channels delete - scuttlectl: channels list/users/delete, backend rename, agent delete - run.sh: agent sync on restart, _run_agent for fleet-style claude sessions - claude-relay.sh: starts IRC agent under same session nick as hooks - scuttlectl binary: compiled and tracked

lmata 2026-04-01 13:27 UTC trunk
Commit 5ac549cc530d57e4c9889bf60d33ef18e32e042188b5d107791eb6ee0373dafa
56 files changed +37 -9 +128 -41 +217 -25 +217 +95 +190 -6 +9 -1 +16 +45 +1 -1 +7 +1 +331 +185 +203 +69 +36 +1 +25 +2413 -482 +67 +141 +12 +377 +204 +1 -88 +8 -3 +118 +304 +59 +189 +88 +39 +2 +86 +100 +77 +349 +87 +44 +39 +70 +68 +84 +34 +94 +81 +139 +67 +35 +13 +122 -10 +190 +228
~ CLAUDE.md ~ bootstrap.md ~ cmd/scuttlebot/main.go + cmd/scuttlectl/cmd_setup.go ~ cmd/scuttlectl/internal/apiclient/apiclient.go ~ cmd/scuttlectl/main.go ~ go.mod ~ go.sum ~ internal/api/agents.go ~ internal/api/api_test.go ~ internal/api/chat.go ~ internal/api/chat_test.go + internal/api/llm_handlers.go + internal/api/login.go + internal/api/login_test.go + internal/api/metrics.go + internal/api/policies.go + internal/api/policies_test.go ~ internal/api/server.go + internal/api/settings.go ~ internal/api/ui/index.html + internal/auth/admin.go + internal/auth/admin_test.go ~ internal/bots/bridge/bridge.go + internal/bots/manager/manager.go + internal/bots/manager/manager_test.go ~ internal/bots/oracle/providers.go ~ internal/bots/scribe/scribe.go ~ internal/bots/scribe/scribe_test.go ~ internal/bots/scribe/store.go + internal/bots/sentinel/sentinel.go + internal/bots/snitch/nickwindow_test.go + internal/bots/snitch/snitch.go + internal/bots/snitch/snitch_test.go + internal/bots/steward/steward.go ~ internal/config/config.go + internal/llm/anthropic.go + internal/llm/anthropic_test.go + internal/llm/bedrock.go + internal/llm/bedrock_test.go + internal/llm/config.go + internal/llm/factory.go + internal/llm/factory_test.go + internal/llm/filter.go + internal/llm/gemini.go + internal/llm/gemini_test.go + internal/llm/ollama.go + internal/llm/ollama_test.go + internal/llm/openai.go + internal/llm/openai_test.go + internal/llm/provider.go + internal/llm/stub.go ~ internal/registry/registry.go + pkg/agentrelay/relay.go + run.sh + scuttlectl
+37 -9
--- CLAUDE.md
+++ CLAUDE.md
@@ -1,19 +1,47 @@
11
# Claude — scuttlebot
22
33
Primary conventions doc: [`bootstrap.md`](bootstrap.md)
4
-Context seed: [`memory.md`](memory.md)
54
6
-Read both before writing any code.
5
+Read it before writing any code.
76
87
---
98
109
## Project-specific notes
1110
12
-- Language: Python 3.12+
13
-- Transport: IRC — all agent coordination flows through IRC channels and messages
14
-- Async runtime: asyncio throughout; IRC library TBD (irc3 or similar)
15
-- No web layer, no database — pure message-passing over IRC
11
+- Language: Go 1.22+
12
+- Transport: IRC — all agent coordination flows through Ergo IRC channels and messages
13
+- HTTP API: `internal/api/` — Bearer token auth, JSON, serves the web UI at `/ui/`
14
+- Admin auth: `internal/auth/` — bcrypt-hashed accounts, login at `POST /login`
15
+- Bot manager: `internal/bots/manager/` — starts/stops system bots based on policy changes
1616
- Human observable by design: everything an agent does is visible in IRC
17
-- Test runner: pytest + pytest-asyncio
18
-- Formatter/linter: Ruff (replaces black, flake8, isort)
19
-- Package manager: uv (`uv sync`, `uv run pytest`)
17
+- Test runner: `go test ./...`
18
+- Formatter: `gofmt` (enforced — run before committing)
19
+- Linter: `golangci-lint run`
20
+- Dev helper: `./run.sh` (start / stop / restart / token / log / test / e2e / clean)
21
+- No ORM, no database — state persisted as JSON files in `data/`
22
+
23
+## Key entry points
24
+
25
+| Path | Purpose |
26
+|------|---------|
27
+| `cmd/scuttlebot/` | daemon binary |
28
+| `cmd/scuttlectl/` | admin CLI |
29
+| `internal/api/` | HTTP API server + web UI |
30
+| `internal/auth/` | admin account store (bcrypt) |
31
+| `internal/registry/` | agent registration + credential issuance |
32
+| `internal/bots/manager/` | bot lifecycle (start/stop on policy change) |
33
+| `internal/ergo/` | Ergo IRC server lifecycle + config generation |
34
+| `internal/config/` | YAML config loading |
35
+| `pkg/client/` | Go agent SDK |
36
+| `pkg/protocol/` | JSON envelope wire format |
37
+
38
+## Conventions
39
+
40
+- Errors returned, not panicked. Wrap: `fmt.Errorf("pkg: operation: %w", err)`
41
+- Interfaces defined at point of use, not in the implementing package
42
+- No global state. Dependencies injected via constructor args or struct fields.
43
+- Env vars for secrets only (e.g. `ORACLE_OPENAI_API_KEY`); everything else in `scuttlebot.yaml`
44
+
45
+## Memory
46
+
47
+See `~/.claude/projects/<sanitized-cwd>/memory/MEMORY.md`
2048
--- CLAUDE.md
+++ CLAUDE.md
@@ -1,19 +1,47 @@
1 # Claude — scuttlebot
2
3 Primary conventions doc: [`bootstrap.md`](bootstrap.md)
4 Context seed: [`memory.md`](memory.md)
5
6 Read both before writing any code.
7
8 ---
9
10 ## Project-specific notes
11
12 - Language: Python 3.12+
13 - Transport: IRC — all agent coordination flows through IRC channels and messages
14 - Async runtime: asyncio throughout; IRC library TBD (irc3 or similar)
15 - No web layer, no database — pure message-passing over IRC
 
16 - Human observable by design: everything an agent does is visible in IRC
17 - Test runner: pytest + pytest-asyncio
18 - Formatter/linter: Ruff (replaces black, flake8, isort)
19 - Package manager: uv (`uv sync`, `uv run pytest`)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
--- CLAUDE.md
+++ CLAUDE.md
@@ -1,19 +1,47 @@
1 # Claude — scuttlebot
2
3 Primary conventions doc: [`bootstrap.md`](bootstrap.md)
 
4
5 Read it before writing any code.
6
7 ---
8
9 ## Project-specific notes
10
11 - Language: Go 1.22+
12 - Transport: IRC — all agent coordination flows through Ergo IRC channels and messages
13 - HTTP API: `internal/api/` — Bearer token auth, JSON, serves the web UI at `/ui/`
14 - Admin auth: `internal/auth/` — bcrypt-hashed accounts, login at `POST /login`
15 - Bot manager: `internal/bots/manager/` — starts/stops system bots based on policy changes
16 - Human observable by design: everything an agent does is visible in IRC
17 - Test runner: `go test ./...`
18 - Formatter: `gofmt` (enforced — run before committing)
19 - Linter: `golangci-lint run`
20 - Dev helper: `./run.sh` (start / stop / restart / token / log / test / e2e / clean)
21 - No ORM, no database — state persisted as JSON files in `data/`
22
23 ## Key entry points
24
25 | Path | Purpose |
26 |------|---------|
27 | `cmd/scuttlebot/` | daemon binary |
28 | `cmd/scuttlectl/` | admin CLI |
29 | `internal/api/` | HTTP API server + web UI |
30 | `internal/auth/` | admin account store (bcrypt) |
31 | `internal/registry/` | agent registration + credential issuance |
32 | `internal/bots/manager/` | bot lifecycle (start/stop on policy change) |
33 | `internal/ergo/` | Ergo IRC server lifecycle + config generation |
34 | `internal/config/` | YAML config loading |
35 | `pkg/client/` | Go agent SDK |
36 | `pkg/protocol/` | JSON envelope wire format |
37
38 ## Conventions
39
40 - Errors returned, not panicked. Wrap: `fmt.Errorf("pkg: operation: %w", err)`
41 - Interfaces defined at point of use, not in the implementing package
42 - No global state. Dependencies injected via constructor args or struct fields.
43 - Env vars for secrets only (e.g. `ORACLE_OPENAI_API_KEY`); everything else in `scuttlebot.yaml`
44
45 ## Memory
46
47 See `~/.claude/projects/<sanitized-cwd>/memory/MEMORY.md`
48
+128 -41
--- bootstrap.md
+++ bootstrap.md
@@ -55,35 +55,49 @@
5555
5656
## Monorepo Layout
5757
5858
```
5959
cmd/
60
- scuttlebot/ # daemon binary
61
- scuttlectl/ # CLI/REPL binary
60
+ scuttlebot/ # daemon binary
61
+ scuttlectl/ # admin CLI
62
+ internal/apiclient/ # typed API client used by scuttlectl
6263
internal/
63
- ergo/ # ergo lifecycle + config generation
64
- registry/ # agent registration + credential issuance
65
- topology/ # channel provisioning + mode/topic management
66
- bots/ # built-in bots (scribe, scroll, herald, oracle, warden)
67
- mcp/ # MCP server for AI agent connectivity
68
-internal/config/ # config loading + validation
64
+ api/ # HTTP API server (Bearer auth) + embedded web UI at /ui/
65
+ ui/index.html # single-file operator web UI
66
+ auth/ # admin account store — bcrypt hashed, persisted to JSON
67
+ bots/
68
+ manager/ # bot lifecycle — starts/stops bots on policy change
69
+ auditbot/ # immutable append-only audit trail
70
+ herald/ # external event → channel routing (webhooks)
71
+ oracle/ # on-demand channel summarization via LLM (PM only)
72
+ scribe/ # structured logging to rotating files
73
+ scroll/ # history replay to PM on request
74
+ snitch/ # flood + join/part cycling detection → operator alerts
75
+ systembot/ # IRC system events (joins, parts, modes, kicks)
76
+ warden/ # channel moderation — warn → mute → kick
77
+ config/ # YAML config loading + validation
78
+ ergo/ # Ergo IRC server lifecycle + config generation
79
+ mcp/ # MCP server for AI agent connectivity
80
+ registry/ # agent registration + SASL credential issuance
81
+ topology/ # channel provisioning + mode/topic management
6982
pkg/
70
- client/ # Go SDK (public)
71
- protocol/ # wire format (message envelope)
72
-apps/
73
- web/ # operator UI — separate app, own stack
74
-sdk/ # future: python, ruby, rust client SDKs
83
+ client/ # Go agent SDK (public)
84
+ protocol/ # JSON envelope wire format
7585
deploy/
76
- docker/ # Dockerfile(s)
77
- compose/ # docker compose (local dev + single-host)
78
- k8s/ # Kubernetes manifests
79
- standalone/ # single binary, no container required
86
+ docker/ # Dockerfile(s)
87
+ compose/ # Docker Compose (local dev + single-host)
88
+ k8s/ # Kubernetes manifests
89
+ standalone/ # single binary, no container required
90
+tests/
91
+ e2e/ # Playwright end-to-end tests (require scuttlebot running)
8092
go.mod
8193
go.sum
94
+bootstrap.md
95
+CLAUDE.md # Claude Code shim — points here
8296
```
8397
84
-Single Go module for everything under `cmd/`, `internal/`, `pkg/`. `apps/web/` and `sdk/*` are their own modules.
98
+Single Go module. All state persisted as JSON files under `data/` (no database required).
8599
86100
---
87101
88102
## Architecture
89103
@@ -143,34 +157,44 @@
143157
- `+v` (voice) — trusted worker agents
144158
- no mode — standard agents
145159
146160
### Built-in bots
147161
148
-| Bot | Role |
149
-|-----|------|
150
-| `scribe` | Structured logging to persistent store |
151
-| `scroll` | History replay to PM on request (never floods channels) |
152
-| `herald` | Alerts + notifications |
153
-| `oracle` | Summarization — packages context as TOON for agent consumption |
154
-| `warden` | Moderation + rate limiting |
155
-
156
-v0 ships `scribe` only. Pattern proven, others follow.
162
+All 8 bots are implemented. Enabled/configured via the web UI or `scuttlectl`. The manager (`internal/bots/manager/`) starts/stops them dynamically when policies change.
163
+
164
+| Bot | Nick | Role |
165
+|-----|------|------|
166
+| `auditbot` | auditbot | Immutable append-only audit trail of agent actions and credential events |
167
+| `herald` | herald | Routes inbound webhook events to IRC channels |
168
+| `oracle` | oracle | On-demand channel summarization via DM — calls any OpenAI-compatible LLM |
169
+| `scribe` | scribe | Structured message logging to rotating files (jsonl/csv/text) |
170
+| `scroll` | scroll | History replay to PM on request |
171
+| `snitch` | snitch | Flood and join/part cycling detection — alerts operators via DM or channel |
172
+| `systembot` | systembot | Logs IRC system events (joins, parts, quits, mode changes) |
173
+| `warden` | warden | Channel moderation — warn → mute → kick on flood |
174
+
175
+Oracle reads history from scribe's log files (pointed at the same dir). Configure `api_key_env` to the name of the env var holding the API key (e.g. `ORACLE_OPENAI_API_KEY`), and `base_url` for non-OpenAI providers.
157176
158177
### Scale
159178
160179
Target: 100s to low 1000s of agents on a private network. Single Ergo instance handles this comfortably (documented up to 10k clients, 2k per channel). Ergo scales up (multi-core), not out — no horizontal clustering today. Federation is planned upstream but has no timeline; not a scuttlebot concern for now.
161180
162181
### Persistence
163182
164
-| What | Standalone | Docker Compose / K8s |
165
-|------|-----------|----------------------|
166
-| Ergo state (accounts, channels, topics) | `ircd.db` local file | PersistentVolume (K8s) or named volume (Compose) |
167
-| Ergo message history | in-memory buffer | MySQL (Ergo-native, unlimited history) |
168
-| scuttlebot state (agent registry, config) | SQLite | Postgres |
169
-| scribe bot (chat/event logs) | SQLite | Postgres or S3 |
170
-
171
-K8s HA: single Ergo pod with PVC for `ircd.db`. Not multi-replica — Ergo is single-instance. HA = fast pod restart with durable storage.
183
+No database required. All state is persisted as JSON files under `data/` by default.
184
+
185
+| What | File | Notes |
186
+|------|------|-------|
187
+| Agent registry | `data/ergo/registry.json` | Agent records + SASL credentials |
188
+| Admin accounts | `data/ergo/admins.json` | bcrypt-hashed; created by `scuttlectl admin add` |
189
+| Policies | `data/ergo/policies.json` | Bot config, agent policy, logging settings |
190
+| Bot passwords | `data/ergo/bot_passwords.json` | Auto-generated SASL passwords for system bots |
191
+| API token | `data/ergo/api_token` | Bearer token for API auth; stable across restarts |
192
+| Ergo state | `data/ergo/ircd.db` | Ergo-native: accounts, channels, topics, history |
193
+| scribe logs | `data/logs/scribe/` | Rotating log files (jsonl/csv/text); configurable |
194
+
195
+K8s / Docker: mount a PersistentVolume at `data/`. Ergo is single-instance — HA = fast pod restart with durable storage, not horizontal scaling.
172196
173197
---
174198
175199
## Conventions
176200
@@ -196,19 +220,64 @@
196220
- Branch: `feature/{issue}-short-description` or `fix/{issue}-short-description`
197221
- No rebases. New commits only.
198222
- No AI attribution in commits.
199223
200224
---
225
+
226
+## HTTP API
227
+
228
+`internal/api/` — two-mux pattern:
229
+
230
+- **Outer mux** (unauthenticated): `POST /login`, `GET /` (redirect), `GET /ui/` (web UI)
231
+- **Inner mux** (`/v1/` routes): require `Authorization: Bearer <token>` header
232
+
233
+The API token is a random hex string generated once at startup, persisted to `data/ergo/api_token`.
234
+
235
+### Auth
236
+
237
+`POST /login` accepts `{username, password}` and returns `{token, username}`. The token is the shared server API token. Rate limited to 10 attempts per minute per IP.
238
+
239
+Admin accounts are managed via `scuttlectl admin` or the web UI settings → admin accounts card. First run auto-creates an `admin` account with a random password printed to the log.
240
+
241
+### Key endpoints
242
+
243
+| Method | Path | Description |
244
+|--------|------|-------------|
245
+| `POST` | `/login` | Username/password login (unauthenticated) |
246
+| `GET` | `/v1/status` | Server status |
247
+| `GET` | `/v1/metrics` | Runtime metrics + bridge stats |
248
+| `GET/PUT` | `/v1/settings/policies` | Bot config, agent policy, logging |
249
+| `GET` | `/v1/agents` | List all registered agents |
250
+| `POST` | `/v1/agents/register` | Register an agent |
251
+| `POST` | `/v1/agents/{nick}/rotate` | Rotate credentials |
252
+| `POST` | `/v1/agents/{nick}/revoke` | Revoke agent |
253
+| `GET` | `/v1/channels` | List joined channels |
254
+| `GET` | `/v1/channels/{ch}/stream` | SSE stream of channel messages |
255
+| `GET/POST` | `/v1/admins` | List / add admin accounts |
256
+| `DELETE` | `/v1/admins/{username}` | Remove admin |
257
+| `PUT` | `/v1/admins/{username}/password` | Change password |
258
+
259
+---
201260
202261
## Adding a New Bot
203262
204
-1. Create `internal/bots/{name}/` package
205
-2. Implement the `Bot` interface (defined in `internal/bots/bot.go`)
206
-3. Register in `internal/bots/registry.go`
207
-4. Add config struct to `internal/config/`
208
-5. Write tests: bot handles valid message, ignores malformed message, handles disconnect/reconnect
263
+1. Create `internal/bots/{name}/` package with a `Bot` struct and `Start(ctx context.Context) error` method
264
+2. Add a `BotSpec` config struct if the bot needs user-configurable settings
265
+3. Register in `internal/bots/manager/manager.go`:
266
+ - Add a case to `buildBot()` that constructs your bot from the spec config
267
+ - Add a `BehaviorConfig` entry to `defaultBehaviors` in `internal/api/policies.go`
268
+4. Add the UI config schema to `BEHAVIOR_SCHEMAS` in `internal/api/ui/index.html`
269
+5. Write tests: bot logic, config parsing, edge cases. IRC connection can be skipped in unit tests.
209270
6. Update this bootstrap
271
+
272
+No separate registration file or global registry. The manager builds bots by ID from the `BotSpec`. Bots satisfy the `bot` interface (unexported in manager package):
273
+
274
+```go
275
+type bot interface {
276
+ Start(ctx context.Context) error
277
+}
278
+```
210279
211280
---
212281
213282
## Adding a New SDK
214283
@@ -230,11 +299,29 @@
230299
---
231300
232301
## Common Commands
233302
234303
```bash
304
+# Dev helper (recommended)
305
+./run.sh # build + start
306
+./run.sh restart # rebuild + restart
307
+./run.sh stop # stop
308
+./run.sh token # print current API token
309
+./run.sh log # tail the log
310
+./run.sh test # go test ./...
311
+./run.sh e2e # Playwright e2e (requires scuttlebot running)
312
+
313
+# Direct Go commands
235314
go build ./cmd/scuttlebot # build daemon
236315
go build ./cmd/scuttlectl # build CLI
237316
go test ./... # run all tests
238317
golangci-lint run # lint
239
-docker compose up # boot ergo + scuttlebot locally
318
+
319
+# Admin CLI
320
+scuttlectl admin list # list admin accounts
321
+scuttlectl admin add alice # add admin (prompts for password)
322
+scuttlectl admin passwd alice # change password
323
+scuttlectl admin remove alice # remove admin
324
+
325
+# Docker
326
+docker compose -f deploy/compose/docker-compose.yml up
240327
```
241328
--- bootstrap.md
+++ bootstrap.md
@@ -55,35 +55,49 @@
55
56 ## Monorepo Layout
57
58 ```
59 cmd/
60 scuttlebot/ # daemon binary
61 scuttlectl/ # CLI/REPL binary
 
62 internal/
63 ergo/ # ergo lifecycle + config generation
64 registry/ # agent registration + credential issuance
65 topology/ # channel provisioning + mode/topic management
66 bots/ # built-in bots (scribe, scroll, herald, oracle, warden)
67 mcp/ # MCP server for AI agent connectivity
68 internal/config/ # config loading + validation
 
 
 
 
 
 
 
 
 
 
 
 
69 pkg/
70 client/ # Go SDK (public)
71 protocol/ # wire format (message envelope)
72 apps/
73 web/ # operator UI — separate app, own stack
74 sdk/ # future: python, ruby, rust client SDKs
75 deploy/
76 docker/ # Dockerfile(s)
77 compose/ # docker compose (local dev + single-host)
78 k8s/ # Kubernetes manifests
79 standalone/ # single binary, no container required
 
 
80 go.mod
81 go.sum
 
 
82 ```
83
84 Single Go module for everything under `cmd/`, `internal/`, `pkg/`. `apps/web/` and `sdk/*` are their own modules.
85
86 ---
87
88 ## Architecture
89
@@ -143,34 +157,44 @@
143 - `+v` (voice) — trusted worker agents
144 - no mode — standard agents
145
146 ### Built-in bots
147
148 | Bot | Role |
149 |-----|------|
150 | `scribe` | Structured logging to persistent store |
151 | `scroll` | History replay to PM on request (never floods channels) |
152 | `herald` | Alerts + notifications |
153 | `oracle` | Summarization — packages context as TOON for agent consumption |
154 | `warden` | Moderation + rate limiting |
155
156 v0 ships `scribe` only. Pattern proven, others follow.
 
 
 
 
 
157
158 ### Scale
159
160 Target: 100s to low 1000s of agents on a private network. Single Ergo instance handles this comfortably (documented up to 10k clients, 2k per channel). Ergo scales up (multi-core), not out — no horizontal clustering today. Federation is planned upstream but has no timeline; not a scuttlebot concern for now.
161
162 ### Persistence
163
164 | What | Standalone | Docker Compose / K8s |
165 |------|-----------|----------------------|
166 | Ergo state (accounts, channels, topics) | `ircd.db` local file | PersistentVolume (K8s) or named volume (Compose) |
167 | Ergo message history | in-memory buffer | MySQL (Ergo-native, unlimited history) |
168 | scuttlebot state (agent registry, config) | SQLite | Postgres |
169 | scribe bot (chat/event logs) | SQLite | Postgres or S3 |
170
171 K8s HA: single Ergo pod with PVC for `ircd.db`. Not multi-replica — Ergo is single-instance. HA = fast pod restart with durable storage.
 
 
 
 
 
172
173 ---
174
175 ## Conventions
176
@@ -196,19 +220,64 @@
196 - Branch: `feature/{issue}-short-description` or `fix/{issue}-short-description`
197 - No rebases. New commits only.
198 - No AI attribution in commits.
199
200 ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
202 ## Adding a New Bot
203
204 1. Create `internal/bots/{name}/` package
205 2. Implement the `Bot` interface (defined in `internal/bots/bot.go`)
206 3. Register in `internal/bots/registry.go`
207 4. Add config struct to `internal/config/`
208 5. Write tests: bot handles valid message, ignores malformed message, handles disconnect/reconnect
 
 
209 6. Update this bootstrap
 
 
 
 
 
 
 
 
210
211 ---
212
213 ## Adding a New SDK
214
@@ -230,11 +299,29 @@
230 ---
231
232 ## Common Commands
233
234 ```bash
 
 
 
 
 
 
 
 
 
 
235 go build ./cmd/scuttlebot # build daemon
236 go build ./cmd/scuttlectl # build CLI
237 go test ./... # run all tests
238 golangci-lint run # lint
239 docker compose up # boot ergo + scuttlebot locally
 
 
 
 
 
 
 
 
240 ```
241
--- bootstrap.md
+++ bootstrap.md
@@ -55,35 +55,49 @@
55
56 ## Monorepo Layout
57
58 ```
59 cmd/
60 scuttlebot/ # daemon binary
61 scuttlectl/ # admin CLI
62 internal/apiclient/ # typed API client used by scuttlectl
63 internal/
64 api/ # HTTP API server (Bearer auth) + embedded web UI at /ui/
65 ui/index.html # single-file operator web UI
66 auth/ # admin account store — bcrypt hashed, persisted to JSON
67 bots/
68 manager/ # bot lifecycle — starts/stops bots on policy change
69 auditbot/ # immutable append-only audit trail
70 herald/ # external event → channel routing (webhooks)
71 oracle/ # on-demand channel summarization via LLM (PM only)
72 scribe/ # structured logging to rotating files
73 scroll/ # history replay to PM on request
74 snitch/ # flood + join/part cycling detection → operator alerts
75 systembot/ # IRC system events (joins, parts, modes, kicks)
76 warden/ # channel moderation — warn → mute → kick
77 config/ # YAML config loading + validation
78 ergo/ # Ergo IRC server lifecycle + config generation
79 mcp/ # MCP server for AI agent connectivity
80 registry/ # agent registration + SASL credential issuance
81 topology/ # channel provisioning + mode/topic management
82 pkg/
83 client/ # Go agent SDK (public)
84 protocol/ # JSON envelope wire format
 
 
 
85 deploy/
86 docker/ # Dockerfile(s)
87 compose/ # Docker Compose (local dev + single-host)
88 k8s/ # Kubernetes manifests
89 standalone/ # single binary, no container required
90 tests/
91 e2e/ # Playwright end-to-end tests (require scuttlebot running)
92 go.mod
93 go.sum
94 bootstrap.md
95 CLAUDE.md # Claude Code shim — points here
96 ```
97
98 Single Go module. All state persisted as JSON files under `data/` (no database required).
99
100 ---
101
102 ## Architecture
103
@@ -143,34 +157,44 @@
157 - `+v` (voice) — trusted worker agents
158 - no mode — standard agents
159
160 ### Built-in bots
161
162 All 8 bots are implemented. Enabled/configured via the web UI or `scuttlectl`. The manager (`internal/bots/manager/`) starts/stops them dynamically when policies change.
163
164 | Bot | Nick | Role |
165 |-----|------|------|
166 | `auditbot` | auditbot | Immutable append-only audit trail of agent actions and credential events |
167 | `herald` | herald | Routes inbound webhook events to IRC channels |
168 | `oracle` | oracle | On-demand channel summarization via DM — calls any OpenAI-compatible LLM |
169 | `scribe` | scribe | Structured message logging to rotating files (jsonl/csv/text) |
170 | `scroll` | scroll | History replay to PM on request |
171 | `snitch` | snitch | Flood and join/part cycling detection — alerts operators via DM or channel |
172 | `systembot` | systembot | Logs IRC system events (joins, parts, quits, mode changes) |
173 | `warden` | warden | Channel moderation — warn → mute → kick on flood |
174
175 Oracle reads history from scribe's log files (pointed at the same dir). Configure `api_key_env` to the name of the env var holding the API key (e.g. `ORACLE_OPENAI_API_KEY`), and `base_url` for non-OpenAI providers.
176
177 ### Scale
178
179 Target: 100s to low 1000s of agents on a private network. Single Ergo instance handles this comfortably (documented up to 10k clients, 2k per channel). Ergo scales up (multi-core), not out — no horizontal clustering today. Federation is planned upstream but has no timeline; not a scuttlebot concern for now.
180
181 ### Persistence
182
183 No database required. All state is persisted as JSON files under `data/` by default.
184
185 | What | File | Notes |
186 |------|------|-------|
187 | Agent registry | `data/ergo/registry.json` | Agent records + SASL credentials |
188 | Admin accounts | `data/ergo/admins.json` | bcrypt-hashed; created by `scuttlectl admin add` |
189 | Policies | `data/ergo/policies.json` | Bot config, agent policy, logging settings |
190 | Bot passwords | `data/ergo/bot_passwords.json` | Auto-generated SASL passwords for system bots |
191 | API token | `data/ergo/api_token` | Bearer token for API auth; stable across restarts |
192 | Ergo state | `data/ergo/ircd.db` | Ergo-native: accounts, channels, topics, history |
193 | scribe logs | `data/logs/scribe/` | Rotating log files (jsonl/csv/text); configurable |
194
195 K8s / Docker: mount a PersistentVolume at `data/`. Ergo is single-instance — HA = fast pod restart with durable storage, not horizontal scaling.
196
197 ---
198
199 ## Conventions
200
@@ -196,19 +220,64 @@
220 - Branch: `feature/{issue}-short-description` or `fix/{issue}-short-description`
221 - No rebases. New commits only.
222 - No AI attribution in commits.
223
224 ---
225
226 ## HTTP API
227
228 `internal/api/` — two-mux pattern:
229
230 - **Outer mux** (unauthenticated): `POST /login`, `GET /` (redirect), `GET /ui/` (web UI)
231 - **Inner mux** (`/v1/` routes): require `Authorization: Bearer <token>` header
232
233 The API token is a random hex string generated once at startup, persisted to `data/ergo/api_token`.
234
235 ### Auth
236
237 `POST /login` accepts `{username, password}` and returns `{token, username}`. The token is the shared server API token. Rate limited to 10 attempts per minute per IP.
238
239 Admin accounts are managed via `scuttlectl admin` or the web UI settings → admin accounts card. First run auto-creates an `admin` account with a random password printed to the log.
240
241 ### Key endpoints
242
243 | Method | Path | Description |
244 |--------|------|-------------|
245 | `POST` | `/login` | Username/password login (unauthenticated) |
246 | `GET` | `/v1/status` | Server status |
247 | `GET` | `/v1/metrics` | Runtime metrics + bridge stats |
248 | `GET/PUT` | `/v1/settings/policies` | Bot config, agent policy, logging |
249 | `GET` | `/v1/agents` | List all registered agents |
250 | `POST` | `/v1/agents/register` | Register an agent |
251 | `POST` | `/v1/agents/{nick}/rotate` | Rotate credentials |
252 | `POST` | `/v1/agents/{nick}/revoke` | Revoke agent |
253 | `GET` | `/v1/channels` | List joined channels |
254 | `GET` | `/v1/channels/{ch}/stream` | SSE stream of channel messages |
255 | `GET/POST` | `/v1/admins` | List / add admin accounts |
256 | `DELETE` | `/v1/admins/{username}` | Remove admin |
257 | `PUT` | `/v1/admins/{username}/password` | Change password |
258
259 ---
260
261 ## Adding a New Bot
262
263 1. Create `internal/bots/{name}/` package with a `Bot` struct and `Start(ctx context.Context) error` method
264 2. Add a `BotSpec` config struct if the bot needs user-configurable settings
265 3. Register in `internal/bots/manager/manager.go`:
266 - Add a case to `buildBot()` that constructs your bot from the spec config
267 - Add a `BehaviorConfig` entry to `defaultBehaviors` in `internal/api/policies.go`
268 4. Add the UI config schema to `BEHAVIOR_SCHEMAS` in `internal/api/ui/index.html`
269 5. Write tests: bot logic, config parsing, edge cases. IRC connection can be skipped in unit tests.
270 6. Update this bootstrap
271
272 No separate registration file or global registry. The manager builds bots by ID from the `BotSpec`. Bots satisfy the `bot` interface (unexported in manager package):
273
274 ```go
275 type bot interface {
276 Start(ctx context.Context) error
277 }
278 ```
279
280 ---
281
282 ## Adding a New SDK
283
@@ -230,11 +299,29 @@
299 ---
300
301 ## Common Commands
302
303 ```bash
304 # Dev helper (recommended)
305 ./run.sh # build + start
306 ./run.sh restart # rebuild + restart
307 ./run.sh stop # stop
308 ./run.sh token # print current API token
309 ./run.sh log # tail the log
310 ./run.sh test # go test ./...
311 ./run.sh e2e # Playwright e2e (requires scuttlebot running)
312
313 # Direct Go commands
314 go build ./cmd/scuttlebot # build daemon
315 go build ./cmd/scuttlectl # build CLI
316 go test ./... # run all tests
317 golangci-lint run # lint
318
319 # Admin CLI
320 scuttlectl admin list # list admin accounts
321 scuttlectl admin add alice # add admin (prompts for password)
322 scuttlectl admin passwd alice # change password
323 scuttlectl admin remove alice # remove admin
324
325 # Docker
326 docker compose -f deploy/compose/docker-compose.yml up
327 ```
328
--- cmd/scuttlebot/main.go
+++ cmd/scuttlebot/main.go
@@ -1,23 +1,29 @@
11
package main
22
33
import (
44
"context"
55
"crypto/rand"
6
+ "crypto/tls"
67
"encoding/hex"
78
"flag"
89
"fmt"
910
"log/slog"
1011
"net/http"
1112
"os"
1213
"os/signal"
1314
"path/filepath"
15
+ "strings"
1416
"syscall"
1517
"time"
18
+
19
+ "golang.org/x/crypto/acme/autocert"
1620
1721
"github.com/conflicthq/scuttlebot/internal/api"
22
+ "github.com/conflicthq/scuttlebot/internal/auth"
1823
"github.com/conflicthq/scuttlebot/internal/bots/bridge"
24
+ botmanager "github.com/conflicthq/scuttlebot/internal/bots/manager"
1925
"github.com/conflicthq/scuttlebot/internal/config"
2026
"github.com/conflicthq/scuttlebot/internal/ergo"
2127
"github.com/conflicthq/scuttlebot/internal/mcp"
2228
"github.com/conflicthq/scuttlebot/internal/registry"
2329
)
@@ -51,34 +57,43 @@
5157
os.Exit(1)
5258
}
5359
cfg.Ergo.BinaryPath = abs
5460
}
5561
56
- // Generate an API token for the Ergo management API if not set.
62
+ // Load or generate a stable Ergo management API token.
63
+ // We persist it to data/ergo-api-token so it survives restarts — without
64
+ // this the token changes every launch and the NickServ password-rotation
65
+ // API call fails with 401 because ergo already loaded the old token.
66
+ ergoTokenPath := filepath.Join(cfg.Ergo.DataDir, "ergo-api-token")
5767
if cfg.Ergo.APIToken == "" {
58
- cfg.Ergo.APIToken = mustGenToken()
68
+ if raw, err := os.ReadFile(ergoTokenPath); err == nil && len(raw) > 0 {
69
+ cfg.Ergo.APIToken = strings.TrimSpace(string(raw))
70
+ } else {
71
+ cfg.Ergo.APIToken = mustGenToken()
72
+ _ = os.WriteFile(ergoTokenPath, []byte(cfg.Ergo.APIToken), 0600)
73
+ }
5974
}
6075
6176
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
6277
defer cancel()
6378
6479
log.Info("scuttlebot starting", "version", version)
6580
6681
// Start Ergo.
67
- manager := ergo.NewManager(cfg.Ergo, log)
82
+ ergoMgr := ergo.NewManager(cfg.Ergo, log)
6883
ergoErr := make(chan error, 1)
6984
go func() {
70
- if err := manager.Start(ctx); err != nil {
85
+ if err := ergoMgr.Start(ctx); err != nil {
7186
ergoErr <- err
7287
}
7388
}()
7489
7590
// Wait for Ergo to become healthy before starting the rest.
7691
healthCtx, healthCancel := context.WithTimeout(ctx, 30*time.Second)
7792
defer healthCancel()
7893
for {
79
- if _, err := manager.API().Status(); err == nil {
94
+ if _, err := ergoMgr.API().Status(); err == nil {
8095
break
8196
}
8297
select {
8398
case <-healthCtx.Done():
8499
log.Error("ergo did not become healthy in time")
@@ -90,28 +105,41 @@
90105
}
91106
}
92107
log.Info("ergo healthy")
93108
94109
// Build registry backed by Ergo's NickServ API.
95
- signingKey := []byte(mustGenToken())
96
- reg := registry.New(manager.API(), signingKey)
110
+ // Signing key persists so issued payloads stay valid across restarts.
111
+ signingKeyHex, err := loadOrCreateToken(filepath.Join(cfg.Ergo.DataDir, "signing_key"))
112
+ if err != nil {
113
+ log.Error("signing key", "err", err)
114
+ os.Exit(1)
115
+ }
116
+ reg := registry.New(ergoMgr.API(), []byte(signingKeyHex))
117
+ if err := reg.SetDataPath(filepath.Join(cfg.Ergo.DataDir, "registry.json")); err != nil {
118
+ log.Error("registry load", "err", err)
119
+ os.Exit(1)
120
+ }
97121
98
- // Shared API token — used by both REST and MCP servers.
99
- apiToken := mustGenToken()
100
- log.Info("api token", "token", apiToken) // printed once on startup — user copies this
122
+ // Shared API token — persisted so the UI token survives restarts.
123
+ apiToken, err := loadOrCreateToken(filepath.Join(cfg.Ergo.DataDir, "api_token"))
124
+ if err != nil {
125
+ log.Error("api token", "err", err)
126
+ os.Exit(1)
127
+ }
128
+ log.Info("api token", "token", apiToken) // printed on every startup
101129
tokens := []string{apiToken}
102130
103131
// Start bridge bot (powers the web chat UI).
104132
var bridgeBot *bridge.Bot
105133
if cfg.Bridge.Enabled {
106134
if cfg.Bridge.Password == "" {
107135
cfg.Bridge.Password = mustGenToken()
108136
}
109137
// Ensure the bridge's NickServ account exists with the current password.
110
- if err := manager.API().RegisterAccount(cfg.Bridge.Nick, cfg.Bridge.Password); err != nil {
138
+ if err := ergoMgr.API().RegisterAccount(cfg.Bridge.Nick, cfg.Bridge.Password); err != nil {
111139
// Account exists from a previous run — update the password so it matches.
112
- if err2 := manager.API().ChangePassword(cfg.Bridge.Nick, cfg.Bridge.Password); err2 != nil {
140
+ if err2 := ergoMgr.API().ChangePassword(cfg.Bridge.Nick, cfg.Bridge.Password); err2 != nil {
113141
log.Error("bridge account setup failed", "err", err2)
114142
os.Exit(1)
115143
}
116144
}
117145
bridgeBot = bridge.New(
@@ -118,34 +146,156 @@
118146
cfg.Ergo.IRCAddr,
119147
cfg.Bridge.Nick,
120148
cfg.Bridge.Password,
121149
cfg.Bridge.Channels,
122150
cfg.Bridge.BufferSize,
151
+ time.Duration(cfg.Bridge.WebUserTTLMinutes)*time.Minute,
123152
log,
124153
)
125154
go func() {
126155
if err := bridgeBot.Start(ctx); err != nil {
127156
log.Error("bridge bot error", "err", err)
128157
}
129158
}()
130159
}
160
+
161
+ // Policy store — persists behavior/agent/logging settings.
162
+ policyStore, err := api.NewPolicyStore(filepath.Join(cfg.Ergo.DataDir, "policies.json"), cfg.Bridge.WebUserTTLMinutes)
163
+ if err != nil {
164
+ log.Error("policy store", "err", err)
165
+ os.Exit(1)
166
+ }
167
+ if bridgeBot != nil {
168
+ bridgeBot.SetWebUserTTL(time.Duration(policyStore.Get().Bridge.WebUserTTLMinutes) * time.Minute)
169
+ }
170
+
171
+ // Admin store — bcrypt-hashed admin accounts.
172
+ adminStore, err := auth.NewAdminStore(filepath.Join(cfg.Ergo.DataDir, "admins.json"))
173
+ if err != nil {
174
+ log.Error("admin store", "err", err)
175
+ os.Exit(1)
176
+ }
177
+ if adminStore.IsEmpty() {
178
+ password := mustGenToken()[:16]
179
+ if err := adminStore.Add("admin", password); err != nil {
180
+ log.Error("create default admin", "err", err)
181
+ os.Exit(1)
182
+ }
183
+ log.Info("first run — default admin created", "username", "admin", "password", password, "action", "change this password immediately")
184
+ }
185
+
186
+ // Bot manager — starts/stops system bots based on policy.
187
+ botMgr := botmanager.New(cfg.Ergo.IRCAddr, cfg.Ergo.DataDir, ergoMgr.API(), &ergoChannelListAdapter{ergoMgr.API()}, log)
188
+
189
+ // Wire policy onChange to re-sync bots on every policy update.
190
+ policyStore.OnChange(func(p api.Policies) {
191
+ specs := make([]botmanager.BotSpec, len(p.Behaviors))
192
+ for i, b := range p.Behaviors {
193
+ specs[i] = botmanager.BotSpec{
194
+ ID: b.ID,
195
+ Nick: b.Nick,
196
+ Enabled: b.Enabled,
197
+ JoinAllChannels: b.JoinAllChannels,
198
+ RequiredChannels: b.RequiredChannels,
199
+ Config: b.Config,
200
+ }
201
+ }
202
+ if bridgeBot != nil {
203
+ bridgeBot.SetWebUserTTL(time.Duration(p.Bridge.WebUserTTLMinutes) * time.Minute)
204
+ }
205
+ botMgr.Sync(ctx, specs)
206
+ })
207
+
208
+ // Initial bot sync from loaded policies.
209
+ {
210
+ p := policyStore.Get()
211
+ specs := make([]botmanager.BotSpec, len(p.Behaviors))
212
+ for i, b := range p.Behaviors {
213
+ specs[i] = botmanager.BotSpec{
214
+ ID: b.ID,
215
+ Nick: b.Nick,
216
+ Enabled: b.Enabled,
217
+ JoinAllChannels: b.JoinAllChannels,
218
+ RequiredChannels: b.RequiredChannels,
219
+ Config: b.Config,
220
+ }
221
+ }
222
+ botMgr.Sync(ctx, specs)
223
+ }
131224
132225
// Start HTTP REST API server.
133
- apiSrv := api.New(reg, tokens, bridgeBot, log)
134
- httpServer := &http.Server{
135
- Addr: cfg.APIAddr,
136
- Handler: apiSrv.Handler(),
137
- }
138
- go func() {
139
- log.Info("api server listening", "addr", httpServer.Addr)
140
- if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
141
- log.Error("api server error", "err", err)
142
- }
143
- }()
226
+ var llmCfg *config.LLMConfig
227
+ if len(cfg.LLM.Backends) > 0 {
228
+ llmCfg = &cfg.LLM
229
+ }
230
+ apiSrv := api.New(reg, tokens, bridgeBot, policyStore, adminStore, llmCfg, cfg.TLS.Domain, log)
231
+ handler := apiSrv.Handler()
232
+
233
+ var httpServer, tlsServer *http.Server
234
+
235
+ if cfg.TLS.Domain != "" {
236
+ certDir := cfg.TLS.CertDir
237
+ if certDir == "" {
238
+ certDir = filepath.Join(cfg.Ergo.DataDir, "certs")
239
+ }
240
+ if err := os.MkdirAll(certDir, 0700); err != nil {
241
+ log.Error("create cert dir", "err", err)
242
+ os.Exit(1)
243
+ }
244
+
245
+ m := &autocert.Manager{
246
+ Cache: autocert.DirCache(certDir),
247
+ Prompt: autocert.AcceptTOS,
248
+ Email: cfg.TLS.Email,
249
+ HostPolicy: autocert.HostWhitelist(cfg.TLS.Domain),
250
+ }
251
+
252
+ // HTTPS on :443
253
+ tlsServer = &http.Server{
254
+ Addr: ":443",
255
+ Handler: handler,
256
+ TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
257
+ }
258
+ go func() {
259
+ log.Info("api server listening (TLS)", "addr", ":443", "domain", cfg.TLS.Domain)
260
+ if err := tlsServer.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
261
+ log.Error("tls server error", "err", err)
262
+ }
263
+ }()
264
+
265
+ // HTTP on :80 — ACME challenge always enabled; also serves API when AllowInsecure.
266
+ var httpHandler http.Handler
267
+ if cfg.TLS.AllowInsecure {
268
+ httpHandler = m.HTTPHandler(handler)
269
+ } else {
270
+ httpHandler = m.HTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
271
+ http.Redirect(w, r, "https://"+cfg.TLS.Domain+r.RequestURI, http.StatusMovedPermanently)
272
+ }))
273
+ }
274
+ httpServer = &http.Server{Addr: ":80", Handler: httpHandler}
275
+ go func() {
276
+ log.Info("http server listening", "addr", ":80", "insecure", cfg.TLS.AllowInsecure)
277
+ if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
278
+ log.Error("http server error", "err", err)
279
+ }
280
+ }()
281
+ } else {
282
+ // No TLS — plain HTTP on configured addr.
283
+ httpServer = &http.Server{
284
+ Addr: cfg.APIAddr,
285
+ Handler: handler,
286
+ }
287
+ go func() {
288
+ log.Info("api server listening", "addr", httpServer.Addr)
289
+ if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
290
+ log.Error("api server error", "err", err)
291
+ }
292
+ }()
293
+ }
144294
145295
// Start MCP server.
146
- mcpSrv := mcp.New(reg, &ergoChannelLister{manager.API()}, tokens, log)
296
+ mcpSrv := mcp.New(reg, &ergoChannelLister{ergoMgr.API()}, tokens, log)
147297
mcpServer := &http.Server{
148298
Addr: cfg.MCPAddr,
149299
Handler: mcpSrv.Handler(),
150300
}
151301
go func() {
@@ -158,15 +308,37 @@
158308
<-ctx.Done()
159309
log.Info("shutting down")
160310
161311
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
162312
defer shutdownCancel()
163
- _ = httpServer.Shutdown(shutdownCtx)
313
+ if httpServer != nil {
314
+ _ = httpServer.Shutdown(shutdownCtx)
315
+ }
316
+ if tlsServer != nil {
317
+ _ = tlsServer.Shutdown(shutdownCtx)
318
+ }
164319
_ = mcpServer.Shutdown(shutdownCtx)
165320
166321
log.Info("goodbye")
167322
}
323
+
324
+// ergoChannelListAdapter adapts ergo.APIClient to botmanager.ChannelLister.
325
+type ergoChannelListAdapter struct {
326
+ api *ergo.APIClient
327
+}
328
+
329
+func (e *ergoChannelListAdapter) ListChannels() ([]string, error) {
330
+ resp, err := e.api.ListChannels()
331
+ if err != nil {
332
+ return nil, err
333
+ }
334
+ out := make([]string, len(resp.Channels))
335
+ for i, ch := range resp.Channels {
336
+ out[i] = ch.Name
337
+ }
338
+ return out, nil
339
+}
168340
169341
// ergoChannelLister adapts ergo.APIClient to mcp.ChannelLister.
170342
type ergoChannelLister struct {
171343
api *ergo.APIClient
172344
}
@@ -193,5 +365,25 @@
193365
fmt.Fprintf(os.Stderr, "failed to generate token: %v\n", err)
194366
os.Exit(1)
195367
}
196368
return hex.EncodeToString(b)
197369
}
370
+
371
+// loadOrCreateToken reads a token from path. If the file doesn't exist it
372
+// generates a new token, writes it, and returns it.
373
+func loadOrCreateToken(path string) (string, error) {
374
+ data, err := os.ReadFile(path)
375
+ if err == nil {
376
+ t := strings.TrimSpace(string(data))
377
+ if t != "" {
378
+ return t, nil
379
+ }
380
+ }
381
+ if !os.IsNotExist(err) && err != nil {
382
+ return "", fmt.Errorf("read token %s: %w", path, err)
383
+ }
384
+ token := mustGenToken()
385
+ if err := os.WriteFile(path, []byte(token+"\n"), 0600); err != nil {
386
+ return "", fmt.Errorf("write token %s: %w", path, err)
387
+ }
388
+ return token, nil
389
+}
198390
199391
ADDED cmd/scuttlectl/cmd_setup.go
--- cmd/scuttlebot/main.go
+++ cmd/scuttlebot/main.go
@@ -1,23 +1,29 @@
1 package main
2
3 import (
4 "context"
5 "crypto/rand"
 
6 "encoding/hex"
7 "flag"
8 "fmt"
9 "log/slog"
10 "net/http"
11 "os"
12 "os/signal"
13 "path/filepath"
 
14 "syscall"
15 "time"
 
 
16
17 "github.com/conflicthq/scuttlebot/internal/api"
 
18 "github.com/conflicthq/scuttlebot/internal/bots/bridge"
 
19 "github.com/conflicthq/scuttlebot/internal/config"
20 "github.com/conflicthq/scuttlebot/internal/ergo"
21 "github.com/conflicthq/scuttlebot/internal/mcp"
22 "github.com/conflicthq/scuttlebot/internal/registry"
23 )
@@ -51,34 +57,43 @@
51 os.Exit(1)
52 }
53 cfg.Ergo.BinaryPath = abs
54 }
55
56 // Generate an API token for the Ergo management API if not set.
 
 
 
 
57 if cfg.Ergo.APIToken == "" {
58 cfg.Ergo.APIToken = mustGenToken()
 
 
 
 
 
59 }
60
61 ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
62 defer cancel()
63
64 log.Info("scuttlebot starting", "version", version)
65
66 // Start Ergo.
67 manager := ergo.NewManager(cfg.Ergo, log)
68 ergoErr := make(chan error, 1)
69 go func() {
70 if err := manager.Start(ctx); err != nil {
71 ergoErr <- err
72 }
73 }()
74
75 // Wait for Ergo to become healthy before starting the rest.
76 healthCtx, healthCancel := context.WithTimeout(ctx, 30*time.Second)
77 defer healthCancel()
78 for {
79 if _, err := manager.API().Status(); err == nil {
80 break
81 }
82 select {
83 case <-healthCtx.Done():
84 log.Error("ergo did not become healthy in time")
@@ -90,28 +105,41 @@
90 }
91 }
92 log.Info("ergo healthy")
93
94 // Build registry backed by Ergo's NickServ API.
95 signingKey := []byte(mustGenToken())
96 reg := registry.New(manager.API(), signingKey)
 
 
 
 
 
 
 
 
 
97
98 // Shared API token — used by both REST and MCP servers.
99 apiToken := mustGenToken()
100 log.Info("api token", "token", apiToken) // printed once on startup — user copies this
 
 
 
 
101 tokens := []string{apiToken}
102
103 // Start bridge bot (powers the web chat UI).
104 var bridgeBot *bridge.Bot
105 if cfg.Bridge.Enabled {
106 if cfg.Bridge.Password == "" {
107 cfg.Bridge.Password = mustGenToken()
108 }
109 // Ensure the bridge's NickServ account exists with the current password.
110 if err := manager.API().RegisterAccount(cfg.Bridge.Nick, cfg.Bridge.Password); err != nil {
111 // Account exists from a previous run — update the password so it matches.
112 if err2 := manager.API().ChangePassword(cfg.Bridge.Nick, cfg.Bridge.Password); err2 != nil {
113 log.Error("bridge account setup failed", "err", err2)
114 os.Exit(1)
115 }
116 }
117 bridgeBot = bridge.New(
@@ -118,34 +146,156 @@
118 cfg.Ergo.IRCAddr,
119 cfg.Bridge.Nick,
120 cfg.Bridge.Password,
121 cfg.Bridge.Channels,
122 cfg.Bridge.BufferSize,
 
123 log,
124 )
125 go func() {
126 if err := bridgeBot.Start(ctx); err != nil {
127 log.Error("bridge bot error", "err", err)
128 }
129 }()
130 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
132 // Start HTTP REST API server.
133 apiSrv := api.New(reg, tokens, bridgeBot, log)
134 httpServer := &http.Server{
135 Addr: cfg.APIAddr,
136 Handler: apiSrv.Handler(),
137 }
138 go func() {
139 log.Info("api server listening", "addr", httpServer.Addr)
140 if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
141 log.Error("api server error", "err", err)
142 }
143 }()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
145 // Start MCP server.
146 mcpSrv := mcp.New(reg, &ergoChannelLister{manager.API()}, tokens, log)
147 mcpServer := &http.Server{
148 Addr: cfg.MCPAddr,
149 Handler: mcpSrv.Handler(),
150 }
151 go func() {
@@ -158,15 +308,37 @@
158 <-ctx.Done()
159 log.Info("shutting down")
160
161 shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
162 defer shutdownCancel()
163 _ = httpServer.Shutdown(shutdownCtx)
 
 
 
 
 
164 _ = mcpServer.Shutdown(shutdownCtx)
165
166 log.Info("goodbye")
167 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
169 // ergoChannelLister adapts ergo.APIClient to mcp.ChannelLister.
170 type ergoChannelLister struct {
171 api *ergo.APIClient
172 }
@@ -193,5 +365,25 @@
193 fmt.Fprintf(os.Stderr, "failed to generate token: %v\n", err)
194 os.Exit(1)
195 }
196 return hex.EncodeToString(b)
197 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
199 DDED cmd/scuttlectl/cmd_setup.go
--- cmd/scuttlebot/main.go
+++ cmd/scuttlebot/main.go
@@ -1,23 +1,29 @@
1 package main
2
3 import (
4 "context"
5 "crypto/rand"
6 "crypto/tls"
7 "encoding/hex"
8 "flag"
9 "fmt"
10 "log/slog"
11 "net/http"
12 "os"
13 "os/signal"
14 "path/filepath"
15 "strings"
16 "syscall"
17 "time"
18
19 "golang.org/x/crypto/acme/autocert"
20
21 "github.com/conflicthq/scuttlebot/internal/api"
22 "github.com/conflicthq/scuttlebot/internal/auth"
23 "github.com/conflicthq/scuttlebot/internal/bots/bridge"
24 botmanager "github.com/conflicthq/scuttlebot/internal/bots/manager"
25 "github.com/conflicthq/scuttlebot/internal/config"
26 "github.com/conflicthq/scuttlebot/internal/ergo"
27 "github.com/conflicthq/scuttlebot/internal/mcp"
28 "github.com/conflicthq/scuttlebot/internal/registry"
29 )
@@ -51,34 +57,43 @@
57 os.Exit(1)
58 }
59 cfg.Ergo.BinaryPath = abs
60 }
61
62 // Load or generate a stable Ergo management API token.
63 // We persist it to data/ergo-api-token so it survives restarts — without
64 // this the token changes every launch and the NickServ password-rotation
65 // API call fails with 401 because ergo already loaded the old token.
66 ergoTokenPath := filepath.Join(cfg.Ergo.DataDir, "ergo-api-token")
67 if cfg.Ergo.APIToken == "" {
68 if raw, err := os.ReadFile(ergoTokenPath); err == nil && len(raw) > 0 {
69 cfg.Ergo.APIToken = strings.TrimSpace(string(raw))
70 } else {
71 cfg.Ergo.APIToken = mustGenToken()
72 _ = os.WriteFile(ergoTokenPath, []byte(cfg.Ergo.APIToken), 0600)
73 }
74 }
75
76 ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
77 defer cancel()
78
79 log.Info("scuttlebot starting", "version", version)
80
81 // Start Ergo.
82 ergoMgr := ergo.NewManager(cfg.Ergo, log)
83 ergoErr := make(chan error, 1)
84 go func() {
85 if err := ergoMgr.Start(ctx); err != nil {
86 ergoErr <- err
87 }
88 }()
89
90 // Wait for Ergo to become healthy before starting the rest.
91 healthCtx, healthCancel := context.WithTimeout(ctx, 30*time.Second)
92 defer healthCancel()
93 for {
94 if _, err := ergoMgr.API().Status(); err == nil {
95 break
96 }
97 select {
98 case <-healthCtx.Done():
99 log.Error("ergo did not become healthy in time")
@@ -90,28 +105,41 @@
105 }
106 }
107 log.Info("ergo healthy")
108
109 // Build registry backed by Ergo's NickServ API.
110 // Signing key persists so issued payloads stay valid across restarts.
111 signingKeyHex, err := loadOrCreateToken(filepath.Join(cfg.Ergo.DataDir, "signing_key"))
112 if err != nil {
113 log.Error("signing key", "err", err)
114 os.Exit(1)
115 }
116 reg := registry.New(ergoMgr.API(), []byte(signingKeyHex))
117 if err := reg.SetDataPath(filepath.Join(cfg.Ergo.DataDir, "registry.json")); err != nil {
118 log.Error("registry load", "err", err)
119 os.Exit(1)
120 }
121
122 // Shared API token — persisted so the UI token survives restarts.
123 apiToken, err := loadOrCreateToken(filepath.Join(cfg.Ergo.DataDir, "api_token"))
124 if err != nil {
125 log.Error("api token", "err", err)
126 os.Exit(1)
127 }
128 log.Info("api token", "token", apiToken) // printed on every startup
129 tokens := []string{apiToken}
130
131 // Start bridge bot (powers the web chat UI).
132 var bridgeBot *bridge.Bot
133 if cfg.Bridge.Enabled {
134 if cfg.Bridge.Password == "" {
135 cfg.Bridge.Password = mustGenToken()
136 }
137 // Ensure the bridge's NickServ account exists with the current password.
138 if err := ergoMgr.API().RegisterAccount(cfg.Bridge.Nick, cfg.Bridge.Password); err != nil {
139 // Account exists from a previous run — update the password so it matches.
140 if err2 := ergoMgr.API().ChangePassword(cfg.Bridge.Nick, cfg.Bridge.Password); err2 != nil {
141 log.Error("bridge account setup failed", "err", err2)
142 os.Exit(1)
143 }
144 }
145 bridgeBot = bridge.New(
@@ -118,34 +146,156 @@
146 cfg.Ergo.IRCAddr,
147 cfg.Bridge.Nick,
148 cfg.Bridge.Password,
149 cfg.Bridge.Channels,
150 cfg.Bridge.BufferSize,
151 time.Duration(cfg.Bridge.WebUserTTLMinutes)*time.Minute,
152 log,
153 )
154 go func() {
155 if err := bridgeBot.Start(ctx); err != nil {
156 log.Error("bridge bot error", "err", err)
157 }
158 }()
159 }
160
161 // Policy store — persists behavior/agent/logging settings.
162 policyStore, err := api.NewPolicyStore(filepath.Join(cfg.Ergo.DataDir, "policies.json"), cfg.Bridge.WebUserTTLMinutes)
163 if err != nil {
164 log.Error("policy store", "err", err)
165 os.Exit(1)
166 }
167 if bridgeBot != nil {
168 bridgeBot.SetWebUserTTL(time.Duration(policyStore.Get().Bridge.WebUserTTLMinutes) * time.Minute)
169 }
170
171 // Admin store — bcrypt-hashed admin accounts.
172 adminStore, err := auth.NewAdminStore(filepath.Join(cfg.Ergo.DataDir, "admins.json"))
173 if err != nil {
174 log.Error("admin store", "err", err)
175 os.Exit(1)
176 }
177 if adminStore.IsEmpty() {
178 password := mustGenToken()[:16]
179 if err := adminStore.Add("admin", password); err != nil {
180 log.Error("create default admin", "err", err)
181 os.Exit(1)
182 }
183 log.Info("first run — default admin created", "username", "admin", "password", password, "action", "change this password immediately")
184 }
185
186 // Bot manager — starts/stops system bots based on policy.
187 botMgr := botmanager.New(cfg.Ergo.IRCAddr, cfg.Ergo.DataDir, ergoMgr.API(), &ergoChannelListAdapter{ergoMgr.API()}, log)
188
189 // Wire policy onChange to re-sync bots on every policy update.
190 policyStore.OnChange(func(p api.Policies) {
191 specs := make([]botmanager.BotSpec, len(p.Behaviors))
192 for i, b := range p.Behaviors {
193 specs[i] = botmanager.BotSpec{
194 ID: b.ID,
195 Nick: b.Nick,
196 Enabled: b.Enabled,
197 JoinAllChannels: b.JoinAllChannels,
198 RequiredChannels: b.RequiredChannels,
199 Config: b.Config,
200 }
201 }
202 if bridgeBot != nil {
203 bridgeBot.SetWebUserTTL(time.Duration(p.Bridge.WebUserTTLMinutes) * time.Minute)
204 }
205 botMgr.Sync(ctx, specs)
206 })
207
208 // Initial bot sync from loaded policies.
209 {
210 p := policyStore.Get()
211 specs := make([]botmanager.BotSpec, len(p.Behaviors))
212 for i, b := range p.Behaviors {
213 specs[i] = botmanager.BotSpec{
214 ID: b.ID,
215 Nick: b.Nick,
216 Enabled: b.Enabled,
217 JoinAllChannels: b.JoinAllChannels,
218 RequiredChannels: b.RequiredChannels,
219 Config: b.Config,
220 }
221 }
222 botMgr.Sync(ctx, specs)
223 }
224
225 // Start HTTP REST API server.
226 var llmCfg *config.LLMConfig
227 if len(cfg.LLM.Backends) > 0 {
228 llmCfg = &cfg.LLM
229 }
230 apiSrv := api.New(reg, tokens, bridgeBot, policyStore, adminStore, llmCfg, cfg.TLS.Domain, log)
231 handler := apiSrv.Handler()
232
233 var httpServer, tlsServer *http.Server
234
235 if cfg.TLS.Domain != "" {
236 certDir := cfg.TLS.CertDir
237 if certDir == "" {
238 certDir = filepath.Join(cfg.Ergo.DataDir, "certs")
239 }
240 if err := os.MkdirAll(certDir, 0700); err != nil {
241 log.Error("create cert dir", "err", err)
242 os.Exit(1)
243 }
244
245 m := &autocert.Manager{
246 Cache: autocert.DirCache(certDir),
247 Prompt: autocert.AcceptTOS,
248 Email: cfg.TLS.Email,
249 HostPolicy: autocert.HostWhitelist(cfg.TLS.Domain),
250 }
251
252 // HTTPS on :443
253 tlsServer = &http.Server{
254 Addr: ":443",
255 Handler: handler,
256 TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
257 }
258 go func() {
259 log.Info("api server listening (TLS)", "addr", ":443", "domain", cfg.TLS.Domain)
260 if err := tlsServer.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
261 log.Error("tls server error", "err", err)
262 }
263 }()
264
265 // HTTP on :80 — ACME challenge always enabled; also serves API when AllowInsecure.
266 var httpHandler http.Handler
267 if cfg.TLS.AllowInsecure {
268 httpHandler = m.HTTPHandler(handler)
269 } else {
270 httpHandler = m.HTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
271 http.Redirect(w, r, "https://"+cfg.TLS.Domain+r.RequestURI, http.StatusMovedPermanently)
272 }))
273 }
274 httpServer = &http.Server{Addr: ":80", Handler: httpHandler}
275 go func() {
276 log.Info("http server listening", "addr", ":80", "insecure", cfg.TLS.AllowInsecure)
277 if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
278 log.Error("http server error", "err", err)
279 }
280 }()
281 } else {
282 // No TLS — plain HTTP on configured addr.
283 httpServer = &http.Server{
284 Addr: cfg.APIAddr,
285 Handler: handler,
286 }
287 go func() {
288 log.Info("api server listening", "addr", httpServer.Addr)
289 if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
290 log.Error("api server error", "err", err)
291 }
292 }()
293 }
294
295 // Start MCP server.
296 mcpSrv := mcp.New(reg, &ergoChannelLister{ergoMgr.API()}, tokens, log)
297 mcpServer := &http.Server{
298 Addr: cfg.MCPAddr,
299 Handler: mcpSrv.Handler(),
300 }
301 go func() {
@@ -158,15 +308,37 @@
308 <-ctx.Done()
309 log.Info("shutting down")
310
311 shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
312 defer shutdownCancel()
313 if httpServer != nil {
314 _ = httpServer.Shutdown(shutdownCtx)
315 }
316 if tlsServer != nil {
317 _ = tlsServer.Shutdown(shutdownCtx)
318 }
319 _ = mcpServer.Shutdown(shutdownCtx)
320
321 log.Info("goodbye")
322 }
323
324 // ergoChannelListAdapter adapts ergo.APIClient to botmanager.ChannelLister.
325 type ergoChannelListAdapter struct {
326 api *ergo.APIClient
327 }
328
329 func (e *ergoChannelListAdapter) ListChannels() ([]string, error) {
330 resp, err := e.api.ListChannels()
331 if err != nil {
332 return nil, err
333 }
334 out := make([]string, len(resp.Channels))
335 for i, ch := range resp.Channels {
336 out[i] = ch.Name
337 }
338 return out, nil
339 }
340
341 // ergoChannelLister adapts ergo.APIClient to mcp.ChannelLister.
342 type ergoChannelLister struct {
343 api *ergo.APIClient
344 }
@@ -193,5 +365,25 @@
365 fmt.Fprintf(os.Stderr, "failed to generate token: %v\n", err)
366 os.Exit(1)
367 }
368 return hex.EncodeToString(b)
369 }
370
371 // loadOrCreateToken reads a token from path. If the file doesn't exist it
372 // generates a new token, writes it, and returns it.
373 func loadOrCreateToken(path string) (string, error) {
374 data, err := os.ReadFile(path)
375 if err == nil {
376 t := strings.TrimSpace(string(data))
377 if t != "" {
378 return t, nil
379 }
380 }
381 if !os.IsNotExist(err) && err != nil {
382 return "", fmt.Errorf("read token %s: %w", path, err)
383 }
384 token := mustGenToken()
385 if err := os.WriteFile(path, []byte(token+"\n"), 0600); err != nil {
386 return "", fmt.Errorf("write token %s: %w", path, err)
387 }
388 return token, nil
389 }
390
391 DDED cmd/scuttlectl/cmd_setup.go
--- a/cmd/scuttlectl/cmd_setup.go
+++ b/cmd/scuttlectl/cmd_setup.go
@@ -0,0 +1,217 @@
1
+package main
2
+
3
+import (
4
+ "bufio"
5
+ "fmt"
6
+ "os"
7
+ "strconv"
8
+ "strings"
9
+
10
+ "gopkg.in/yaml.v3"
11
+)
12
+
13
+// cmdSetup runs an interactive wizard that writes scuttlebot.yaml.
14
+// It does not require a running server or an API token.
15
+func cmdSetup(path string) {
16
+ s := newSetupScanner()
17
+
18
+ fmt.Println()
19
+ fmt.Println(" scuttlebot setup wizard")
20
+ fmt.Println(" ─────────────────────────────────────────")
21
+ fmt.Println(" Answers in [brackets] are the default — press Enter to accept.")
22
+ fmt.Println()
23
+
24
+ // Check for existing file.
25
+ if _, err := os.Stat(path); err == nil {
26
+ if !s.confirm(fmt.Sprintf(" %s already exists — overwrite?", path), false) {
27
+ fmt.Println(" Aborted.")
28
+ os.Exit(0)
29
+ }
30
+ }
31
+
32
+ cfg := buildConfig(s)
33
+
34
+ data, err := yaml.Marshal(cfg)
35
+ if err != nil {
36
+ fmt.Fprintln(os.Stderr, "error encoding yaml:", err)
37
+ os.Exit(1)
38
+ }
39
+
40
+ if err := os.WriteFile(path, data, 0600); err != nil {
41
+ fmt.Fprintln(os.Stderr, "error writing config:", err)
42
+ os.Exit(1)
43
+ }
44
+
45
+ fmt.Println()
46
+ fmt.Printf(" ✓ wrote %s\n", path)
47
+ fmt.Println()
48
+ fmt.Println(" Next steps:")
49
+ fmt.Println(" ./run.sh start # start scuttlebot")
50
+ fmt.Println(" ./run.sh token # print API token")
51
+ fmt.Println(" open http://localhost:8080/ui/")
52
+ fmt.Println()
53
+}
54
+
55
+func buildConfig(s *setupScanner) map[string]any {
56
+ cfg := map[string]any{}
57
+
58
+ // ── network ──────────────────────────────────────────────────────────────
59
+ printSection("IRC / network")
60
+
61
+ networkName := s.ask(" IRC network name",, "scuttlebot")
62
+ serverName := s.ask(" IRC server hostname", "irc.s scuttlebot.local")
63
+ ircAddr := s.a "127.0.0.1:6667")
64
+ apiAddr := s.ask(" HTTP API listen address", ":8080")
65
+
66
+ cfg["ergo"] = map[string]any{
67
+ "network_name": networkName,
68
+ "server_name": serverName,
69
+ "irc_addr": ircAddr,
70
+ }
71
+ cfg["api_addr"] = apiAddr
72
+
73
+ // ── TLS ──────────────────────────────────────────────────────────────────
74
+ printSection("TLS / HTTPS (skip for local/dev)")
75
+
76
+ if s.confirm(" Enable Let's Encrypt TLS?", faSprintf(" %s already exists — overwrite?", path), false) {
77
+ fmt.Println(" Aborted.")
78
+ os.Exit(0)
79
+ }
80
+ }
81
+
82
+ cfg := buildConfig(s)
83
+
84
+ data, err := yaml.Marshal(cfg)
85
+ if err != nil {
86
+ fmt.Fprintln(os.Stderr, "error encoding yaml:", err)
87
+ os.Exit(1)
88
+ }
89
+
90
+ if err := os.WriteFile(path, data, 0600); err != nil {
91
+ fmt.Fprintln(os.Stderr, "error writing config:", err)
92
+ os.Exit(1)
93
+ }
94
+
95
+ fmt.Println()
96
+ fmt.Printf(" ✓ wrote %s\n", path)
97
+ fmt.Println()
98
+ fmt.Println(" Next steps:")
99
+ fmt.Println(" ./run.sh start # start scuttlebot")
100
+ fmt.Println(" ./run.sh token # print API token")
101
+ fmt.Println(" open http://localhost:8080/ui/")
102
+ fmt.Println()
103
+}
104
+
105
+func buildConfig(s *setupScanner) map[string]any {
106
+ cfg := map[string]any{}
107
+
108
+ // ── network ──────────────────────────────────────────────────────────────
109
+ printSection("IRC / network")
110
+
111
+ networkName := s.ask(" IRC network name", "scuttlebot")
112
+ serverName := s.ask(" IRC server hostname", "irc.scuttlebot.local")
113
+ ircAddr := s.ask(" IRC listen address", "127.0.0.1:6667")
114
+ apiAddr := s.ask(" HTTP API listen address", ":8080")
115
+
116
+ cfg["ergo"] = map[string]any{
117
+ "network_name": networkName,
118
+ "server_name": serverName,
119
+ "irc_addr": ircAddr,
120
+ }
121
+ cfg["api_addr"] = apiAddr
122
+
123
+ // ── TLS ────────�───────────�────────────────────
124
+ printSection("TLS / HTTPS (skip for local/dev)")
125
+
126
+ if s.confirm(" Enable Let's Encrypt TLS?", false) {
127
+ domain := s.ask(" Domain name", "")
128
+ email := s.ask(" Email for cert expiry notices", "")
129
+ cfg["t; _ = format; _ = logDir
130
+ _ = format
131
+ _ = rotatef
132
+ fmt.Printf("\n Note: scribe is enabled via the web UI (settings → system behaviors).\n")
133
+ fmt.Printf(" Set dir=%s format=%s rotation=%s in oracle's behavior config.\n\n", logDir, format, rotatef)
134
+ }
135
+
136
+ return cfg
137
+}
138
+
139
+func buildBackend(s *setupScanner) map[string]any {
140
+ backends := []string{
141
+ "openai", "anthropic", "gemini", "bedrock", "ollama",
142
+ "openrouter", "groq", "together", "fireworks", "mistral",
143
+ "deepseek", "xai", "cerebras", "litellm", "lmstudio", "vllm", "localai",
144
+ }
145
+ backendType := s.choice(" Backend type", backends, "openai")
146
+ name := s.ask(" Backend name (identifier)", backendType+"-1")
147
+
148
+ b := map[string]any{
149
+ "name": name,
150
+ "backend": backendType,
151
+ }
152
+
153
+ switch backendType {
154
+ case "bedrock":
155
+ b["region"] = s.ask(" AWS region", "us-east-1")
156
+ if s.confirm(" Use static AWS credentials? (No = IAM role auto-detected)", f false) {
157
+ b["aws_key_id"] = s.ask(" AWS access key ID", "")
158
+ b["aws_secret_key"] = s.ask(" AWS secret access key", "")
159
+ } else {
160
+ fmt.Println(" → credentials will be resolved from env vars or instance/task role")
161
+ }
162
+ b["model"] = s.ask(" Default model", "anthropic.claude-3-5-sonnet-20241022-v2:0")
163
+
164
+ case "ollama":
165
+ b["base_url"] = s.ask(" Ollama base URL", "http://loca = s.ask(" Default model", "llama3.2")
166
+
167
+ case "anthropic":
168
+ b["api_key"] = s.secret(" API key")
169
+ b["model"] = s.ask(" Default model", "claude-3-5-sonnet-20241022")
170
+
171
+ case "gemini":
172
+ b["api_key"] = s.secret(" API key")
173
+ b["model"] = s.ask(" Default model", "gemini-1.5-flash")
174
+
175
+ default:
176
+ b["api_key"] = s.secret(" API key")
177
+ b["model"] = s.ask(" Default model", = s.ask(" Default model", defaultModelFor(backendType))
178
+ }
179
+
180
+ if s.confirm(" Add model allow/block regex filters?", false) {
181
+ allow := s.ask(" Allow patterns (comma-separated regex)", "")
182
+ block := s.ask(" Block patterns (comma-separated regex)", "")
183
+ if allow != "" {
184
+ b["allow"] = splitComma(allow)
185
+ }
186
+ if block != "" {
187
+ b["block"] = splitComma(block)
188
+ }
189
+ }
190
+
191
+ if s.confirm(" Mark as default backend?", len([]map[string]any{b}) == 0) {
192
+ b["default"] = true
193
+ }
194
+
195
+ return b
196
+}
197
+
198
+func defaultModelFor(backend string) strackage main
199
+
200
+import (
201
+ "bufio"
202
+ "
203
+ "fmt"
204
+ "ofmt"
205
+ "os"
206
+ "strcdentifier)", backendType+"-1")
207
+
208
+ me": name,
209
+ "backend": backendType,
210
+ }
211
+
212
+ switch backendType {
213
+ casse "bedrock":
214
+
215
+ b["region"] = s.ask(" AWS regionfirm(" Use static AWS crconfirm(" Use static AWS credent "",
216
+ "lmstudio": "",
217
+ "vllm
--- a/cmd/scuttlectl/cmd_setup.go
+++ b/cmd/scuttlectl/cmd_setup.go
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/cmd/scuttlectl/cmd_setup.go
+++ b/cmd/scuttlectl/cmd_setup.go
@@ -0,0 +1,217 @@
1 package main
2
3 import (
4 "bufio"
5 "fmt"
6 "os"
7 "strconv"
8 "strings"
9
10 "gopkg.in/yaml.v3"
11 )
12
13 // cmdSetup runs an interactive wizard that writes scuttlebot.yaml.
14 // It does not require a running server or an API token.
15 func cmdSetup(path string) {
16 s := newSetupScanner()
17
18 fmt.Println()
19 fmt.Println(" scuttlebot setup wizard")
20 fmt.Println(" ─────────────────────────────────────────")
21 fmt.Println(" Answers in [brackets] are the default — press Enter to accept.")
22 fmt.Println()
23
24 // Check for existing file.
25 if _, err := os.Stat(path); err == nil {
26 if !s.confirm(fmt.Sprintf(" %s already exists — overwrite?", path), false) {
27 fmt.Println(" Aborted.")
28 os.Exit(0)
29 }
30 }
31
32 cfg := buildConfig(s)
33
34 data, err := yaml.Marshal(cfg)
35 if err != nil {
36 fmt.Fprintln(os.Stderr, "error encoding yaml:", err)
37 os.Exit(1)
38 }
39
40 if err := os.WriteFile(path, data, 0600); err != nil {
41 fmt.Fprintln(os.Stderr, "error writing config:", err)
42 os.Exit(1)
43 }
44
45 fmt.Println()
46 fmt.Printf(" ✓ wrote %s\n", path)
47 fmt.Println()
48 fmt.Println(" Next steps:")
49 fmt.Println(" ./run.sh start # start scuttlebot")
50 fmt.Println(" ./run.sh token # print API token")
51 fmt.Println(" open http://localhost:8080/ui/")
52 fmt.Println()
53 }
54
55 func buildConfig(s *setupScanner) map[string]any {
56 cfg := map[string]any{}
57
58 // ── network ──────────────────────────────────────────────────────────────
59 printSection("IRC / network")
60
61 networkName := s.ask(" IRC network name",, "scuttlebot")
62 serverName := s.ask(" IRC server hostname", "irc.s scuttlebot.local")
63 ircAddr := s.a "127.0.0.1:6667")
64 apiAddr := s.ask(" HTTP API listen address", ":8080")
65
66 cfg["ergo"] = map[string]any{
67 "network_name": networkName,
68 "server_name": serverName,
69 "irc_addr": ircAddr,
70 }
71 cfg["api_addr"] = apiAddr
72
73 // ── TLS ──────────────────────────────────────────────────────────────────
74 printSection("TLS / HTTPS (skip for local/dev)")
75
76 if s.confirm(" Enable Let's Encrypt TLS?", faSprintf(" %s already exists — overwrite?", path), false) {
77 fmt.Println(" Aborted.")
78 os.Exit(0)
79 }
80 }
81
82 cfg := buildConfig(s)
83
84 data, err := yaml.Marshal(cfg)
85 if err != nil {
86 fmt.Fprintln(os.Stderr, "error encoding yaml:", err)
87 os.Exit(1)
88 }
89
90 if err := os.WriteFile(path, data, 0600); err != nil {
91 fmt.Fprintln(os.Stderr, "error writing config:", err)
92 os.Exit(1)
93 }
94
95 fmt.Println()
96 fmt.Printf(" ✓ wrote %s\n", path)
97 fmt.Println()
98 fmt.Println(" Next steps:")
99 fmt.Println(" ./run.sh start # start scuttlebot")
100 fmt.Println(" ./run.sh token # print API token")
101 fmt.Println(" open http://localhost:8080/ui/")
102 fmt.Println()
103 }
104
105 func buildConfig(s *setupScanner) map[string]any {
106 cfg := map[string]any{}
107
108 // ── network ──────────────────────────────────────────────────────────────
109 printSection("IRC / network")
110
111 networkName := s.ask(" IRC network name", "scuttlebot")
112 serverName := s.ask(" IRC server hostname", "irc.scuttlebot.local")
113 ircAddr := s.ask(" IRC listen address", "127.0.0.1:6667")
114 apiAddr := s.ask(" HTTP API listen address", ":8080")
115
116 cfg["ergo"] = map[string]any{
117 "network_name": networkName,
118 "server_name": serverName,
119 "irc_addr": ircAddr,
120 }
121 cfg["api_addr"] = apiAddr
122
123 // ── TLS ────────�───────────�────────────────────
124 printSection("TLS / HTTPS (skip for local/dev)")
125
126 if s.confirm(" Enable Let's Encrypt TLS?", false) {
127 domain := s.ask(" Domain name", "")
128 email := s.ask(" Email for cert expiry notices", "")
129 cfg["t; _ = format; _ = logDir
130 _ = format
131 _ = rotatef
132 fmt.Printf("\n Note: scribe is enabled via the web UI (settings → system behaviors).\n")
133 fmt.Printf(" Set dir=%s format=%s rotation=%s in oracle's behavior config.\n\n", logDir, format, rotatef)
134 }
135
136 return cfg
137 }
138
139 func buildBackend(s *setupScanner) map[string]any {
140 backends := []string{
141 "openai", "anthropic", "gemini", "bedrock", "ollama",
142 "openrouter", "groq", "together", "fireworks", "mistral",
143 "deepseek", "xai", "cerebras", "litellm", "lmstudio", "vllm", "localai",
144 }
145 backendType := s.choice(" Backend type", backends, "openai")
146 name := s.ask(" Backend name (identifier)", backendType+"-1")
147
148 b := map[string]any{
149 "name": name,
150 "backend": backendType,
151 }
152
153 switch backendType {
154 case "bedrock":
155 b["region"] = s.ask(" AWS region", "us-east-1")
156 if s.confirm(" Use static AWS credentials? (No = IAM role auto-detected)", f false) {
157 b["aws_key_id"] = s.ask(" AWS access key ID", "")
158 b["aws_secret_key"] = s.ask(" AWS secret access key", "")
159 } else {
160 fmt.Println(" → credentials will be resolved from env vars or instance/task role")
161 }
162 b["model"] = s.ask(" Default model", "anthropic.claude-3-5-sonnet-20241022-v2:0")
163
164 case "ollama":
165 b["base_url"] = s.ask(" Ollama base URL", "http://loca = s.ask(" Default model", "llama3.2")
166
167 case "anthropic":
168 b["api_key"] = s.secret(" API key")
169 b["model"] = s.ask(" Default model", "claude-3-5-sonnet-20241022")
170
171 case "gemini":
172 b["api_key"] = s.secret(" API key")
173 b["model"] = s.ask(" Default model", "gemini-1.5-flash")
174
175 default:
176 b["api_key"] = s.secret(" API key")
177 b["model"] = s.ask(" Default model", = s.ask(" Default model", defaultModelFor(backendType))
178 }
179
180 if s.confirm(" Add model allow/block regex filters?", false) {
181 allow := s.ask(" Allow patterns (comma-separated regex)", "")
182 block := s.ask(" Block patterns (comma-separated regex)", "")
183 if allow != "" {
184 b["allow"] = splitComma(allow)
185 }
186 if block != "" {
187 b["block"] = splitComma(block)
188 }
189 }
190
191 if s.confirm(" Mark as default backend?", len([]map[string]any{b}) == 0) {
192 b["default"] = true
193 }
194
195 return b
196 }
197
198 func defaultModelFor(backend string) strackage main
199
200 import (
201 "bufio"
202 "
203 "fmt"
204 "ofmt"
205 "os"
206 "strcdentifier)", backendType+"-1")
207
208 me": name,
209 "backend": backendType,
210 }
211
212 switch backendType {
213 casse "bedrock":
214
215 b["region"] = s.ask(" AWS regionfirm(" Use static AWS crconfirm(" Use static AWS credent "",
216 "lmstudio": "",
217 "vllm
--- cmd/scuttlectl/internal/apiclient/apiclient.go
+++ cmd/scuttlectl/internal/apiclient/apiclient.go
@@ -5,10 +5,11 @@
55
"bytes"
66
"encoding/json"
77
"fmt"
88
"io"
99
"net/http"
10
+ "strings"
1011
)
1112
1213
// Client calls the scuttlebot REST API.
1314
type Client struct {
1415
base string
@@ -57,10 +58,90 @@
5758
5859
// RotateAgent sends POST /v1/agents/{nick}/rotate and returns raw JSON.
5960
func (c *Client) RotateAgent(nick string) (json.RawMessage, error) {
6061
return c.post("/v1/agents/"+nick+"/rotate", nil)
6162
}
63
+
64
+// DeleteAgent sends DELETE /v1/agents/{nick}.
65
+func (c *Client) DeleteAgent(nick string) error {
66
+ _, err := c.doNoBody("DELETE", "/v1/agents/"+nick)
67
+ return err
68
+}
69
+
70
+// ChannelUsers sends GET /v1/channels/{channel}/users and returns raw JSON.
71
+func (c *Client) ChannelUsers(channel string) (json.RawMessage, error) {
72
+ return c.get("/v1/channels/" + channel + "/users")
73
+}
74
+
75
+// DeleteChannel sends DELETE /v1/channels/{channel}.
76
+func (c *Client) DeleteChannel(channel string) error {
77
+ channel = strings.TrimPrefix(channel, "#")
78
+ _, err := c.doNoBody("DELETE", "/v1/channels/"+channel)
79
+ return err
80
+}
81
+
82
+// ListChannels sends GET /v1/channels and returns raw JSON.
83
+func (c *Client) ListChannels() (json.RawMessage, error) {
84
+ return c.get("/v1/channels")
85
+}
86
+
87
+// GetLLMBackend sends GET /v1/llm/backends and finds the named backend, returning raw JSON.
88
+func (c *Client) GetLLMBackend(name string) (json.RawMessage, error) {
89
+ raw, err := c.get("/v1/llm/backends")
90
+ if err != nil {
91
+ return nil, err
92
+ }
93
+ var resp struct {
94
+ Backends []json.RawMessage `json:"backends"`
95
+ }
96
+ if err := json.Unmarshal(raw, &resp); err != nil {
97
+ return nil, err
98
+ }
99
+ for _, b := range resp.Backends {
100
+ var named struct {
101
+ Name string `json:"name"`
102
+ }
103
+ if json.Unmarshal(b, &named) == nil && named.Name == name {
104
+ return b, nil
105
+ }
106
+ }
107
+ return nil, fmt.Errorf("backend %q not found", name)
108
+}
109
+
110
+// CreateLLMBackend sends POST /v1/llm/backends.
111
+func (c *Client) CreateLLMBackend(cfg map[string]any) error {
112
+ _, err := c.post("/v1/llm/backends", cfg)
113
+ return err
114
+}
115
+
116
+// DeleteLLMBackend sends DELETE /v1/llm/backends/{name}.
117
+func (c *Client) DeleteLLMBackend(name string) error {
118
+ _, err := c.doNoBody("DELETE", "/v1/llm/backends/"+name)
119
+ return err
120
+}
121
+
122
+// ListAdmins sends GET /v1/admins and returns raw JSON.
123
+func (c *Client) ListAdmins() (json.RawMessage, error) {
124
+ return c.get("/v1/admins")
125
+}
126
+
127
+// AddAdmin sends POST /v1/admins and returns raw JSON.
128
+func (c *Client) AddAdmin(username, password string) (json.RawMessage, error) {
129
+ return c.post("/v1/admins", map[string]string{"username": username, "password": password})
130
+}
131
+
132
+// RemoveAdmin sends DELETE /v1/admins/{username}.
133
+func (c *Client) RemoveAdmin(username string) error {
134
+ _, err := c.doNoBody("DELETE", "/v1/admins/"+username)
135
+ return err
136
+}
137
+
138
+// SetAdminPassword sends PUT /v1/admins/{username}/password.
139
+func (c *Client) SetAdminPassword(username, password string) error {
140
+ _, err := c.put("/v1/admins/"+username+"/password", map[string]string{"password": password})
141
+ return err
142
+}
62143
63144
func (c *Client) get(path string) (json.RawMessage, error) {
64145
return c.do("GET", path, nil)
65146
}
66147
@@ -71,10 +152,24 @@
71152
return nil, err
72153
}
73154
}
74155
return c.do("POST", path, &buf)
75156
}
157
+
158
+func (c *Client) put(path string, body any) (json.RawMessage, error) {
159
+ var buf bytes.Buffer
160
+ if body != nil {
161
+ if err := json.NewEncoder(&buf).Encode(body); err != nil {
162
+ return nil, err
163
+ }
164
+ }
165
+ return c.do("PUT", path, &buf)
166
+}
167
+
168
+func (c *Client) doNoBody(method, path string) (json.RawMessage, error) {
169
+ return c.do(method, path, nil)
170
+}
76171
77172
func (c *Client) do(method, path string, body io.Reader) (json.RawMessage, error) {
78173
req, err := http.NewRequest(method, c.base+path, body)
79174
if err != nil {
80175
return nil, err
81176
--- cmd/scuttlectl/internal/apiclient/apiclient.go
+++ cmd/scuttlectl/internal/apiclient/apiclient.go
@@ -5,10 +5,11 @@
5 "bytes"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
 
10 )
11
12 // Client calls the scuttlebot REST API.
13 type Client struct {
14 base string
@@ -57,10 +58,90 @@
57
58 // RotateAgent sends POST /v1/agents/{nick}/rotate and returns raw JSON.
59 func (c *Client) RotateAgent(nick string) (json.RawMessage, error) {
60 return c.post("/v1/agents/"+nick+"/rotate", nil)
61 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
63 func (c *Client) get(path string) (json.RawMessage, error) {
64 return c.do("GET", path, nil)
65 }
66
@@ -71,10 +152,24 @@
71 return nil, err
72 }
73 }
74 return c.do("POST", path, &buf)
75 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
77 func (c *Client) do(method, path string, body io.Reader) (json.RawMessage, error) {
78 req, err := http.NewRequest(method, c.base+path, body)
79 if err != nil {
80 return nil, err
81
--- cmd/scuttlectl/internal/apiclient/apiclient.go
+++ cmd/scuttlectl/internal/apiclient/apiclient.go
@@ -5,10 +5,11 @@
5 "bytes"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "strings"
11 )
12
13 // Client calls the scuttlebot REST API.
14 type Client struct {
15 base string
@@ -57,10 +58,90 @@
58
59 // RotateAgent sends POST /v1/agents/{nick}/rotate and returns raw JSON.
60 func (c *Client) RotateAgent(nick string) (json.RawMessage, error) {
61 return c.post("/v1/agents/"+nick+"/rotate", nil)
62 }
63
64 // DeleteAgent sends DELETE /v1/agents/{nick}.
65 func (c *Client) DeleteAgent(nick string) error {
66 _, err := c.doNoBody("DELETE", "/v1/agents/"+nick)
67 return err
68 }
69
70 // ChannelUsers sends GET /v1/channels/{channel}/users and returns raw JSON.
71 func (c *Client) ChannelUsers(channel string) (json.RawMessage, error) {
72 return c.get("/v1/channels/" + channel + "/users")
73 }
74
75 // DeleteChannel sends DELETE /v1/channels/{channel}.
76 func (c *Client) DeleteChannel(channel string) error {
77 channel = strings.TrimPrefix(channel, "#")
78 _, err := c.doNoBody("DELETE", "/v1/channels/"+channel)
79 return err
80 }
81
82 // ListChannels sends GET /v1/channels and returns raw JSON.
83 func (c *Client) ListChannels() (json.RawMessage, error) {
84 return c.get("/v1/channels")
85 }
86
87 // GetLLMBackend sends GET /v1/llm/backends and finds the named backend, returning raw JSON.
88 func (c *Client) GetLLMBackend(name string) (json.RawMessage, error) {
89 raw, err := c.get("/v1/llm/backends")
90 if err != nil {
91 return nil, err
92 }
93 var resp struct {
94 Backends []json.RawMessage `json:"backends"`
95 }
96 if err := json.Unmarshal(raw, &resp); err != nil {
97 return nil, err
98 }
99 for _, b := range resp.Backends {
100 var named struct {
101 Name string `json:"name"`
102 }
103 if json.Unmarshal(b, &named) == nil && named.Name == name {
104 return b, nil
105 }
106 }
107 return nil, fmt.Errorf("backend %q not found", name)
108 }
109
110 // CreateLLMBackend sends POST /v1/llm/backends.
111 func (c *Client) CreateLLMBackend(cfg map[string]any) error {
112 _, err := c.post("/v1/llm/backends", cfg)
113 return err
114 }
115
116 // DeleteLLMBackend sends DELETE /v1/llm/backends/{name}.
117 func (c *Client) DeleteLLMBackend(name string) error {
118 _, err := c.doNoBody("DELETE", "/v1/llm/backends/"+name)
119 return err
120 }
121
122 // ListAdmins sends GET /v1/admins and returns raw JSON.
123 func (c *Client) ListAdmins() (json.RawMessage, error) {
124 return c.get("/v1/admins")
125 }
126
127 // AddAdmin sends POST /v1/admins and returns raw JSON.
128 func (c *Client) AddAdmin(username, password string) (json.RawMessage, error) {
129 return c.post("/v1/admins", map[string]string{"username": username, "password": password})
130 }
131
132 // RemoveAdmin sends DELETE /v1/admins/{username}.
133 func (c *Client) RemoveAdmin(username string) error {
134 _, err := c.doNoBody("DELETE", "/v1/admins/"+username)
135 return err
136 }
137
138 // SetAdminPassword sends PUT /v1/admins/{username}/password.
139 func (c *Client) SetAdminPassword(username, password string) error {
140 _, err := c.put("/v1/admins/"+username+"/password", map[string]string{"password": password})
141 return err
142 }
143
144 func (c *Client) get(path string) (json.RawMessage, error) {
145 return c.do("GET", path, nil)
146 }
147
@@ -71,10 +152,24 @@
152 return nil, err
153 }
154 }
155 return c.do("POST", path, &buf)
156 }
157
158 func (c *Client) put(path string, body any) (json.RawMessage, error) {
159 var buf bytes.Buffer
160 if body != nil {
161 if err := json.NewEncoder(&buf).Encode(body); err != nil {
162 return nil, err
163 }
164 }
165 return c.do("PUT", path, &buf)
166 }
167
168 func (c *Client) doNoBody(method, path string) (json.RawMessage, error) {
169 return c.do(method, path, nil)
170 }
171
172 func (c *Client) do(method, path string, body io.Reader) (json.RawMessage, error) {
173 req, err := http.NewRequest(method, c.base+path, body)
174 if err != nil {
175 return nil, err
176
--- cmd/scuttlectl/main.go
+++ cmd/scuttlectl/main.go
@@ -40,10 +40,20 @@
4040
args := flag.Args()
4141
if len(args) == 0 {
4242
usage()
4343
os.Exit(1)
4444
}
45
+
46
+ switch args[0] {
47
+ case "setup":
48
+ cfgPath := "scuttlebot.yaml"
49
+ if len(args) > 1 {
50
+ cfgPath = args[1]
51
+ }
52
+ cmdSetup(cfgPath)
53
+ return
54
+ }
4555
4656
if *tokenFlag == "" {
4757
fmt.Fprintln(os.Stderr, "error: API token required (set SCUTTLEBOT_TOKEN or use --token)")
4858
os.Exit(1)
4959
}
@@ -68,24 +78,72 @@
6878
requireArgs(args, 3, "scuttlectl agent register <nick> [--type worker] [--channels #a,#b]")
6979
cmdAgentRegister(api, args[2:], *jsonFlag)
7080
case "revoke":
7181
requireArgs(args, 3, "scuttlectl agent revoke <nick>")
7282
cmdAgentRevoke(api, args[2])
83
+ case "delete":
84
+ requireArgs(args, 3, "scuttlectl agent delete <nick>")
85
+ cmdAgentDelete(api, args[2])
7386
case "rotate":
7487
requireArgs(args, 3, "scuttlectl agent rotate <nick>")
7588
cmdAgentRotate(api, args[2], *jsonFlag)
7689
default:
7790
fmt.Fprintf(os.Stderr, "unknown subcommand: %s\n", args[1])
7891
os.Exit(1)
7992
}
80
- case "channels":
81
- if len(args) < 2 || args[1] == "list" {
82
- fmt.Fprintln(os.Stderr, "channels list: not yet implemented (requires #12 discovery)")
93
+ case "admin":
94
+ if len(args) < 2 {
95
+ fmt.Fprintf(os.Stderr, "usage: scuttlectl admin <subcommand>\n")
96
+ os.Exit(1)
97
+ }
98
+ switch args[1] {
99
+ case "list":
100
+ cmdAdminList(api, *jsonFlag)
101
+ case "add":
102
+ requireArgs(args, 3, "scuttlectl admin add <username>")
103
+ cmdAdminAdd(api, args[2])
104
+ case "remove":
105
+ requireArgs(args, 3, "scuttlectl admin remove <username>")
106
+ cmdAdminRemove(api, args[2])
107
+ case "passwd":
108
+ requireArgs(args, 3, "scuttlectl admin passwd <username>")
109
+ cmdAdminPasswd(api, args[2])
110
+ default:
111
+ fmt.Fprintf(os.Stderr, "unknown subcommand: admin %s\n", args[1])
112
+ os.Exit(1)
113
+ }
114
+ case "channels", "channel":
115
+ if len(args) < 2 {
116
+ fmt.Fprintf(os.Stderr, "usage: scuttlectl channels <list|users <channel>>\n")
117
+ os.Exit(1)
118
+ }
119
+ switch args[1] {
120
+ case "list":
121
+ cmdChannelList(api, *jsonFlag)
122
+ case "users":
123
+ requireArgs(args, 3, "scuttlectl channels users <channel>")
124
+ cmdChannelUsers(api, args[2], *jsonFlag)
125
+ case "delete", "rm":
126
+ requireArgs(args, 3, "scuttlectl channels delete <channel>")
127
+ cmdChannelDelete(api, args[2])
128
+ default:
129
+ fmt.Fprintf(os.Stderr, "unknown subcommand: channels %s\n", args[1])
130
+ os.Exit(1)
131
+ }
132
+ case "backend", "backends":
133
+ if len(args) < 2 {
134
+ fmt.Fprintf(os.Stderr, "usage: scuttlectl backend rename <old-name> <new-name>\n")
83135
os.Exit(1)
84136
}
85
- fmt.Fprintf(os.Stderr, "unknown subcommand: channels %s\n", args[1])
86
- os.Exit(1)
137
+ switch args[1] {
138
+ case "rename":
139
+ requireArgs(args, 4, "scuttlectl backend rename <old-name> <new-name>")
140
+ cmdBackendRename(api, args[2], args[3])
141
+ default:
142
+ fmt.Fprintf(os.Stderr, "unknown subcommand: backend %s\n", args[1])
143
+ os.Exit(1)
144
+ }
87145
case "logs":
88146
fmt.Fprintln(os.Stderr, "logs tail: not yet implemented (requires scribe HTTP endpoint)")
89147
os.Exit(1)
90148
default:
91149
fmt.Fprintf(os.Stderr, "unknown command: %s\n", args[0])
@@ -227,15 +285,132 @@
227285
fmt.Fprintf(tw, "password\t%s\n", body.Credentials.Password)
228286
fmt.Fprintf(tw, "server\t%s\n", body.Credentials.Server)
229287
tw.Flush()
230288
fmt.Println("\nStore these credentials — the password will not be shown again.")
231289
}
290
+
291
+func cmdAdminList(api *apiclient.Client, asJSON bool) {
292
+ raw, err := api.ListAdmins()
293
+ die(err)
294
+ if asJSON {
295
+ printJSON(raw)
296
+ return
297
+ }
298
+
299
+ var body struct {
300
+ Admins []struct {
301
+ Username string `json:"username"`
302
+ Created string `json:"created"`
303
+ } `json:"admins"`
304
+ }
305
+ must(json.Unmarshal(raw, &body))
306
+
307
+ if len(body.Admins) == 0 {
308
+ fmt.Println("no admin accounts")
309
+ return
310
+ }
311
+
312
+ tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
313
+ fmt.Fprintln(tw, "USERNAME\tCREATED")
314
+ for _, a := range body.Admins {
315
+ fmt.Fprintf(tw, "%s\t%s\n", a.Username, a.Created)
316
+ }
317
+ tw.Flush()
318
+}
319
+
320
+func cmdAdminAdd(api *apiclient.Client, username string) {
321
+ pass := promptPassword()
322
+ _, err := api.AddAdmin(username, pass)
323
+ die(err)
324
+ fmt.Printf("Admin added: %s\n", username)
325
+}
326
+
327
+func cmdAdminRemove(api *apiclient.Client, username string) {
328
+ die(api.RemoveAdmin(username))
329
+ fmt.Printf("Admin removed: %s\n", username)
330
+}
331
+
332
+func cmdAdminPasswd(api *apiclient.Client, username string) {
333
+ pass := promptPassword()
334
+ die(api.SetAdminPassword(username, pass))
335
+ fmt.Printf("Password updated for: %s\n", username)
336
+}
337
+
338
+func promptPassword() string {
339
+ fmt.Fprint(os.Stderr, "password: ")
340
+ var pass string
341
+ fmt.Scanln(&pass)
342
+ return pass
343
+}
232344
233345
func cmdAgentRevoke(api *apiclient.Client, nick string) {
234346
die(api.RevokeAgent(nick))
235347
fmt.Printf("Agent revoked: %s\n", nick)
236348
}
349
+
350
+func cmdAgentDelete(api *apiclient.Client, nick string) {
351
+ die(api.DeleteAgent(nick))
352
+ fmt.Printf("Agent deleted: %s\n", nick)
353
+}
354
+
355
+func cmdChannelList(api *apiclient.Client, asJSON bool) {
356
+ raw, err := api.ListChannels()
357
+ die(err)
358
+ if asJSON {
359
+ printJSON(raw)
360
+ return
361
+ }
362
+ var body struct {
363
+ Channels []string `json:"channels"`
364
+ }
365
+ must(json.Unmarshal(raw, &body))
366
+ if len(body.Channels) == 0 {
367
+ fmt.Println("no channels")
368
+ return
369
+ }
370
+ for _, ch := range body.Channels {
371
+ fmt.Println(ch)
372
+ }
373
+}
374
+
375
+func cmdChannelUsers(api *apiclient.Client, channel string, asJSON bool) {
376
+ raw, err := api.ChannelUsers(channel)
377
+ die(err)
378
+ if asJSON {
379
+ printJSON(raw)
380
+ return
381
+ }
382
+ var body struct {
383
+ Users []string `json:"users"`
384
+ }
385
+ must(json.Unmarshal(raw, &body))
386
+ if len(body.Users) == 0 {
387
+ fmt.Printf("no users in %s\n", channel)
388
+ return
389
+ }
390
+ for _, u := range body.Users {
391
+ fmt.Println(u)
392
+ }
393
+}
394
+
395
+func cmdChannelDelete(api *apiclient.Client, channel string) {
396
+ die(api.DeleteChannel(channel))
397
+ fmt.Printf("Channel deleted: #%s\n", strings.TrimPrefix(channel, "#"))
398
+}
399
+
400
+func cmdBackendRename(api *apiclient.Client, oldName, newName string) {
401
+ raw, err := api.GetLLMBackend(oldName)
402
+ die(err)
403
+
404
+ var cfg map[string]any
405
+ must(json.Unmarshal(raw, &cfg))
406
+ cfg["name"] = newName
407
+
408
+ die(api.CreateLLMBackend(cfg))
409
+ die(api.DeleteLLMBackend(oldName))
410
+ fmt.Printf("Backend renamed: %s → %s\n", oldName, newName)
411
+}
237412
238413
func cmdAgentRotate(api *apiclient.Client, nick string, asJSON bool) {
239414
raw, err := api.RotateAgent(nick)
240415
die(err)
241416
if asJSON {
@@ -271,20 +446,29 @@
271446
--token API bearer token (default: $SCUTTLEBOT_TOKEN)
272447
--json output raw JSON
273448
--version print version and exit
274449
275450
Commands:
451
+ setup [path] interactive wizard — write scuttlebot.yaml (no token needed)
276452
status daemon + ergo health
277453
agents list list all registered agents
278454
agent get <nick> get a single agent
279455
agent register <nick> register a new agent, print credentials
280456
[--type worker|orchestrator|observer]
281457
[--channels #a,#b,#c]
282458
agent revoke <nick> revoke agent credentials
459
+ agent delete <nick> permanently remove agent from registry
283460
agent rotate <nick> rotate agent password
284
- channels list list provisioned channels (requires #12)
461
+ channels list list active channels
462
+ channels users <channel> list users in a channel
463
+ channels delete <channel> part bridge from channel (closes when empty)
464
+ backend rename <old> <new> rename an LLM backend
285465
logs tail tail scribe log (coming soon)
466
+ admin list list admin accounts
467
+ admin add <username> add admin (prompts for password)
468
+ admin remove <username> remove admin
469
+ admin passwd <username> change admin password (prompts)
286470
`, version)
287471
}
288472
289473
func printJSON(raw json.RawMessage) {
290474
var buf []byte
291475
--- cmd/scuttlectl/main.go
+++ cmd/scuttlectl/main.go
@@ -40,10 +40,20 @@
40 args := flag.Args()
41 if len(args) == 0 {
42 usage()
43 os.Exit(1)
44 }
 
 
 
 
 
 
 
 
 
 
45
46 if *tokenFlag == "" {
47 fmt.Fprintln(os.Stderr, "error: API token required (set SCUTTLEBOT_TOKEN or use --token)")
48 os.Exit(1)
49 }
@@ -68,24 +78,72 @@
68 requireArgs(args, 3, "scuttlectl agent register <nick> [--type worker] [--channels #a,#b]")
69 cmdAgentRegister(api, args[2:], *jsonFlag)
70 case "revoke":
71 requireArgs(args, 3, "scuttlectl agent revoke <nick>")
72 cmdAgentRevoke(api, args[2])
 
 
 
73 case "rotate":
74 requireArgs(args, 3, "scuttlectl agent rotate <nick>")
75 cmdAgentRotate(api, args[2], *jsonFlag)
76 default:
77 fmt.Fprintf(os.Stderr, "unknown subcommand: %s\n", args[1])
78 os.Exit(1)
79 }
80 case "channels":
81 if len(args) < 2 || args[1] == "list" {
82 fmt.Fprintln(os.Stderr, "channels list: not yet implemented (requires #12 discovery)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83 os.Exit(1)
84 }
85 fmt.Fprintf(os.Stderr, "unknown subcommand: channels %s\n", args[1])
86 os.Exit(1)
 
 
 
 
 
 
87 case "logs":
88 fmt.Fprintln(os.Stderr, "logs tail: not yet implemented (requires scribe HTTP endpoint)")
89 os.Exit(1)
90 default:
91 fmt.Fprintf(os.Stderr, "unknown command: %s\n", args[0])
@@ -227,15 +285,132 @@
227 fmt.Fprintf(tw, "password\t%s\n", body.Credentials.Password)
228 fmt.Fprintf(tw, "server\t%s\n", body.Credentials.Server)
229 tw.Flush()
230 fmt.Println("\nStore these credentials — the password will not be shown again.")
231 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
233 func cmdAgentRevoke(api *apiclient.Client, nick string) {
234 die(api.RevokeAgent(nick))
235 fmt.Printf("Agent revoked: %s\n", nick)
236 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
238 func cmdAgentRotate(api *apiclient.Client, nick string, asJSON bool) {
239 raw, err := api.RotateAgent(nick)
240 die(err)
241 if asJSON {
@@ -271,20 +446,29 @@
271 --token API bearer token (default: $SCUTTLEBOT_TOKEN)
272 --json output raw JSON
273 --version print version and exit
274
275 Commands:
 
276 status daemon + ergo health
277 agents list list all registered agents
278 agent get <nick> get a single agent
279 agent register <nick> register a new agent, print credentials
280 [--type worker|orchestrator|observer]
281 [--channels #a,#b,#c]
282 agent revoke <nick> revoke agent credentials
 
283 agent rotate <nick> rotate agent password
284 channels list list provisioned channels (requires #12)
 
 
 
285 logs tail tail scribe log (coming soon)
 
 
 
 
286 `, version)
287 }
288
289 func printJSON(raw json.RawMessage) {
290 var buf []byte
291
--- cmd/scuttlectl/main.go
+++ cmd/scuttlectl/main.go
@@ -40,10 +40,20 @@
40 args := flag.Args()
41 if len(args) == 0 {
42 usage()
43 os.Exit(1)
44 }
45
46 switch args[0] {
47 case "setup":
48 cfgPath := "scuttlebot.yaml"
49 if len(args) > 1 {
50 cfgPath = args[1]
51 }
52 cmdSetup(cfgPath)
53 return
54 }
55
56 if *tokenFlag == "" {
57 fmt.Fprintln(os.Stderr, "error: API token required (set SCUTTLEBOT_TOKEN or use --token)")
58 os.Exit(1)
59 }
@@ -68,24 +78,72 @@
78 requireArgs(args, 3, "scuttlectl agent register <nick> [--type worker] [--channels #a,#b]")
79 cmdAgentRegister(api, args[2:], *jsonFlag)
80 case "revoke":
81 requireArgs(args, 3, "scuttlectl agent revoke <nick>")
82 cmdAgentRevoke(api, args[2])
83 case "delete":
84 requireArgs(args, 3, "scuttlectl agent delete <nick>")
85 cmdAgentDelete(api, args[2])
86 case "rotate":
87 requireArgs(args, 3, "scuttlectl agent rotate <nick>")
88 cmdAgentRotate(api, args[2], *jsonFlag)
89 default:
90 fmt.Fprintf(os.Stderr, "unknown subcommand: %s\n", args[1])
91 os.Exit(1)
92 }
93 case "admin":
94 if len(args) < 2 {
95 fmt.Fprintf(os.Stderr, "usage: scuttlectl admin <subcommand>\n")
96 os.Exit(1)
97 }
98 switch args[1] {
99 case "list":
100 cmdAdminList(api, *jsonFlag)
101 case "add":
102 requireArgs(args, 3, "scuttlectl admin add <username>")
103 cmdAdminAdd(api, args[2])
104 case "remove":
105 requireArgs(args, 3, "scuttlectl admin remove <username>")
106 cmdAdminRemove(api, args[2])
107 case "passwd":
108 requireArgs(args, 3, "scuttlectl admin passwd <username>")
109 cmdAdminPasswd(api, args[2])
110 default:
111 fmt.Fprintf(os.Stderr, "unknown subcommand: admin %s\n", args[1])
112 os.Exit(1)
113 }
114 case "channels", "channel":
115 if len(args) < 2 {
116 fmt.Fprintf(os.Stderr, "usage: scuttlectl channels <list|users <channel>>\n")
117 os.Exit(1)
118 }
119 switch args[1] {
120 case "list":
121 cmdChannelList(api, *jsonFlag)
122 case "users":
123 requireArgs(args, 3, "scuttlectl channels users <channel>")
124 cmdChannelUsers(api, args[2], *jsonFlag)
125 case "delete", "rm":
126 requireArgs(args, 3, "scuttlectl channels delete <channel>")
127 cmdChannelDelete(api, args[2])
128 default:
129 fmt.Fprintf(os.Stderr, "unknown subcommand: channels %s\n", args[1])
130 os.Exit(1)
131 }
132 case "backend", "backends":
133 if len(args) < 2 {
134 fmt.Fprintf(os.Stderr, "usage: scuttlectl backend rename <old-name> <new-name>\n")
135 os.Exit(1)
136 }
137 switch args[1] {
138 case "rename":
139 requireArgs(args, 4, "scuttlectl backend rename <old-name> <new-name>")
140 cmdBackendRename(api, args[2], args[3])
141 default:
142 fmt.Fprintf(os.Stderr, "unknown subcommand: backend %s\n", args[1])
143 os.Exit(1)
144 }
145 case "logs":
146 fmt.Fprintln(os.Stderr, "logs tail: not yet implemented (requires scribe HTTP endpoint)")
147 os.Exit(1)
148 default:
149 fmt.Fprintf(os.Stderr, "unknown command: %s\n", args[0])
@@ -227,15 +285,132 @@
285 fmt.Fprintf(tw, "password\t%s\n", body.Credentials.Password)
286 fmt.Fprintf(tw, "server\t%s\n", body.Credentials.Server)
287 tw.Flush()
288 fmt.Println("\nStore these credentials — the password will not be shown again.")
289 }
290
291 func cmdAdminList(api *apiclient.Client, asJSON bool) {
292 raw, err := api.ListAdmins()
293 die(err)
294 if asJSON {
295 printJSON(raw)
296 return
297 }
298
299 var body struct {
300 Admins []struct {
301 Username string `json:"username"`
302 Created string `json:"created"`
303 } `json:"admins"`
304 }
305 must(json.Unmarshal(raw, &body))
306
307 if len(body.Admins) == 0 {
308 fmt.Println("no admin accounts")
309 return
310 }
311
312 tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
313 fmt.Fprintln(tw, "USERNAME\tCREATED")
314 for _, a := range body.Admins {
315 fmt.Fprintf(tw, "%s\t%s\n", a.Username, a.Created)
316 }
317 tw.Flush()
318 }
319
320 func cmdAdminAdd(api *apiclient.Client, username string) {
321 pass := promptPassword()
322 _, err := api.AddAdmin(username, pass)
323 die(err)
324 fmt.Printf("Admin added: %s\n", username)
325 }
326
327 func cmdAdminRemove(api *apiclient.Client, username string) {
328 die(api.RemoveAdmin(username))
329 fmt.Printf("Admin removed: %s\n", username)
330 }
331
332 func cmdAdminPasswd(api *apiclient.Client, username string) {
333 pass := promptPassword()
334 die(api.SetAdminPassword(username, pass))
335 fmt.Printf("Password updated for: %s\n", username)
336 }
337
338 func promptPassword() string {
339 fmt.Fprint(os.Stderr, "password: ")
340 var pass string
341 fmt.Scanln(&pass)
342 return pass
343 }
344
345 func cmdAgentRevoke(api *apiclient.Client, nick string) {
346 die(api.RevokeAgent(nick))
347 fmt.Printf("Agent revoked: %s\n", nick)
348 }
349
350 func cmdAgentDelete(api *apiclient.Client, nick string) {
351 die(api.DeleteAgent(nick))
352 fmt.Printf("Agent deleted: %s\n", nick)
353 }
354
355 func cmdChannelList(api *apiclient.Client, asJSON bool) {
356 raw, err := api.ListChannels()
357 die(err)
358 if asJSON {
359 printJSON(raw)
360 return
361 }
362 var body struct {
363 Channels []string `json:"channels"`
364 }
365 must(json.Unmarshal(raw, &body))
366 if len(body.Channels) == 0 {
367 fmt.Println("no channels")
368 return
369 }
370 for _, ch := range body.Channels {
371 fmt.Println(ch)
372 }
373 }
374
375 func cmdChannelUsers(api *apiclient.Client, channel string, asJSON bool) {
376 raw, err := api.ChannelUsers(channel)
377 die(err)
378 if asJSON {
379 printJSON(raw)
380 return
381 }
382 var body struct {
383 Users []string `json:"users"`
384 }
385 must(json.Unmarshal(raw, &body))
386 if len(body.Users) == 0 {
387 fmt.Printf("no users in %s\n", channel)
388 return
389 }
390 for _, u := range body.Users {
391 fmt.Println(u)
392 }
393 }
394
395 func cmdChannelDelete(api *apiclient.Client, channel string) {
396 die(api.DeleteChannel(channel))
397 fmt.Printf("Channel deleted: #%s\n", strings.TrimPrefix(channel, "#"))
398 }
399
400 func cmdBackendRename(api *apiclient.Client, oldName, newName string) {
401 raw, err := api.GetLLMBackend(oldName)
402 die(err)
403
404 var cfg map[string]any
405 must(json.Unmarshal(raw, &cfg))
406 cfg["name"] = newName
407
408 die(api.CreateLLMBackend(cfg))
409 die(api.DeleteLLMBackend(oldName))
410 fmt.Printf("Backend renamed: %s → %s\n", oldName, newName)
411 }
412
413 func cmdAgentRotate(api *apiclient.Client, nick string, asJSON bool) {
414 raw, err := api.RotateAgent(nick)
415 die(err)
416 if asJSON {
@@ -271,20 +446,29 @@
446 --token API bearer token (default: $SCUTTLEBOT_TOKEN)
447 --json output raw JSON
448 --version print version and exit
449
450 Commands:
451 setup [path] interactive wizard — write scuttlebot.yaml (no token needed)
452 status daemon + ergo health
453 agents list list all registered agents
454 agent get <nick> get a single agent
455 agent register <nick> register a new agent, print credentials
456 [--type worker|orchestrator|observer]
457 [--channels #a,#b,#c]
458 agent revoke <nick> revoke agent credentials
459 agent delete <nick> permanently remove agent from registry
460 agent rotate <nick> rotate agent password
461 channels list list active channels
462 channels users <channel> list users in a channel
463 channels delete <channel> part bridge from channel (closes when empty)
464 backend rename <old> <new> rename an LLM backend
465 logs tail tail scribe log (coming soon)
466 admin list list admin accounts
467 admin add <username> add admin (prompts for password)
468 admin remove <username> remove admin
469 admin passwd <username> change admin password (prompts)
470 `, version)
471 }
472
473 func printJSON(raw json.RawMessage) {
474 var buf []byte
475
M go.mod
+9 -1
--- go.mod
+++ go.mod
@@ -4,6 +4,14 @@
44
55
require github.com/oklog/ulid/v2 v2.1.1
66
77
require github.com/lrstanley/girc v1.1.1
88
9
-require gopkg.in/yaml.v3 v3.0.1 // indirect
9
+require (
10
+ github.com/creack/pty v1.1.24 // indirect
11
+ golang.org/x/crypto v0.39.0 // indirect
12
+ golang.org/x/net v0.41.0 // indirect
13
+ golang.org/x/sys v0.33.0 // indirect
14
+ golang.org/x/term v0.32.0 // indirect
15
+ golang.org/x/text v0.35.0 // indirect
16
+ gopkg.in/yaml.v3 v3.0.1 // indirect
17
+)
1018
--- go.mod
+++ go.mod
@@ -4,6 +4,14 @@
4
5 require github.com/oklog/ulid/v2 v2.1.1
6
7 require github.com/lrstanley/girc v1.1.1
8
9 require gopkg.in/yaml.v3 v3.0.1 // indirect
 
 
 
 
 
 
 
 
10
--- go.mod
+++ go.mod
@@ -4,6 +4,14 @@
4
5 require github.com/oklog/ulid/v2 v2.1.1
6
7 require github.com/lrstanley/girc v1.1.1
8
9 require (
10 github.com/creack/pty v1.1.24 // indirect
11 golang.org/x/crypto v0.39.0 // indirect
12 golang.org/x/net v0.41.0 // indirect
13 golang.org/x/sys v0.33.0 // indirect
14 golang.org/x/term v0.32.0 // indirect
15 golang.org/x/text v0.35.0 // indirect
16 gopkg.in/yaml.v3 v3.0.1 // indirect
17 )
18
M go.sum
+16
--- go.sum
+++ go.sum
@@ -1,8 +1,24 @@
1
+github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
2
+github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
13
github.com/lrstanley/girc v1.1.1 h1:0Y8a2tqQGDeFXfBQkAYOu5DbWqlydCJsi+4N+td4azk=
24
github.com/lrstanley/girc v1.1.1/go.mod h1:lgrnhcF8bg/Bd5HA5DOb4Z+uGqUqGnp4skr+J2GwVgI=
35
github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s=
46
github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=
57
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
8
+golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
9
+golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
10
+golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
11
+golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
12
+golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
13
+golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
14
+golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
15
+golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
16
+golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
17
+golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
18
+golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
19
+golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
20
+golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
21
+golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
622
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
723
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
824
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
925
--- go.sum
+++ go.sum
@@ -1,8 +1,24 @@
 
 
1 github.com/lrstanley/girc v1.1.1 h1:0Y8a2tqQGDeFXfBQkAYOu5DbWqlydCJsi+4N+td4azk=
2 github.com/lrstanley/girc v1.1.1/go.mod h1:lgrnhcF8bg/Bd5HA5DOb4Z+uGqUqGnp4skr+J2GwVgI=
3 github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s=
4 github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=
5 github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
7 gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
8 gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
9
--- go.sum
+++ go.sum
@@ -1,8 +1,24 @@
1 github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
2 github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
3 github.com/lrstanley/girc v1.1.1 h1:0Y8a2tqQGDeFXfBQkAYOu5DbWqlydCJsi+4N+td4azk=
4 github.com/lrstanley/girc v1.1.1/go.mod h1:lgrnhcF8bg/Bd5HA5DOb4Z+uGqUqGnp4skr+J2GwVgI=
5 github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s=
6 github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=
7 github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
8 golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
9 golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
10 golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
11 golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
12 golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
13 golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
14 golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
15 golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
16 golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
17 golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
18 golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
19 golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
20 golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
21 golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
22 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
23 gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
24 gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
25
--- internal/api/agents.go
+++ internal/api/agents.go
@@ -60,10 +60,41 @@
6060
writeJSON(w, http.StatusCreated, registerResponse{
6161
Credentials: creds,
6262
Payload: payload,
6363
})
6464
}
65
+
66
+func (s *Server) handleAdopt(w http.ResponseWriter, r *http.Request) {
67
+ nick := r.PathValue("nick")
68
+ var req struct {
69
+ Type registry.AgentType `json:"type"`
70
+ Channels []string `json:"channels"`
71
+ Permissions []string `json:"permissions"`
72
+ }
73
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
74
+ writeError(w, http.StatusBadRequest, "invalid request body")
75
+ return
76
+ }
77
+ if req.Type == "" {
78
+ req.Type = registry.AgentTypeWorker
79
+ }
80
+ cfg := registry.EngagementConfig{
81
+ Channels: req.Channels,
82
+ Permissions: req.Permissions,
83
+ }
84
+ payload, err := s.registry.Adopt(nick, req.Type, cfg)
85
+ if err != nil {
86
+ if strings.Contains(err.Error(), "already registered") {
87
+ writeError(w, http.StatusConflict, err.Error())
88
+ return
89
+ }
90
+ s.log.Error("adopt agent", "nick", nick, "err", err)
91
+ writeError(w, http.StatusInternalServerError, "adopt failed")
92
+ return
93
+ }
94
+ writeJSON(w, http.StatusOK, map[string]any{"nick": nick, "payload": payload})
95
+}
6596
6697
func (s *Server) handleRotate(w http.ResponseWriter, r *http.Request) {
6798
nick := r.PathValue("nick")
6899
creds, err := s.registry.Rotate(nick)
69100
if err != nil {
@@ -86,10 +117,24 @@
86117
return
87118
}
88119
s.log.Error("revoke agent", "nick", nick, "err", err)
89120
writeError(w, http.StatusInternalServerError, "revocation failed")
90121
return
122
+ }
123
+ w.WriteHeader(http.StatusNoContent)
124
+}
125
+
126
+func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) {
127
+ nick := r.PathValue("nick")
128
+ if err := s.registry.Delete(nick); err != nil {
129
+ if strings.Contains(err.Error(), "not found") {
130
+ writeError(w, http.StatusNotFound, err.Error())
131
+ return
132
+ }
133
+ s.log.Error("delete agent", "nick", nick, "err", err)
134
+ writeError(w, http.StatusInternalServerError, "deletion failed")
135
+ return
91136
}
92137
w.WriteHeader(http.StatusNoContent)
93138
}
94139
95140
func (s *Server) handleListAgents(w http.ResponseWriter, r *http.Request) {
96141
--- internal/api/agents.go
+++ internal/api/agents.go
@@ -60,10 +60,41 @@
60 writeJSON(w, http.StatusCreated, registerResponse{
61 Credentials: creds,
62 Payload: payload,
63 })
64 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
66 func (s *Server) handleRotate(w http.ResponseWriter, r *http.Request) {
67 nick := r.PathValue("nick")
68 creds, err := s.registry.Rotate(nick)
69 if err != nil {
@@ -86,10 +117,24 @@
86 return
87 }
88 s.log.Error("revoke agent", "nick", nick, "err", err)
89 writeError(w, http.StatusInternalServerError, "revocation failed")
90 return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91 }
92 w.WriteHeader(http.StatusNoContent)
93 }
94
95 func (s *Server) handleListAgents(w http.ResponseWriter, r *http.Request) {
96
--- internal/api/agents.go
+++ internal/api/agents.go
@@ -60,10 +60,41 @@
60 writeJSON(w, http.StatusCreated, registerResponse{
61 Credentials: creds,
62 Payload: payload,
63 })
64 }
65
66 func (s *Server) handleAdopt(w http.ResponseWriter, r *http.Request) {
67 nick := r.PathValue("nick")
68 var req struct {
69 Type registry.AgentType `json:"type"`
70 Channels []string `json:"channels"`
71 Permissions []string `json:"permissions"`
72 }
73 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
74 writeError(w, http.StatusBadRequest, "invalid request body")
75 return
76 }
77 if req.Type == "" {
78 req.Type = registry.AgentTypeWorker
79 }
80 cfg := registry.EngagementConfig{
81 Channels: req.Channels,
82 Permissions: req.Permissions,
83 }
84 payload, err := s.registry.Adopt(nick, req.Type, cfg)
85 if err != nil {
86 if strings.Contains(err.Error(), "already registered") {
87 writeError(w, http.StatusConflict, err.Error())
88 return
89 }
90 s.log.Error("adopt agent", "nick", nick, "err", err)
91 writeError(w, http.StatusInternalServerError, "adopt failed")
92 return
93 }
94 writeJSON(w, http.StatusOK, map[string]any{"nick": nick, "payload": payload})
95 }
96
97 func (s *Server) handleRotate(w http.ResponseWriter, r *http.Request) {
98 nick := r.PathValue("nick")
99 creds, err := s.registry.Rotate(nick)
100 if err != nil {
@@ -86,10 +117,24 @@
117 return
118 }
119 s.log.Error("revoke agent", "nick", nick, "err", err)
120 writeError(w, http.StatusInternalServerError, "revocation failed")
121 return
122 }
123 w.WriteHeader(http.StatusNoContent)
124 }
125
126 func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) {
127 nick := r.PathValue("nick")
128 if err := s.registry.Delete(nick); err != nil {
129 if strings.Contains(err.Error(), "not found") {
130 writeError(w, http.StatusNotFound, err.Error())
131 return
132 }
133 s.log.Error("delete agent", "nick", nick, "err", err)
134 writeError(w, http.StatusInternalServerError, "deletion failed")
135 return
136 }
137 w.WriteHeader(http.StatusNoContent)
138 }
139
140 func (s *Server) handleListAgents(w http.ResponseWriter, r *http.Request) {
141
--- internal/api/api_test.go
+++ internal/api/api_test.go
@@ -50,11 +50,11 @@
5050
const testToken = "test-api-token-abc123"
5151
5252
func newTestServer(t *testing.T) *httptest.Server {
5353
t.Helper()
5454
reg := registry.New(newMock(), []byte("test-signing-key"))
55
- srv := api.New(reg, []string{testToken}, nil, testLog)
55
+ srv := api.New(reg, []string{testToken}, nil, nil, nil, nil, "", testLog)
5656
return httptest.NewServer(srv.Handler())
5757
}
5858
5959
func authHeader() http.Header {
6060
h := http.Header{}
6161
--- internal/api/api_test.go
+++ internal/api/api_test.go
@@ -50,11 +50,11 @@
50 const testToken = "test-api-token-abc123"
51
52 func newTestServer(t *testing.T) *httptest.Server {
53 t.Helper()
54 reg := registry.New(newMock(), []byte("test-signing-key"))
55 srv := api.New(reg, []string{testToken}, nil, testLog)
56 return httptest.NewServer(srv.Handler())
57 }
58
59 func authHeader() http.Header {
60 h := http.Header{}
61
--- internal/api/api_test.go
+++ internal/api/api_test.go
@@ -50,11 +50,11 @@
50 const testToken = "test-api-token-abc123"
51
52 func newTestServer(t *testing.T) *httptest.Server {
53 t.Helper()
54 reg := registry.New(newMock(), []byte("test-signing-key"))
55 srv := api.New(reg, []string{testToken}, nil, nil, nil, nil, "", testLog)
56 return httptest.NewServer(srv.Handler())
57 }
58
59 func authHeader() http.Header {
60 h := http.Header{}
61
--- internal/api/chat.go
+++ internal/api/chat.go
@@ -12,10 +12,11 @@
1212
1313
// chatBridge is the interface the API layer requires from the bridge bot.
1414
type chatBridge interface {
1515
Channels() []string
1616
JoinChannel(channel string)
17
+ LeaveChannel(channel string)
1718
Messages(channel string) []bridge.Message
1819
Subscribe(channel string) (<-chan bridge.Message, func())
1920
Send(ctx context.Context, channel, text, senderNick string) error
2021
Stats() bridge.Stats
2122
TouchUser(channel, nick string)
@@ -25,10 +26,16 @@
2526
func (s *Server) handleJoinChannel(w http.ResponseWriter, r *http.Request) {
2627
channel := "#" + r.PathValue("channel")
2728
s.bridge.JoinChannel(channel)
2829
w.WriteHeader(http.StatusNoContent)
2930
}
31
+
32
+func (s *Server) handleDeleteChannel(w http.ResponseWriter, r *http.Request) {
33
+ channel := "#" + r.PathValue("channel")
34
+ s.bridge.LeaveChannel(channel)
35
+ w.WriteHeader(http.StatusNoContent)
36
+}
3037
3138
func (s *Server) handleListChannels(w http.ResponseWriter, r *http.Request) {
3239
writeJSON(w, http.StatusOK, map[string]any{"channels": s.bridge.Channels()})
3340
}
3441
3542
--- internal/api/chat.go
+++ internal/api/chat.go
@@ -12,10 +12,11 @@
12
13 // chatBridge is the interface the API layer requires from the bridge bot.
14 type chatBridge interface {
15 Channels() []string
16 JoinChannel(channel string)
 
17 Messages(channel string) []bridge.Message
18 Subscribe(channel string) (<-chan bridge.Message, func())
19 Send(ctx context.Context, channel, text, senderNick string) error
20 Stats() bridge.Stats
21 TouchUser(channel, nick string)
@@ -25,10 +26,16 @@
25 func (s *Server) handleJoinChannel(w http.ResponseWriter, r *http.Request) {
26 channel := "#" + r.PathValue("channel")
27 s.bridge.JoinChannel(channel)
28 w.WriteHeader(http.StatusNoContent)
29 }
 
 
 
 
 
 
30
31 func (s *Server) handleListChannels(w http.ResponseWriter, r *http.Request) {
32 writeJSON(w, http.StatusOK, map[string]any{"channels": s.bridge.Channels()})
33 }
34
35
--- internal/api/chat.go
+++ internal/api/chat.go
@@ -12,10 +12,11 @@
12
13 // chatBridge is the interface the API layer requires from the bridge bot.
14 type chatBridge interface {
15 Channels() []string
16 JoinChannel(channel string)
17 LeaveChannel(channel string)
18 Messages(channel string) []bridge.Message
19 Subscribe(channel string) (<-chan bridge.Message, func())
20 Send(ctx context.Context, channel, text, senderNick string) error
21 Stats() bridge.Stats
22 TouchUser(channel, nick string)
@@ -25,10 +26,16 @@
26 func (s *Server) handleJoinChannel(w http.ResponseWriter, r *http.Request) {
27 channel := "#" + r.PathValue("channel")
28 s.bridge.JoinChannel(channel)
29 w.WriteHeader(http.StatusNoContent)
30 }
31
32 func (s *Server) handleDeleteChannel(w http.ResponseWriter, r *http.Request) {
33 channel := "#" + r.PathValue("channel")
34 s.bridge.LeaveChannel(channel)
35 w.WriteHeader(http.StatusNoContent)
36 }
37
38 func (s *Server) handleListChannels(w http.ResponseWriter, r *http.Request) {
39 writeJSON(w, http.StatusOK, map[string]any{"channels": s.bridge.Channels()})
40 }
41
42
--- internal/api/chat_test.go
+++ internal/api/chat_test.go
@@ -21,10 +21,11 @@
2121
}
2222
}
2323
2424
func (b *stubChatBridge) Channels() []string { return nil }
2525
func (b *stubChatBridge) JoinChannel(string) {}
26
+func (b *stubChatBridge) LeaveChannel(string) {}
2627
func (b *stubChatBridge) Messages(string) []bridge.Message { return nil }
2728
func (b *stubChatBridge) Subscribe(string) (<-chan bridge.Message, func()) {
2829
return make(chan bridge.Message), func() {}
2930
}
3031
func (b *stubChatBridge) Send(context.Context, string, string, string) error { return nil }
3132
3233
ADDED internal/api/llm_handlers.go
3334
ADDED internal/api/login.go
3435
ADDED internal/api/login_test.go
3536
ADDED internal/api/metrics.go
3637
ADDED internal/api/policies.go
3738
ADDED internal/api/policies_test.go
--- internal/api/chat_test.go
+++ internal/api/chat_test.go
@@ -21,10 +21,11 @@
21 }
22 }
23
24 func (b *stubChatBridge) Channels() []string { return nil }
25 func (b *stubChatBridge) JoinChannel(string) {}
 
26 func (b *stubChatBridge) Messages(string) []bridge.Message { return nil }
27 func (b *stubChatBridge) Subscribe(string) (<-chan bridge.Message, func()) {
28 return make(chan bridge.Message), func() {}
29 }
30 func (b *stubChatBridge) Send(context.Context, string, string, string) error { return nil }
31
32 DDED internal/api/llm_handlers.go
33 DDED internal/api/login.go
34 DDED internal/api/login_test.go
35 DDED internal/api/metrics.go
36 DDED internal/api/policies.go
37 DDED internal/api/policies_test.go
--- internal/api/chat_test.go
+++ internal/api/chat_test.go
@@ -21,10 +21,11 @@
21 }
22 }
23
24 func (b *stubChatBridge) Channels() []string { return nil }
25 func (b *stubChatBridge) JoinChannel(string) {}
26 func (b *stubChatBridge) LeaveChannel(string) {}
27 func (b *stubChatBridge) Messages(string) []bridge.Message { return nil }
28 func (b *stubChatBridge) Subscribe(string) (<-chan bridge.Message, func()) {
29 return make(chan bridge.Message), func() {}
30 }
31 func (b *stubChatBridge) Send(context.Context, string, string, string) error { return nil }
32
33 DDED internal/api/llm_handlers.go
34 DDED internal/api/login.go
35 DDED internal/api/login_test.go
36 DDED internal/api/metrics.go
37 DDED internal/api/policies.go
38 DDED internal/api/policies_test.go
--- a/internal/api/llm_handlers.go
+++ b/internal/api/llm_handlers.go
@@ -0,0 +1,331 @@
1
+package api
2
+
3
+import (
4
+ "encoding/json"
5
+ "net/http"
6
+ "sort"
7
+
8
+ "github.com/conflicthq/scuttlebot/internal/config"
9
+ "github.com/conflicthq/scuttlebot/internal/llm"
10
+)
11
+
12
+// backendView is the read-safe representation of a backend returned by the API.
13
+// API keys are replaced with "***" if set, so they are never exposed.
14
+type backendView struct {
15
+ Name string `json:"name"`
16
+ Backend string `json:"backend"`
17
+ APIKey string `json:"api_key,omitempty"` // "***" if set, "" if not
18
+ BaseURL string `json:"base_url,omitempty"`
19
+ Model string `json:"model,omitempty"`
20
+ Region string `json:"region,omitempty"`
21
+ AWSKeyID string `json:"aws_key_id,omitempty"` // "***" if set
22
+ Allow []string `json:"allow,omitempty"`
23
+ Block []string `json:"block,omitempty"`
24
+ Default bool `json:"default,omitempty"`
25
+ Source string `json:"source"` // "config" (yaml, read-only) or "policy" (ui-managed)
26
+}
27
+
28
+func mask(s string) string {
29
+ if s == "" {
30
+ return ""
31
+ }
32
+ return "***"
33
+}
34
+
35
+// handleLLMKnown returns the list of all known backend names.
36
+func (s *Server) handleLLMKnown(w http.ResponseWriter, _ *http.Request) {
37
+ type knownBackend struct {
38
+ Name string `json:"name"`
39
+ BaseURL string `json:"base_url,omitempty"`
40
+ Native bool `json:"native,omitempty"`
41
+ }
42
+
43
+ var backends []knownBackend
44
+ for name, url := range llm.KnownBackends {
45
+ backends = append(backends, knownBackend{Name: name, BaseURL: url})
46
+ }
47
+ backends = append(backends,
48
+ knownBackend{Name: "anthropic", Native: true},
49
+ knownBackend{Name: "gemini", Native: true},
50
+ knownBackend{Name: "bedrock", Native: true},
51
+ knownBackend{Name: "ollama", BaseURL: "http://localhost:11434", Native: true},
52
+ )
53
+ sort.Slice(backends, func(i, j int) bool {
54
+ return backends[i].Name < backends[j].Name
55
+ })
56
+ writeJSON(w, http.StatusOK, backends)
57
+}
58
+
59
+// handleLLMBackends lists all configured backends (YAML config + policy store).
60
+// API keys are masked.
61
+func (s *Server) handleLLMBackends(w http.ResponseWriter, _ *http.Request) {
62
+ var out []backendView
63
+
64
+ // YAML-configured backends (read-only).
65
+ if s.llmCfg != nil {
66
+ for _, b := range s.llmCfg.Backends {
67
+ out = append(out, backendView{
68
+ Name: b.Name,
69
+ Backend: b.Backend,
70
+ APIKey: mask(b.APIKey),
71
+ BaseURL: b.BaseURL,
72
+ Model: b.Model,
73
+ Region: b.Region,
74
+ AWSKeyID: mask(b.AWSKeyID),
75
+ Allow: b.Allow,
76
+ Block: b.Block,
77
+ Default: b.Default,
78
+ Source: "config",
79
+ })
80
+ }
81
+ }
82
+
83
+ // Policy-store backends (UI-managed, editable).
84
+ if s.policies != nil {
85
+ for _, b := range s.policies.Get().LLMBackends {
86
+ out = append(out, backendView{
87
+ Name: b.Name,
88
+ Backend: b.Backend,
89
+ APIKey: mask(b.APIKey),
90
+ BaseURL: b.BaseURL,
91
+ Model: b.Model,
92
+ Region: b.Region,
93
+ AWSKeyID: mask(b.AWSKeyID),
94
+ Allow: b.Allow,
95
+ Block: b.Block,
96
+ Default: b.Default,
97
+ Source: "policy",
98
+ })
99
+ }
100
+ }
101
+
102
+ if out == nil {
103
+ out = []backendView{}
104
+ }
105
+ writeJSON(w, http.StatusOK, out)
106
+}
107
+
108
+// handleLLMBackendCreate adds a new backend to the policy store.
109
+func (s *Server) handleLLMBackendCreate(w http.ResponseWriter, r *http.Request) {
110
+ if s.policies == nil {
111
+ http.Error(w, "policy store not available", http.StatusServiceUnavailable)
112
+ return
113
+ }
114
+ var b PolicyLLMBackend
115
+ if err := json.NewDecoder(r.Body).Decode(&b); err != nil {
116
+ http.Error(w, "invalid request body", http.StatusBadRequest)
117
+ return
118
+ }
119
+ if b.Name == "" || b.Backend == "" {
120
+ http.Error(w, "name and backend are required", http.StatusBadRequest)
121
+ return
122
+ }
123
+
124
+ p := s.policies.Get()
125
+ for _, existing := range p.LLMBackends {
126
+ if existing.Name == b.Name {
127
+ http.Error(w, "backend name already exists", http.StatusConflict)
128
+ return
129
+ }
130
+ }
131
+ // Also check YAML backends.
132
+ if s.llmCfg != nil {
133
+ for _, existing := range s.llmCfg.Backends {
134
+ if existing.Name == b.Name {
135
+ http.Error(w, "backend name already exists in config", http.StatusConflict)
136
+ return
137
+ }
138
+ }
139
+ }
140
+
141
+ p.LLMBackends = append(p.LLMBackends, b)
142
+ if err := s.policies.Set(p); err != nil {
143
+ http.Error(w, "failed to save", http.StatusInternalServerError)
144
+ return
145
+ }
146
+ writeJSON(w, http.StatusCreated, backendView{
147
+ Name: b.Name,
148
+ Backend: b.Backend,
149
+ APIKey: mask(b.APIKey),
150
+ BaseURL: b.BaseURL,
151
+ Model: b.Model,
152
+ Region: b.Region,
153
+ Allow: b.Allow,
154
+ Block: b.Block,
155
+ Default: b.Default,
156
+ Source: "policy",
157
+ })
158
+}
159
+
160
+// handleLLMBackendUpdate updates a policy-store backend by name.
161
+// Fields present in the request body override the stored value.
162
+// Send api_key / aws_secret_key as "" to leave the stored value unchanged
163
+// (the UI masks these and should omit them if unchanged).
164
+func (s *Server) handleLLMBackendUpdate(w http.ResponseWriter, r *http.Request) {
165
+ if s.policies == nil {
166
+ http.Error(w, "policy store not available", http.StatusServiceUnavailable)
167
+ return
168
+ }
169
+ name := r.PathValue("name")
170
+ var req PolicyLLMBackend
171
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
172
+ http.Error(w, "invalid request body", http.StatusBadRequest)
173
+ return
174
+ }
175
+
176
+ p := s.policies.Get()
177
+ idx := -1
178
+ for i, b := range p.LLMBackends {
179
+ if b.Name == name {
180
+ idx = i
181
+ break
182
+ }
183
+ }
184
+ if idx == -1 {
185
+ http.Error(w, "backend not found (only policy backends are editable)", http.StatusNotFound)
186
+ return
187
+ }
188
+
189
+ existing := p.LLMBackends[idx]
190
+ // Preserve stored secrets when the UI sends "***" or empty.
191
+ if req.APIKey == "" || req.APIKey == "***" {
192
+ req.APIKey = existing.APIKey
193
+ }
194
+ if req.AWSSecretKey == "" || req.AWSSecretKey == "***" {
195
+ req.AWSSecretKey = existing.AWSSecretKey
196
+ }
197
+ if req.AWSKeyID == "" || req.AWSKeyID == "***" {
198
+ req.AWSKeyID = existing.AWSKeyID
199
+ }
200
+ req.Name = name // name is immutable
201
+ p.LLMBackends[idx] = req
202
+
203
+ if err := s.policies.Set(p); err != nil {
204
+ http.Error(w, "failed to save", http.StatusInternalServerError)
205
+ return
206
+ }
207
+ writeJSON(w, http.StatusOK, backendView{
208
+ Name: req.Name,
209
+ Backend: req.Backend,
210
+ APIKey: mask(req.APIKey),
211
+ BaseURL: req.BaseURL,
212
+ Model: req.Model,
213
+ Region: req.Region,
214
+ Allow: req.Allow,
215
+ Block: req.Block,
216
+ Default: req.Default,
217
+ Source: "policy",
218
+ })
219
+}
220
+
221
+// handleLLMBackendDelete removes a policy-store backend by name.
222
+func (s *Server) handleLLMBackendDelete(w http.ResponseWriter, r *http.Request) {
223
+ if s.policies == nil {
224
+ http.Error(w, "policy store not available", http.StatusServiceUnavailable)
225
+ return
226
+ }
227
+ name := r.PathValue("name")
228
+ p := s.policies.Get()
229
+ idx := -1
230
+ for i, b := range p.LLMBackends {
231
+ if b.Name == name {
232
+ idx = i
233
+ break
234
+ }
235
+ }
236
+ if idx == -1 {
237
+ http.Error(w, "backend not found (only policy backends are deletable)", http.StatusNotFound)
238
+ return
239
+ }
240
+ p.LLMBackends = append(p.LLMBackends[:idx], p.LLMBackends[idx+1:]...)
241
+ if err := s.policies.Set(p); err != nil {
242
+ http.Error(w, "failed to save", http.StatusInternalServerError)
243
+ return
244
+ }
245
+ w.WriteHeader(http.StatusNoContent)
246
+}
247
+
248
+// handleLLMModels runs model discovery for the named backend.
249
+// Looks in YAML config first, then policy store.
250
+func (s *Server) handleLLMModels(w http.ResponseWriter, r *http.Request) {
251
+ name := r.PathValue("name")
252
+ cfg, ok := s.findBackendConfig(name)
253
+ if !ok {
254
+ http.Error(w, "backend not found", http.StatusNotFound)
255
+ return
256
+ }
257
+ models, err := llm.Discover(r.Context(), cfg)
258
+ if err != nil {
259
+ s.log.Error("llm model discovery", "backend", name, "err", err)
260
+ http.Error(w, "model discovery failed: "+err.Error(), http.StatusBadGateway)
261
+ return
262
+ }
263
+ writeJSON(w, http.StatusOK, models)
264
+}
265
+
266
+// handleLLMDiscover runs ad-hoc model discovery from form credentials.
267
+// Used by the UI "load live models" button before a backend is saved.
268
+func (s *Server) handleLLMDiscover(w http.ResponseWriter, r *http.Request) {
269
+ var req struct {
270
+ Backend string `json:"backend"`
271
+ APIKey string `json:"api_key"`
272
+ BaseURL string `json:"base_url"`
273
+ Model string `json:"model"`
274
+ Region string `json:"region"`
275
+ AWSKeyID string `json:"aws_key_id"`
276
+ AWSSecretKey string `json:"aws_secret_key"`
277
+ Allow []string `json:"allow"`
278
+ Block []string `json:"block"`
279
+ }
280
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
281
+ http.Error(w, "invalid request body", http.StatusBadRequest)
282
+ return
283
+ }
284
+ if req.Backend == "" {
285
+ http.Error(w, "backend is required", http.StatusBadRequest)
286
+ return
287
+ }
288
+ cfg := llm.BackendConfig{
289
+ Backend: req.Backend,
290
+ APIKey: req.APIKey,
291
+ BaseURL: req.BaseURL,
292
+ Model: req.Model,
293
+ Region: req.Region,
294
+ AWSKeyID: req.AWSKeyID,
295
+ AWSSecretKey: req.AWSSecretKey,
296
+ Allow: req.Allow,
297
+ Block: req.Block,
298
+ }
299
+ models, err := llm.Discover(r.Context(), cfg)
300
+ if err != nil {
301
+ s.log.Error("llm ad-hoc discovery", "backend", req.Backend, "err", err)
302
+ http.Error(w, "model discovery failed: "+err.Error(), http.StatusBadGateway)
303
+ return
304
+ }
305
+ writeJSON(w, http.StatusOK, models)
306
+}
307
+
308
+// findBackendConfig looks up a backend by name in YAML config then policy store.
309
+func (s *Server) findBackendConfig(name string) (llm.BackendConfig, bool) {
310
+ if s.llmCfg != nil {
311
+ for _, b := range s.llmCfg.Backends {
312
+ if b.Name == name {
313
+ return yamlBackendToLLM(b), true
314
+ }
315
+ }
316
+ }
317
+ if s.policies != nil {
318
+ for _, b := range s.policies.Get().LLMBackends {
319
+ if b.Name == name {
320
+ return policyBackendToLLM(b), true
321
+ }
322
+ }
323
+ }
324
+ return llm.BackendConfig{}, false
325
+}
326
+
327
+func yamlBackendToLLM(b config.LLMBackendConfig) llm.BackendConfig {
328
+ return llm.BackendConfig{
329
+ Backend: b.Backend,
330
+ APIKey: b.APIKey,
331
+ BaseURL:
--- a/internal/api/llm_handlers.go
+++ b/internal/api/llm_handlers.go
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/internal/api/llm_handlers.go
+++ b/internal/api/llm_handlers.go
@@ -0,0 +1,331 @@
1 package api
2
3 import (
4 "encoding/json"
5 "net/http"
6 "sort"
7
8 "github.com/conflicthq/scuttlebot/internal/config"
9 "github.com/conflicthq/scuttlebot/internal/llm"
10 )
11
12 // backendView is the read-safe representation of a backend returned by the API.
13 // API keys are replaced with "***" if set, so they are never exposed.
14 type backendView struct {
15 Name string `json:"name"`
16 Backend string `json:"backend"`
17 APIKey string `json:"api_key,omitempty"` // "***" if set, "" if not
18 BaseURL string `json:"base_url,omitempty"`
19 Model string `json:"model,omitempty"`
20 Region string `json:"region,omitempty"`
21 AWSKeyID string `json:"aws_key_id,omitempty"` // "***" if set
22 Allow []string `json:"allow,omitempty"`
23 Block []string `json:"block,omitempty"`
24 Default bool `json:"default,omitempty"`
25 Source string `json:"source"` // "config" (yaml, read-only) or "policy" (ui-managed)
26 }
27
28 func mask(s string) string {
29 if s == "" {
30 return ""
31 }
32 return "***"
33 }
34
35 // handleLLMKnown returns the list of all known backend names.
36 func (s *Server) handleLLMKnown(w http.ResponseWriter, _ *http.Request) {
37 type knownBackend struct {
38 Name string `json:"name"`
39 BaseURL string `json:"base_url,omitempty"`
40 Native bool `json:"native,omitempty"`
41 }
42
43 var backends []knownBackend
44 for name, url := range llm.KnownBackends {
45 backends = append(backends, knownBackend{Name: name, BaseURL: url})
46 }
47 backends = append(backends,
48 knownBackend{Name: "anthropic", Native: true},
49 knownBackend{Name: "gemini", Native: true},
50 knownBackend{Name: "bedrock", Native: true},
51 knownBackend{Name: "ollama", BaseURL: "http://localhost:11434", Native: true},
52 )
53 sort.Slice(backends, func(i, j int) bool {
54 return backends[i].Name < backends[j].Name
55 })
56 writeJSON(w, http.StatusOK, backends)
57 }
58
59 // handleLLMBackends lists all configured backends (YAML config + policy store).
60 // API keys are masked.
61 func (s *Server) handleLLMBackends(w http.ResponseWriter, _ *http.Request) {
62 var out []backendView
63
64 // YAML-configured backends (read-only).
65 if s.llmCfg != nil {
66 for _, b := range s.llmCfg.Backends {
67 out = append(out, backendView{
68 Name: b.Name,
69 Backend: b.Backend,
70 APIKey: mask(b.APIKey),
71 BaseURL: b.BaseURL,
72 Model: b.Model,
73 Region: b.Region,
74 AWSKeyID: mask(b.AWSKeyID),
75 Allow: b.Allow,
76 Block: b.Block,
77 Default: b.Default,
78 Source: "config",
79 })
80 }
81 }
82
83 // Policy-store backends (UI-managed, editable).
84 if s.policies != nil {
85 for _, b := range s.policies.Get().LLMBackends {
86 out = append(out, backendView{
87 Name: b.Name,
88 Backend: b.Backend,
89 APIKey: mask(b.APIKey),
90 BaseURL: b.BaseURL,
91 Model: b.Model,
92 Region: b.Region,
93 AWSKeyID: mask(b.AWSKeyID),
94 Allow: b.Allow,
95 Block: b.Block,
96 Default: b.Default,
97 Source: "policy",
98 })
99 }
100 }
101
102 if out == nil {
103 out = []backendView{}
104 }
105 writeJSON(w, http.StatusOK, out)
106 }
107
108 // handleLLMBackendCreate adds a new backend to the policy store.
109 func (s *Server) handleLLMBackendCreate(w http.ResponseWriter, r *http.Request) {
110 if s.policies == nil {
111 http.Error(w, "policy store not available", http.StatusServiceUnavailable)
112 return
113 }
114 var b PolicyLLMBackend
115 if err := json.NewDecoder(r.Body).Decode(&b); err != nil {
116 http.Error(w, "invalid request body", http.StatusBadRequest)
117 return
118 }
119 if b.Name == "" || b.Backend == "" {
120 http.Error(w, "name and backend are required", http.StatusBadRequest)
121 return
122 }
123
124 p := s.policies.Get()
125 for _, existing := range p.LLMBackends {
126 if existing.Name == b.Name {
127 http.Error(w, "backend name already exists", http.StatusConflict)
128 return
129 }
130 }
131 // Also check YAML backends.
132 if s.llmCfg != nil {
133 for _, existing := range s.llmCfg.Backends {
134 if existing.Name == b.Name {
135 http.Error(w, "backend name already exists in config", http.StatusConflict)
136 return
137 }
138 }
139 }
140
141 p.LLMBackends = append(p.LLMBackends, b)
142 if err := s.policies.Set(p); err != nil {
143 http.Error(w, "failed to save", http.StatusInternalServerError)
144 return
145 }
146 writeJSON(w, http.StatusCreated, backendView{
147 Name: b.Name,
148 Backend: b.Backend,
149 APIKey: mask(b.APIKey),
150 BaseURL: b.BaseURL,
151 Model: b.Model,
152 Region: b.Region,
153 Allow: b.Allow,
154 Block: b.Block,
155 Default: b.Default,
156 Source: "policy",
157 })
158 }
159
160 // handleLLMBackendUpdate updates a policy-store backend by name.
161 // Fields present in the request body override the stored value.
162 // Send api_key / aws_secret_key as "" to leave the stored value unchanged
163 // (the UI masks these and should omit them if unchanged).
164 func (s *Server) handleLLMBackendUpdate(w http.ResponseWriter, r *http.Request) {
165 if s.policies == nil {
166 http.Error(w, "policy store not available", http.StatusServiceUnavailable)
167 return
168 }
169 name := r.PathValue("name")
170 var req PolicyLLMBackend
171 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
172 http.Error(w, "invalid request body", http.StatusBadRequest)
173 return
174 }
175
176 p := s.policies.Get()
177 idx := -1
178 for i, b := range p.LLMBackends {
179 if b.Name == name {
180 idx = i
181 break
182 }
183 }
184 if idx == -1 {
185 http.Error(w, "backend not found (only policy backends are editable)", http.StatusNotFound)
186 return
187 }
188
189 existing := p.LLMBackends[idx]
190 // Preserve stored secrets when the UI sends "***" or empty.
191 if req.APIKey == "" || req.APIKey == "***" {
192 req.APIKey = existing.APIKey
193 }
194 if req.AWSSecretKey == "" || req.AWSSecretKey == "***" {
195 req.AWSSecretKey = existing.AWSSecretKey
196 }
197 if req.AWSKeyID == "" || req.AWSKeyID == "***" {
198 req.AWSKeyID = existing.AWSKeyID
199 }
200 req.Name = name // name is immutable
201 p.LLMBackends[idx] = req
202
203 if err := s.policies.Set(p); err != nil {
204 http.Error(w, "failed to save", http.StatusInternalServerError)
205 return
206 }
207 writeJSON(w, http.StatusOK, backendView{
208 Name: req.Name,
209 Backend: req.Backend,
210 APIKey: mask(req.APIKey),
211 BaseURL: req.BaseURL,
212 Model: req.Model,
213 Region: req.Region,
214 Allow: req.Allow,
215 Block: req.Block,
216 Default: req.Default,
217 Source: "policy",
218 })
219 }
220
221 // handleLLMBackendDelete removes a policy-store backend by name.
222 func (s *Server) handleLLMBackendDelete(w http.ResponseWriter, r *http.Request) {
223 if s.policies == nil {
224 http.Error(w, "policy store not available", http.StatusServiceUnavailable)
225 return
226 }
227 name := r.PathValue("name")
228 p := s.policies.Get()
229 idx := -1
230 for i, b := range p.LLMBackends {
231 if b.Name == name {
232 idx = i
233 break
234 }
235 }
236 if idx == -1 {
237 http.Error(w, "backend not found (only policy backends are deletable)", http.StatusNotFound)
238 return
239 }
240 p.LLMBackends = append(p.LLMBackends[:idx], p.LLMBackends[idx+1:]...)
241 if err := s.policies.Set(p); err != nil {
242 http.Error(w, "failed to save", http.StatusInternalServerError)
243 return
244 }
245 w.WriteHeader(http.StatusNoContent)
246 }
247
248 // handleLLMModels runs model discovery for the named backend.
249 // Looks in YAML config first, then policy store.
250 func (s *Server) handleLLMModels(w http.ResponseWriter, r *http.Request) {
251 name := r.PathValue("name")
252 cfg, ok := s.findBackendConfig(name)
253 if !ok {
254 http.Error(w, "backend not found", http.StatusNotFound)
255 return
256 }
257 models, err := llm.Discover(r.Context(), cfg)
258 if err != nil {
259 s.log.Error("llm model discovery", "backend", name, "err", err)
260 http.Error(w, "model discovery failed: "+err.Error(), http.StatusBadGateway)
261 return
262 }
263 writeJSON(w, http.StatusOK, models)
264 }
265
266 // handleLLMDiscover runs ad-hoc model discovery from form credentials.
267 // Used by the UI "load live models" button before a backend is saved.
268 func (s *Server) handleLLMDiscover(w http.ResponseWriter, r *http.Request) {
269 var req struct {
270 Backend string `json:"backend"`
271 APIKey string `json:"api_key"`
272 BaseURL string `json:"base_url"`
273 Model string `json:"model"`
274 Region string `json:"region"`
275 AWSKeyID string `json:"aws_key_id"`
276 AWSSecretKey string `json:"aws_secret_key"`
277 Allow []string `json:"allow"`
278 Block []string `json:"block"`
279 }
280 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
281 http.Error(w, "invalid request body", http.StatusBadRequest)
282 return
283 }
284 if req.Backend == "" {
285 http.Error(w, "backend is required", http.StatusBadRequest)
286 return
287 }
288 cfg := llm.BackendConfig{
289 Backend: req.Backend,
290 APIKey: req.APIKey,
291 BaseURL: req.BaseURL,
292 Model: req.Model,
293 Region: req.Region,
294 AWSKeyID: req.AWSKeyID,
295 AWSSecretKey: req.AWSSecretKey,
296 Allow: req.Allow,
297 Block: req.Block,
298 }
299 models, err := llm.Discover(r.Context(), cfg)
300 if err != nil {
301 s.log.Error("llm ad-hoc discovery", "backend", req.Backend, "err", err)
302 http.Error(w, "model discovery failed: "+err.Error(), http.StatusBadGateway)
303 return
304 }
305 writeJSON(w, http.StatusOK, models)
306 }
307
308 // findBackendConfig looks up a backend by name in YAML config then policy store.
309 func (s *Server) findBackendConfig(name string) (llm.BackendConfig, bool) {
310 if s.llmCfg != nil {
311 for _, b := range s.llmCfg.Backends {
312 if b.Name == name {
313 return yamlBackendToLLM(b), true
314 }
315 }
316 }
317 if s.policies != nil {
318 for _, b := range s.policies.Get().LLMBackends {
319 if b.Name == name {
320 return policyBackendToLLM(b), true
321 }
322 }
323 }
324 return llm.BackendConfig{}, false
325 }
326
327 func yamlBackendToLLM(b config.LLMBackendConfig) llm.BackendConfig {
328 return llm.BackendConfig{
329 Backend: b.Backend,
330 APIKey: b.APIKey,
331 BaseURL:
--- a/internal/api/login.go
+++ b/internal/api/login.go
@@ -0,0 +1,185 @@
1
+package api
2
+
3
+import (
4
+ "encoding/json"
5
+ "net/http"
6
+ "sync"
7
+ "time"
8
+
9
+ "github.com/conflicthq/scuttlebot/internal/auth"
10
+)
11
+
12
+// adminStore is the interface the Server uses for admin operations.
13
+type adminStore interface {
14
+ Authenticate(username, password string) bool
15
+ List() []auth.Admin
16
+ Add(username, password string) error
17
+ Remove(username string) error
18
+ SetPassword(username, password string) error
19
+}
20
+
21
+// loginRateLimiter enforces a per-IP sliding window of 10 attempts per minute.
22
+type loginRateLimiter struct {
23
+ mu sync.Mutex
24
+ windows map[string][]time.Time
25
+}
26
+
27
+func newLoginRateLimiter() *loginRateLimiter {
28
+ return &loginRateLimiter{windows: make(map[string][]time.Time)}
29
+}
30
+
31
+// Allow returns true if the IP is within the allowed rate.
32
+func (rl *loginRateLimiter) Allow(ip string) bool {
33
+ rl.mu.Lock()
34
+ defer rl.mu.Unlock()
35
+
36
+ const (
37
+ maxAttempts = 10
38
+ window = time.Minute
39
+ )
40
+
41
+ now := time.Now()
42
+ cutoff := now.Add(-window)
43
+
44
+ prev := rl.windows[ip]
45
+ var kept []time.Time
46
+ for _, t := range prev {
47
+ if t.After(cutoff) {
48
+ kept = append(kept, t)
49
+ }
50
+ }
51
+ kept = append(kept, now)
52
+ rl.windows[ip] = kept
53
+
54
+ return len(kept) <= maxAttempts
55
+}
56
+
57
+func clientIP(r *http.Request) string {
58
+ // Use RemoteAddr; X-Forwarded-For is not trustworthy without proxy config.
59
+ host := r.RemoteAddr
60
+ // Strip port if present.
61
+ for i := len(host) - 1; i >= 0; i-- {
62
+ if host[i] == ':' {
63
+ host = host[:i]
64
+ break
65
+ }
66
+ }
67
+ return host
68
+}
69
+
70
+// handleLogin handles POST /login.
71
+// Unauthenticated. Returns {token, username} on success.
72
+func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
73
+ if s.admins == nil {
74
+ writeError(w, http.StatusNotFound, "admin authentication not configured")
75
+ return
76
+ }
77
+
78
+ ip := clientIP(r)
79
+ if !s.loginRL.Allow(ip) {
80
+ writeError(w, http.StatusTooManyRequests, "too many login attempts")
81
+ return
82
+ }
83
+
84
+ var req struct {
85
+ Username string `json:"username"`
86
+ Password string `json:"password"`
87
+ }
88
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
89
+ writeError(w, http.StatusBadRequest, "invalid request body")
90
+ return
91
+ }
92
+
93
+ if !s.admins.Authenticate(req.Username, req.Password) {
94
+ writeError(w, http.StatusUnauthorized, "invalid credentials")
95
+ return
96
+ }
97
+
98
+ // Return the first API token — the shared server token.
99
+ var token string
100
+ for t := range s.tokenStrip port if pts = 10
101
+ window = time.Minute
102
+ )
103
+
104
+ now := time.Now()
105
+ cutoff := now.Add(-window)
106
+
107
+ prev := rl.windows[ip]
108
+ var kept []time.Time
109
+ for _, t := range prev {
110
+ if t.After(cutoff) {
111
+ kept = append(kept, t)
112
+ }
113
+ }
114
+ kept = append(kept, now)
115
+ rl.windows[ip] = kept
116
+
117
+ return len(kept) <= maxAttempts
118
+}
119
+
120
+func clientIP(r *http.Request) string {
121
+ // Use RemoteAddr; X-Forwarded-For is not trustworthy without proxy config.
122
+ host := r.RemoteAddr
123
+ // Strip port if present.
124
+ for i := len(host) - 1; i >= 0; i-- {
125
+ if host[i] == ':' {
126
+ host = host[:i]
127
+ break
128
+ }
129
+ }
130
+ return host
131
+}
132
+
133
+// handleLogin handles POST /login.
134
+// Unauthenticated. Returns {token, username} on success.
135
+func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
136
+ if s.admins == nil {
137
+ writeError(w, http.StatusNotFound, "admin authentication not configured")
138
+ return
139
+ }
140
+
141
+ ip := clientIP(r)
142
+ if !s.loginRL.Allow(ip) {
143
+ writeError(w, http.StatusTooManyRequests, "too many login attempts")
144
+ return
145
+ }
146
+
147
+ var req struct {
148
+ Username string `json:"username"`
149
+ Password string `json:"password"`
150
+ }
151
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
152
+ writeError(w, http.StatusBadRequest, "invalid request body")
153
+ return
154
+ }
155
+
156
+ if !s.admins.Authenticate(req.Username, req.Password) {
157
+ writeError(w, http.StatusUnauthorized, "invalid credentials")
158
+ return
159
+ }
160
+
161
+ // Create a session API key for this admin login.
162
+ sessionName := "session:" + req.Username
163
+ token, _, err := s.apiKeys.Create(sessionName, []auth.Scope{auth.ScopeAdmin}, time.Now().Add(24*time.Hour))
164
+ if err != nil {
165
+ s.log.Error("login: create session key", "err", err)
166
+ writeError(w, http.StatusInternalServerError, "failed to create session")
167
+ return
168
+ }
169
+
170
+ writeJSON(w, http.StatusOK, map[string]string{
171
+ "token": token,
172
+ "username": req.Username,
173
+ })
174
+}
175
+
176
+// handleAdminList handles GET /v1/admins.
177
+func (s *Server) handleAdminList(w http.ResponseWriter, r *http.Request) {
178
+ admins := s.admins.List()
179
+ type adminView struct {
180
+ Username string `json:"username"`
181
+ Created time.Time `json:"created"`
182
+ }
183
+ out := make([]adminView, len(admins))
184
+ for i, a := range admins {
185
+ out[i] = adminView{Username: a.Username, Created:
--- a/internal/api/login.go
+++ b/internal/api/login.go
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/internal/api/login.go
+++ b/internal/api/login.go
@@ -0,0 +1,185 @@
1 package api
2
3 import (
4 "encoding/json"
5 "net/http"
6 "sync"
7 "time"
8
9 "github.com/conflicthq/scuttlebot/internal/auth"
10 )
11
12 // adminStore is the interface the Server uses for admin operations.
13 type adminStore interface {
14 Authenticate(username, password string) bool
15 List() []auth.Admin
16 Add(username, password string) error
17 Remove(username string) error
18 SetPassword(username, password string) error
19 }
20
21 // loginRateLimiter enforces a per-IP sliding window of 10 attempts per minute.
22 type loginRateLimiter struct {
23 mu sync.Mutex
24 windows map[string][]time.Time
25 }
26
27 func newLoginRateLimiter() *loginRateLimiter {
28 return &loginRateLimiter{windows: make(map[string][]time.Time)}
29 }
30
31 // Allow returns true if the IP is within the allowed rate.
32 func (rl *loginRateLimiter) Allow(ip string) bool {
33 rl.mu.Lock()
34 defer rl.mu.Unlock()
35
36 const (
37 maxAttempts = 10
38 window = time.Minute
39 )
40
41 now := time.Now()
42 cutoff := now.Add(-window)
43
44 prev := rl.windows[ip]
45 var kept []time.Time
46 for _, t := range prev {
47 if t.After(cutoff) {
48 kept = append(kept, t)
49 }
50 }
51 kept = append(kept, now)
52 rl.windows[ip] = kept
53
54 return len(kept) <= maxAttempts
55 }
56
57 func clientIP(r *http.Request) string {
58 // Use RemoteAddr; X-Forwarded-For is not trustworthy without proxy config.
59 host := r.RemoteAddr
60 // Strip port if present.
61 for i := len(host) - 1; i >= 0; i-- {
62 if host[i] == ':' {
63 host = host[:i]
64 break
65 }
66 }
67 return host
68 }
69
70 // handleLogin handles POST /login.
71 // Unauthenticated. Returns {token, username} on success.
72 func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
73 if s.admins == nil {
74 writeError(w, http.StatusNotFound, "admin authentication not configured")
75 return
76 }
77
78 ip := clientIP(r)
79 if !s.loginRL.Allow(ip) {
80 writeError(w, http.StatusTooManyRequests, "too many login attempts")
81 return
82 }
83
84 var req struct {
85 Username string `json:"username"`
86 Password string `json:"password"`
87 }
88 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
89 writeError(w, http.StatusBadRequest, "invalid request body")
90 return
91 }
92
93 if !s.admins.Authenticate(req.Username, req.Password) {
94 writeError(w, http.StatusUnauthorized, "invalid credentials")
95 return
96 }
97
98 // Return the first API token — the shared server token.
99 var token string
100 for t := range s.tokenStrip port if pts = 10
101 window = time.Minute
102 )
103
104 now := time.Now()
105 cutoff := now.Add(-window)
106
107 prev := rl.windows[ip]
108 var kept []time.Time
109 for _, t := range prev {
110 if t.After(cutoff) {
111 kept = append(kept, t)
112 }
113 }
114 kept = append(kept, now)
115 rl.windows[ip] = kept
116
117 return len(kept) <= maxAttempts
118 }
119
120 func clientIP(r *http.Request) string {
121 // Use RemoteAddr; X-Forwarded-For is not trustworthy without proxy config.
122 host := r.RemoteAddr
123 // Strip port if present.
124 for i := len(host) - 1; i >= 0; i-- {
125 if host[i] == ':' {
126 host = host[:i]
127 break
128 }
129 }
130 return host
131 }
132
133 // handleLogin handles POST /login.
134 // Unauthenticated. Returns {token, username} on success.
135 func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
136 if s.admins == nil {
137 writeError(w, http.StatusNotFound, "admin authentication not configured")
138 return
139 }
140
141 ip := clientIP(r)
142 if !s.loginRL.Allow(ip) {
143 writeError(w, http.StatusTooManyRequests, "too many login attempts")
144 return
145 }
146
147 var req struct {
148 Username string `json:"username"`
149 Password string `json:"password"`
150 }
151 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
152 writeError(w, http.StatusBadRequest, "invalid request body")
153 return
154 }
155
156 if !s.admins.Authenticate(req.Username, req.Password) {
157 writeError(w, http.StatusUnauthorized, "invalid credentials")
158 return
159 }
160
161 // Create a session API key for this admin login.
162 sessionName := "session:" + req.Username
163 token, _, err := s.apiKeys.Create(sessionName, []auth.Scope{auth.ScopeAdmin}, time.Now().Add(24*time.Hour))
164 if err != nil {
165 s.log.Error("login: create session key", "err", err)
166 writeError(w, http.StatusInternalServerError, "failed to create session")
167 return
168 }
169
170 writeJSON(w, http.StatusOK, map[string]string{
171 "token": token,
172 "username": req.Username,
173 })
174 }
175
176 // handleAdminList handles GET /v1/admins.
177 func (s *Server) handleAdminList(w http.ResponseWriter, r *http.Request) {
178 admins := s.admins.List()
179 type adminView struct {
180 Username string `json:"username"`
181 Created time.Time `json:"created"`
182 }
183 out := make([]adminView, len(admins))
184 for i, a := range admins {
185 out[i] = adminView{Username: a.Username, Created:
--- a/internal/api/login_test.go
+++ b/internal/api/login_test.go
@@ -0,0 +1,203 @@
1
+package api_test
2
+
3
+import (
4
+ "encoding/json"
5
+ "net/http"
6
+ "testing"
7
+
8
+ "github.com/conflicthq/scuttlebot/internal/api"
9
+ "github.com/conflicthq/scuttlebot/internal/auth"
10
+ "github.com/conflicthq/scuttlebot/internal/registry"
11
+ "net/http/httptest"
12
+ "path/filepath"
13
+)
14
+
15
+// newAdminStore creates an AdminStore backed by a temp file.
16
+func newAdminStore(t *testing.T) *auth.AdminStore {
17
+ t.Helper()
18
+ s, err := auth.NewAdminStore(filepath.Join(t.TempDir(), "admins.json"))
19
+ if err != nil {
20
+ t.Fatalf("NewAdminStore: %v", err)
21
+ }
22
+ return s
23
+}
24
+
25
+// newTestServerWithAdmins creates a test server with admin auth configured.
26
+func newTestServerWithAdmins(t *testing.T) (*httptest.Server, *auth.AdminStore) {
27
+ t.Helper()
28
+ admins := newAdminStore(t)
29
+ if err := admins.Add("admin", "hunter2"); err != nil {
30
+ t.Fatalf("Add admin: %v", err)
31
+ }
32
+ reg := registry.New(newMock(), []byte("test-signing-key"))
33
+ srv := api.New(reg, []string{testTokeil, admins, nil, nil, nil, "", testLog)
34
+ return httptest.NewServer(srv.Handler()), admins
35
+}
36
+
37
+func TestLoginNoAdmins(t *testing.T) {
38
+ // When admins is nil, login returns 404.
39
+ reg := registry.New(newMock(), []byte("test-signing-key"))
40
+ srv := api.New(reg, []string{testT"", testLog)
41
+ ts := httptest.NewServer(srv.Handler())
42
+ defer ts.Close()
43
+
44
+ resp := do(t, ts, "POST", "/login", map[string]any{"username": "admin", "password": "pw"}, nil)
45
+ defer resp.Body.Close()
46
+ if resp.StatusCode != http.StatusNotFound {
47
+ t.Errorf("expected 404 when no admins configured, got %d", resp.StatusCode)
48
+ }
49
+}
50
+
51
+func TestLoginValidCredentials(t *testing.T) {
52
+ ts, _ := newTestServerWithAdmins(t)
53
+ defer ts.Close()
54
+
55
+ resp := do(t, ts, "POST", "/login", map[string]any{"username": "admin", "password": "hunter2"}, nil)
56
+ defer resp.Body.Close()
57
+ if resp.StatusCode != http.StatusOK {
58
+ t.Fatalf("expected 200, got %d", resp.StatusCode)
59
+ }
60
+
61
+ var body map[string]string
62
+ if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
63
+ t.Fatalf("decode: %v", err)
64
+ }
65
+ if body["token"] == "" {
66
+ t.Error("expected token in response")
67
+ }
68
+ if body["username"] != "admin" {
69
+ t.Errorf("expected username=admin, got %q", body["username"])
70
+ }
71
+}
72
+
73
+func TestLoginWrongPassword(t *testing.T) {
74
+ ts, _ := newTestServerWithAdmins(t)
75
+ defer ts.Close()
76
+
77
+ resp := do(t, ts, "POST", "/login", map[string]any{"username": "admin", "password": "wrong"}, nil)
78
+ defer resp.Body.Close()
79
+ if resp.StatusCode != http.StatusUnauthorized {
80
+ t.Errorf("expected 401, got %d", resp.StatusCode)
81
+ }
82
+}
83
+
84
+func TestLoginUnknownUser(t *testing.T) {
85
+ ts, _ := newTestServerWithAdmins(t)
86
+ defer ts.Close()
87
+
88
+ resp := do(t, ts, "POST", "/login", map[string]any{"username": "nobody", "password": "hunter2"}, nil)
89
+ defer resp.Body.Close()
90
+ if resp.StatusCode != http.StatusUnauthorized {
91
+ t.Errorf("expected 401, got %d", resp.StatusCode)
92
+ }
93
+}
94
+
95
+func TestLoginBadBody(t *testing.T) {
96
+ ts, _ := newTestServerWithAdmins(t)
97
+ defer ts.Close()
98
+
99
+ resp := do(t, ts, "POST", "/login", "not-json", nil)
100
+ defer resp.Body.Close()
101
+ if resp.StatusCode != http.StatusBadRequest {
102
+ t.Errorf("expected 400, got %d", resp.StatusCode)
103
+ }
104
+}
105
+
106
+func TestLoginRateLimit(t *testing.T) {
107
+ ts, _ := newTestServerWithAdmins(t)
108
+ defer ts.Close()
109
+
110
+ // 11 attempts from the same IP — the 11th should be rate-limited.
111
+ var lastStatus int
112
+ for i := 0; i < 11; i++ {
113
+ resp := do(t, ts, "POST", "/login", map[string]any{"username": "admin", "password": "wrong"}, nil)
114
+ lastStatus = resp.StatusCode
115
+ resp.Body.Close()
116
+ }
117
+ if lastStatus != http.StatusTooManyRequests {
118
+ t.Errorf("expected 429 on 11th attempt, got %d", lastStatus)
119
+ }
120
+}
121
+
122
+// --- admin management endpoints ---
123
+
124
+func TestAdminList(t *testing.T) {
125
+ ts, _ := newTestServerWithAdmins(t)
126
+ defer ts.Close()
127
+
128
+ resp := do(t, ts, "GET", "/v1/admins", nil, authHeader())
129
+ defer resp.Body.Close()
130
+ if resp.StatusCode != http.StatusOK {
131
+ t.Fatalf("expected 200, got %d", resp.StatusCode)
132
+ }
133
+
134
+ var body map[string]any
135
+ if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
136
+ t.Fatalf("decode: %v", err)
137
+ }
138
+ admins := body["admins"].([]any)
139
+ if len(admins) != 1 {
140
+ t.Errorf("expected 1 admin, got %d", len(admins))
141
+ }
142
+}
143
+
144
+func TestAdminAdd(t *testing.T) {
145
+ ts, _ := newTestServerWithAdmins(t)
146
+ defer ts.Close()
147
+
148
+ resp := do(t, ts, "POST", "/v1/admins", map[string]any{"username": "bob", "password": "passw0rd"}, authHeader())
149
+ defer resp.Body.Close()
150
+ if resp.StatusCode != http.StatusCreated {
151
+ t.Errorf("expected 201, got %d", resp.StatusCode)
152
+ }
153
+
154
+ // List should now have 2.
155
+ resp2 := do(t, ts, "GET", "/v1/admins", nil, authHeader())
156
+ defer resp2.Body.Close()
157
+ var body map[string]any
158
+ json.NewDecoder(resp2.Body).Decode(&body)
159
+ admins := body["admins"].([]any)
160
+ if len(admins) != 2 {
161
+ t.Errorf("expected 2 admins after add, got %d", len(admins))
162
+ }
163
+}
164
+
165
+func TestAdminAddDuplicate(t *testing.T) {
166
+ ts, _ := newTestServerWithAdmins(t)
167
+ defer ts.Close()
168
+
169
+ resp := do(t, ts, "POST", "/v1/admins", map[string]any{"username": "admin", "password": "pw"}, authHeader())
170
+ defer resp.Body.Close()
171
+ if resp.StatusCode != http.StatusConflict {
172
+ t.Errorf("expected 409 on duplicate, got %d", resp.StatusCode)
173
+ }
174
+}
175
+
176
+func TestAdminAddMissingFields(t *testing.T) {
177
+ ts, _ := newTestServerWithAdmins(t)
178
+ defer ts.Close()
179
+
180
+ resp := do(t, ts, "POST", "/v1/admins", map[string]any{"username": "bob"}, authHeader())
181
+ defer resp.Body.Close()
182
+ if resp.StatusCode != http.StatusBadRequest {
183
+ t.Errorf("expected 400 when password missing, got %d", resp.StatusCode)
184
+ }
185
+}
186
+
187
+func TestAdminRemove(t *testing.T) {
188
+ ts, admins := newTestServerWithAdmins(t)
189
+ defer ts.Close()
190
+
191
+ // Add a second admin first so we're not removing the only one.
192
+ _ = admins.Add("bob", "pw")
193
+
194
+ resp := do(t, ts, "DELETE", "/v1/admins/admin", nil, authHeader())
195
+ defer resp.Body.Close()
196
+ if resp.StatusCode != http.StatusNoContent {
197
+ t.Errorf("expected 204, got %d", resp.StatusCode)
198
+ }
199
+
200
+ resp2 := do(t, ts, "GET", "/v1/admins", nil, authHeader())
201
+ defer resp2.Body.Close()
202
+ var body map[string]any
203
+ json.NewDecoder(resp2.B
--- a/internal/api/login_test.go
+++ b/internal/api/login_test.go
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/internal/api/login_test.go
+++ b/internal/api/login_test.go
@@ -0,0 +1,203 @@
1 package api_test
2
3 import (
4 "encoding/json"
5 "net/http"
6 "testing"
7
8 "github.com/conflicthq/scuttlebot/internal/api"
9 "github.com/conflicthq/scuttlebot/internal/auth"
10 "github.com/conflicthq/scuttlebot/internal/registry"
11 "net/http/httptest"
12 "path/filepath"
13 )
14
15 // newAdminStore creates an AdminStore backed by a temp file.
16 func newAdminStore(t *testing.T) *auth.AdminStore {
17 t.Helper()
18 s, err := auth.NewAdminStore(filepath.Join(t.TempDir(), "admins.json"))
19 if err != nil {
20 t.Fatalf("NewAdminStore: %v", err)
21 }
22 return s
23 }
24
25 // newTestServerWithAdmins creates a test server with admin auth configured.
26 func newTestServerWithAdmins(t *testing.T) (*httptest.Server, *auth.AdminStore) {
27 t.Helper()
28 admins := newAdminStore(t)
29 if err := admins.Add("admin", "hunter2"); err != nil {
30 t.Fatalf("Add admin: %v", err)
31 }
32 reg := registry.New(newMock(), []byte("test-signing-key"))
33 srv := api.New(reg, []string{testTokeil, admins, nil, nil, nil, "", testLog)
34 return httptest.NewServer(srv.Handler()), admins
35 }
36
37 func TestLoginNoAdmins(t *testing.T) {
38 // When admins is nil, login returns 404.
39 reg := registry.New(newMock(), []byte("test-signing-key"))
40 srv := api.New(reg, []string{testT"", testLog)
41 ts := httptest.NewServer(srv.Handler())
42 defer ts.Close()
43
44 resp := do(t, ts, "POST", "/login", map[string]any{"username": "admin", "password": "pw"}, nil)
45 defer resp.Body.Close()
46 if resp.StatusCode != http.StatusNotFound {
47 t.Errorf("expected 404 when no admins configured, got %d", resp.StatusCode)
48 }
49 }
50
51 func TestLoginValidCredentials(t *testing.T) {
52 ts, _ := newTestServerWithAdmins(t)
53 defer ts.Close()
54
55 resp := do(t, ts, "POST", "/login", map[string]any{"username": "admin", "password": "hunter2"}, nil)
56 defer resp.Body.Close()
57 if resp.StatusCode != http.StatusOK {
58 t.Fatalf("expected 200, got %d", resp.StatusCode)
59 }
60
61 var body map[string]string
62 if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
63 t.Fatalf("decode: %v", err)
64 }
65 if body["token"] == "" {
66 t.Error("expected token in response")
67 }
68 if body["username"] != "admin" {
69 t.Errorf("expected username=admin, got %q", body["username"])
70 }
71 }
72
73 func TestLoginWrongPassword(t *testing.T) {
74 ts, _ := newTestServerWithAdmins(t)
75 defer ts.Close()
76
77 resp := do(t, ts, "POST", "/login", map[string]any{"username": "admin", "password": "wrong"}, nil)
78 defer resp.Body.Close()
79 if resp.StatusCode != http.StatusUnauthorized {
80 t.Errorf("expected 401, got %d", resp.StatusCode)
81 }
82 }
83
84 func TestLoginUnknownUser(t *testing.T) {
85 ts, _ := newTestServerWithAdmins(t)
86 defer ts.Close()
87
88 resp := do(t, ts, "POST", "/login", map[string]any{"username": "nobody", "password": "hunter2"}, nil)
89 defer resp.Body.Close()
90 if resp.StatusCode != http.StatusUnauthorized {
91 t.Errorf("expected 401, got %d", resp.StatusCode)
92 }
93 }
94
95 func TestLoginBadBody(t *testing.T) {
96 ts, _ := newTestServerWithAdmins(t)
97 defer ts.Close()
98
99 resp := do(t, ts, "POST", "/login", "not-json", nil)
100 defer resp.Body.Close()
101 if resp.StatusCode != http.StatusBadRequest {
102 t.Errorf("expected 400, got %d", resp.StatusCode)
103 }
104 }
105
106 func TestLoginRateLimit(t *testing.T) {
107 ts, _ := newTestServerWithAdmins(t)
108 defer ts.Close()
109
110 // 11 attempts from the same IP — the 11th should be rate-limited.
111 var lastStatus int
112 for i := 0; i < 11; i++ {
113 resp := do(t, ts, "POST", "/login", map[string]any{"username": "admin", "password": "wrong"}, nil)
114 lastStatus = resp.StatusCode
115 resp.Body.Close()
116 }
117 if lastStatus != http.StatusTooManyRequests {
118 t.Errorf("expected 429 on 11th attempt, got %d", lastStatus)
119 }
120 }
121
122 // --- admin management endpoints ---
123
124 func TestAdminList(t *testing.T) {
125 ts, _ := newTestServerWithAdmins(t)
126 defer ts.Close()
127
128 resp := do(t, ts, "GET", "/v1/admins", nil, authHeader())
129 defer resp.Body.Close()
130 if resp.StatusCode != http.StatusOK {
131 t.Fatalf("expected 200, got %d", resp.StatusCode)
132 }
133
134 var body map[string]any
135 if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
136 t.Fatalf("decode: %v", err)
137 }
138 admins := body["admins"].([]any)
139 if len(admins) != 1 {
140 t.Errorf("expected 1 admin, got %d", len(admins))
141 }
142 }
143
144 func TestAdminAdd(t *testing.T) {
145 ts, _ := newTestServerWithAdmins(t)
146 defer ts.Close()
147
148 resp := do(t, ts, "POST", "/v1/admins", map[string]any{"username": "bob", "password": "passw0rd"}, authHeader())
149 defer resp.Body.Close()
150 if resp.StatusCode != http.StatusCreated {
151 t.Errorf("expected 201, got %d", resp.StatusCode)
152 }
153
154 // List should now have 2.
155 resp2 := do(t, ts, "GET", "/v1/admins", nil, authHeader())
156 defer resp2.Body.Close()
157 var body map[string]any
158 json.NewDecoder(resp2.Body).Decode(&body)
159 admins := body["admins"].([]any)
160 if len(admins) != 2 {
161 t.Errorf("expected 2 admins after add, got %d", len(admins))
162 }
163 }
164
165 func TestAdminAddDuplicate(t *testing.T) {
166 ts, _ := newTestServerWithAdmins(t)
167 defer ts.Close()
168
169 resp := do(t, ts, "POST", "/v1/admins", map[string]any{"username": "admin", "password": "pw"}, authHeader())
170 defer resp.Body.Close()
171 if resp.StatusCode != http.StatusConflict {
172 t.Errorf("expected 409 on duplicate, got %d", resp.StatusCode)
173 }
174 }
175
176 func TestAdminAddMissingFields(t *testing.T) {
177 ts, _ := newTestServerWithAdmins(t)
178 defer ts.Close()
179
180 resp := do(t, ts, "POST", "/v1/admins", map[string]any{"username": "bob"}, authHeader())
181 defer resp.Body.Close()
182 if resp.StatusCode != http.StatusBadRequest {
183 t.Errorf("expected 400 when password missing, got %d", resp.StatusCode)
184 }
185 }
186
187 func TestAdminRemove(t *testing.T) {
188 ts, admins := newTestServerWithAdmins(t)
189 defer ts.Close()
190
191 // Add a second admin first so we're not removing the only one.
192 _ = admins.Add("bob", "pw")
193
194 resp := do(t, ts, "DELETE", "/v1/admins/admin", nil, authHeader())
195 defer resp.Body.Close()
196 if resp.StatusCode != http.StatusNoContent {
197 t.Errorf("expected 204, got %d", resp.StatusCode)
198 }
199
200 resp2 := do(t, ts, "GET", "/v1/admins", nil, authHeader())
201 defer resp2.Body.Close()
202 var body map[string]any
203 json.NewDecoder(resp2.B
--- a/internal/api/metrics.go
+++ b/internal/api/metrics.go
@@ -0,0 +1,69 @@
1
+package api
2
+
3
+import (
4
+ "net/http"
5
+ "runtime"
6
+ "time"
7
+)
8
+
9
+type metricsResponse struct {
10
+ Timestamp string `json:"timestamp"`
11
+ Runtime runtimeMetrics `json:"runtime"`
12
+ Bridge *bridgeMetrics `json:"bridge,omitempty"`
13
+ Registry registryMetrics `json:"registry"`
14
+}
15
+
16
+type runtimeMetrics struct {
17
+ Goroutines int `json:"goroutines"`
18
+ HeapAlloc uint64 `json:"heap_alloc_bytes"`
19
+ HeapSys uint64 `json:"heap_sys_bytes"`
20
+ GCRuns uint32 `json:"gc_runs"`
21
+}
22
+
23
+type bridgeMetrics struct {
24
+ Channels int `json:"channels"`
25
+ MessagesTotal int64 `json:"messages_total"`
26
+ ActiveSubs int `json:"active_subscribers"`
27
+}
28
+
29
+type registryMetrics struct {
30
+ Total int `json:"total"`
31
+ Active int `json:"active"`
32
+ Revoked int `json:"revoked"`
33
+}
34
+
35
+func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
36
+ var ms runtime.MemStats
37
+ runtime.ReadMemStats(&ms)
38
+
39
+ resp := metricsResponse{
40
+ Timestamp: time.Now().UTC().Format(time.RFC3339),
41
+ Runtime: runtimeMetrics{
42
+ Goroutines: runtime.NumGoroutine(),
43
+ HeapAlloc: ms.HeapAlloc,
44
+ HeapSys: ms.HeapSys,
45
+ GCRuns: ms.NumGC,
46
+ },
47
+ }
48
+
49
+ if s.bridge != nil {
50
+ st := s.bridge.Stats()
51
+ resp.Bridge = &bridgeMetrics{
52
+ Channels: st.Channels,
53
+ MessagesTotal: st.MessagesTotal,
54
+ ActiveSubs: st.ActiveSubs,
55
+ }
56
+ }
57
+
58
+ agents := s.registry.List()
59
+ for _, a := range agents {
60
+ resp.Registry.Total++
61
+ if a.Revoked {
62
+ resp.Registry.Revoked++
63
+ } else {
64
+ resp.Registry.Active++
65
+ }
66
+ }
67
+
68
+ writeJSON(w, http.StatusOK, resp)
69
+}
--- a/internal/api/metrics.go
+++ b/internal/api/metrics.go
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/internal/api/metrics.go
+++ b/internal/api/metrics.go
@@ -0,0 +1,69 @@
1 package api
2
3 import (
4 "net/http"
5 "runtime"
6 "time"
7 )
8
9 type metricsResponse struct {
10 Timestamp string `json:"timestamp"`
11 Runtime runtimeMetrics `json:"runtime"`
12 Bridge *bridgeMetrics `json:"bridge,omitempty"`
13 Registry registryMetrics `json:"registry"`
14 }
15
16 type runtimeMetrics struct {
17 Goroutines int `json:"goroutines"`
18 HeapAlloc uint64 `json:"heap_alloc_bytes"`
19 HeapSys uint64 `json:"heap_sys_bytes"`
20 GCRuns uint32 `json:"gc_runs"`
21 }
22
23 type bridgeMetrics struct {
24 Channels int `json:"channels"`
25 MessagesTotal int64 `json:"messages_total"`
26 ActiveSubs int `json:"active_subscribers"`
27 }
28
29 type registryMetrics struct {
30 Total int `json:"total"`
31 Active int `json:"active"`
32 Revoked int `json:"revoked"`
33 }
34
35 func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
36 var ms runtime.MemStats
37 runtime.ReadMemStats(&ms)
38
39 resp := metricsResponse{
40 Timestamp: time.Now().UTC().Format(time.RFC3339),
41 Runtime: runtimeMetrics{
42 Goroutines: runtime.NumGoroutine(),
43 HeapAlloc: ms.HeapAlloc,
44 HeapSys: ms.HeapSys,
45 GCRuns: ms.NumGC,
46 },
47 }
48
49 if s.bridge != nil {
50 st := s.bridge.Stats()
51 resp.Bridge = &bridgeMetrics{
52 Channels: st.Channels,
53 MessagesTotal: st.MessagesTotal,
54 ActiveSubs: st.ActiveSubs,
55 }
56 }
57
58 agents := s.registry.List()
59 for _, a := range agents {
60 resp.Registry.Total++
61 if a.Revoked {
62 resp.Registry.Revoked++
63 } else {
64 resp.Registry.Active++
65 }
66 }
67
68 writeJSON(w, http.StatusOK, resp)
69 }

No diff available

--- a/internal/api/policies_test.go
+++ b/internal/api/policies_test.go
@@ -0,0 +1,36 @@
1
+package api
2
+
3
+import (
4
+ "path/filepath"
5
+ "testing"
6
+)
7
+
8
+func TestNewPolicyStoreDefaultsBridgeTTL(t *testing.T) {
9
+ ps, err := NewPolicyStore(filepath.Join(t.TempDir(), "policies.json"), 5)
10
+ if err != nil {
11
+ t.Fatalf("NewPolicyStore() error = %v", err)
12
+ }
13
+
14
+ got := ps.Get().Bridge.WebUserTTLMinutes
15
+ if got != 5 {
16
+ t.Fatalf("default bridge ttl = %d, want 5", got)
17
+ }
18
+}
19
+
20
+func TestPolicyStoreSetNormalizesBridgeTTL(t *testing.T) {
21
+ ps, err := NewPolicyStore(filepath.Join(t.TempDir(), "policies.json"), 5)
22
+ if err != nil {
23
+ t.Fatalf("NewPolicyStore() error = %v", err)
24
+ }
25
+
26
+ p := ps.Get()
27
+ p.Bridge.WebUserTTLMinutes = 0
28
+ if err := ps.Set(p); err != nil {
29
+ t.Fatalf("Set() error = %v", err)
30
+ }
31
+
32
+ got := ps.Get().Bridge.WebUserTTLMinutes
33
+ if got != 5 {
34
+ t.Fatalf("normalized bridge ttl = %d, want 5", got)
35
+ }
36
+}
--- a/internal/api/policies_test.go
+++ b/internal/api/policies_test.go
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/internal/api/policies_test.go
+++ b/internal/api/policies_test.go
@@ -0,0 +1,36 @@
1 package api
2
3 import (
4 "path/filepath"
5 "testing"
6 )
7
8 func TestNewPolicyStoreDefaultsBridgeTTL(t *testing.T) {
9 ps, err := NewPolicyStore(filepath.Join(t.TempDir(), "policies.json"), 5)
10 if err != nil {
11 t.Fatalf("NewPolicyStore() error = %v", err)
12 }
13
14 got := ps.Get().Bridge.WebUserTTLMinutes
15 if got != 5 {
16 t.Fatalf("default bridge ttl = %d, want 5", got)
17 }
18 }
19
20 func TestPolicyStoreSetNormalizesBridgeTTL(t *testing.T) {
21 ps, err := NewPolicyStore(filepath.Join(t.TempDir(), "policies.json"), 5)
22 if err != nil {
23 t.Fatalf("NewPolicyStore() error = %v", err)
24 }
25
26 p := ps.Get()
27 p.Bridge.WebUserTTLMinutes = 0
28 if err := ps.Set(p); err != nil {
29 t.Fatalf("Set() error = %v", err)
30 }
31
32 got := ps.Get().Bridge.WebUserTTLMinutes
33 if got != 5 {
34 t.Fatalf("normalized bridge ttl = %d, want 5", got)
35 }
36 }
--- internal/api/server.go
+++ internal/api/server.go
@@ -66,10 +66,11 @@
6666
apiMux.HandleFunc("POST /v1/agents/{nick}/revoke", s.handleRevoke)
6767
apiMux.HandleFunc("DELETE /v1/agents/{nick}", s.handleDelete)
6868
if s.bridge != nil {
6969
apiMux.HandleFunc("GET /v1/channels", s.handleListChannels)
7070
apiMux.HandleFunc("POST /v1/channels/{channel}/join", s.handleJoinChannel)
71
+ apiMux.HandleFunc("DELETE /v1/channels/{channel}", s.handleDeleteChannel)
7172
apiMux.HandleFunc("GET /v1/channels/{channel}/messages", s.handleChannelMessages)
7273
apiMux.HandleFunc("POST /v1/channels/{channel}/messages", s.handleSendMessage)
7374
apiMux.HandleFunc("POST /v1/channels/{channel}/presence", s.handleChannelPresence)
7475
apiMux.HandleFunc("GET /v1/channels/{channel}/users", s.handleChannelUsers)
7576
}
7677
7778
ADDED internal/api/settings.go
--- internal/api/server.go
+++ internal/api/server.go
@@ -66,10 +66,11 @@
66 apiMux.HandleFunc("POST /v1/agents/{nick}/revoke", s.handleRevoke)
67 apiMux.HandleFunc("DELETE /v1/agents/{nick}", s.handleDelete)
68 if s.bridge != nil {
69 apiMux.HandleFunc("GET /v1/channels", s.handleListChannels)
70 apiMux.HandleFunc("POST /v1/channels/{channel}/join", s.handleJoinChannel)
 
71 apiMux.HandleFunc("GET /v1/channels/{channel}/messages", s.handleChannelMessages)
72 apiMux.HandleFunc("POST /v1/channels/{channel}/messages", s.handleSendMessage)
73 apiMux.HandleFunc("POST /v1/channels/{channel}/presence", s.handleChannelPresence)
74 apiMux.HandleFunc("GET /v1/channels/{channel}/users", s.handleChannelUsers)
75 }
76
77 DDED internal/api/settings.go
--- internal/api/server.go
+++ internal/api/server.go
@@ -66,10 +66,11 @@
66 apiMux.HandleFunc("POST /v1/agents/{nick}/revoke", s.handleRevoke)
67 apiMux.HandleFunc("DELETE /v1/agents/{nick}", s.handleDelete)
68 if s.bridge != nil {
69 apiMux.HandleFunc("GET /v1/channels", s.handleListChannels)
70 apiMux.HandleFunc("POST /v1/channels/{channel}/join", s.handleJoinChannel)
71 apiMux.HandleFunc("DELETE /v1/channels/{channel}", s.handleDeleteChannel)
72 apiMux.HandleFunc("GET /v1/channels/{channel}/messages", s.handleChannelMessages)
73 apiMux.HandleFunc("POST /v1/channels/{channel}/messages", s.handleSendMessage)
74 apiMux.HandleFunc("POST /v1/channels/{channel}/presence", s.handleChannelPresence)
75 apiMux.HandleFunc("GET /v1/channels/{channel}/users", s.handleChannelUsers)
76 }
77
78 DDED internal/api/settings.go
--- a/internal/api/settings.go
+++ b/internal/api/settings.go
@@ -0,0 +1,25 @@
1
+package api
2
+
3
+import "net/http"
4
+
5
+type settingsResponse struct {
6
+ TLS tlsInfo `json:"tls"`
7
+ Policies Policies `json:"policies"`
8
+:"bot_commands,omitempty"`
9
+}
10
+
11
+type tlsInfo struct {
12
+ Enabled bool `json:"enabled"`
13
+ Domain string `json:"domain,omitempty"`
14
+ AllowInsecure bool `json:"allow_insecure"`
15
+}
16
+
17
+func (s *Server) handleGetSettings(w http.ResponseWriter, r *http.Request) {
18
+ resp := settingsResponse{
19
+ TLS: tlsInfo{
20
+ Enabled: s.tlsDomain != "",
21
+ Domain: s.tlsDoma // always true in current build Domain: s.tlsDomain,
22
+ AllowInsecure: true,
23
+ },
24
+ }
25
+ if s.pol
--- a/internal/api/settings.go
+++ b/internal/api/settings.go
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/internal/api/settings.go
+++ b/internal/api/settings.go
@@ -0,0 +1,25 @@
1 package api
2
3 import "net/http"
4
5 type settingsResponse struct {
6 TLS tlsInfo `json:"tls"`
7 Policies Policies `json:"policies"`
8 :"bot_commands,omitempty"`
9 }
10
11 type tlsInfo struct {
12 Enabled bool `json:"enabled"`
13 Domain string `json:"domain,omitempty"`
14 AllowInsecure bool `json:"allow_insecure"`
15 }
16
17 func (s *Server) handleGetSettings(w http.ResponseWriter, r *http.Request) {
18 resp := settingsResponse{
19 TLS: tlsInfo{
20 Enabled: s.tlsDomain != "",
21 Domain: s.tlsDoma // always true in current build Domain: s.tlsDomain,
22 AllowInsecure: true,
23 },
24 }
25 if s.pol
--- internal/api/ui/index.html
+++ internal/api/ui/index.html
@@ -3,545 +3,2476 @@
33
<head>
44
<meta charset="UTF-8">
55
<meta name="viewport" content="width=device-width, initial-scale=1.0">
66
<title>scuttlebot</title>
77
<style>
8
- * { box-sizing: border-box; margin: 0; padding: 0; }
9
- body { font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace; background: #0d1117; color: #e6edf3; min-height: 100vh; }
10
- header { background: #161b22; border-bottom: 1px solid #30363d; padding: 12px 24px; display: flex; align-items: center; gap: 16px; }
11
- header h1 { font-size: 16px; color: #58a6ff; letter-spacing: 0.05em; }
12
- header .tagline { font-size: 12px; color: #8b949e; }
13
- header .spacer { flex: 1; }
14
- .token-badge { font-size: 12px; color: #8b949e; display: flex; align-items: center; gap: 8px; }
15
- .token-badge code { background: #21262d; border: 1px solid #30363d; border-radius: 4px; padding: 2px 8px; color: #a5d6ff; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
16
- button { cursor: pointer; border: 1px solid #30363d; border-radius: 6px; padding: 6px 12px; font-size: 13px; font-family: inherit; background: #21262d; color: #e6edf3; transition: background 0.1s; }
17
- button:hover { background: #30363d; }
18
- button.primary { background: #1f6feb; border-color: #1f6feb; color: #fff; }
19
- button.primary:hover { background: #388bfd; }
20
- button.danger { background: #21262d; border-color: #f85149; color: #f85149; }
21
- button.danger:hover { background: #3d1f1e; }
22
- button.small { padding: 3px 8px; font-size: 12px; }
23
- main { max-width: 960px; margin: 0 auto; padding: 24px; display: flex; flex-direction: column; gap: 24px; }
24
- .card { background: #161b22; border: 1px solid #30363d; border-radius: 8px; overflow: hidden; }
25
- .card-header { padding: 12px 16px; border-bottom: 1px solid #30363d; display: flex; align-items: center; gap: 8px; }
26
- .card-header h2 { font-size: 14px; color: #e6edf3; font-weight: 600; }
27
- .card-header .badge { background: #1f6feb22; border: 1px solid #1f6feb44; color: #58a6ff; border-radius: 999px; padding: 1px 8px; font-size: 12px; }
28
- .card-body { padding: 16px; }
29
- .status-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; }
30
- .stat { background: #0d1117; border: 1px solid #21262d; border-radius: 6px; padding: 12px 16px; }
31
- .stat .label { font-size: 11px; color: #8b949e; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 4px; }
32
- .stat .value { font-size: 20px; color: #58a6ff; font-weight: 600; }
33
- .stat .sub { font-size: 11px; color: #8b949e; margin-top: 2px; }
34
- .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; }
35
- .dot.green { background: #3fb950; box-shadow: 0 0 6px #3fb950aa; }
36
- .dot.red { background: #f85149; }
37
- table { width: 100%; border-collapse: collapse; font-size: 13px; }
38
- th { text-align: left; padding: 8px 12px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #8b949e; border-bottom: 1px solid #21262d; }
39
- td { padding: 10px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; vertical-align: top; }
40
- tr:last-child td { border-bottom: none; }
41
- tr:hover td { background: #1c2128; }
42
- .tag { display: inline-block; background: #1f6feb22; border: 1px solid #1f6feb44; color: #79c0ff; border-radius: 4px; padding: 1px 6px; font-size: 11px; margin: 1px; }
43
- .tag.type-operator { background: #db613622; border-color: #db613644; color: #ffa657; }
44
- .tag.type-orchestrator { background: #8957e522; border-color: #8957e544; color: #d2a8ff; }
45
- .tag.type-worker { background: #1f6feb22; border-color: #1f6feb44; color: #79c0ff; }
46
- .tag.type-observer { background: #21262d; border-color: #30363d; color: #8b949e; }
47
- .tag.revoked { background: #f8514922; border-color: #f8514944; color: #ff7b72; }
48
- .actions { display: flex; gap: 6px; flex-wrap: wrap; }
49
- .empty { color: #8b949e; font-size: 13px; text-align: center; padding: 24px; }
50
- .chan-item { padding: 8px 12px; font-size: 13px; cursor: pointer; color: #8b949e; border-bottom: 1px solid #21262d; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
51
- .chan-item:hover { background: #1c2128; color: #e6edf3; }
52
- .chan-item.active { background: #1f6feb22; color: #58a6ff; border-left: 2px solid #58a6ff; }
53
- .msg-row { display: flex; gap: 8px; font-size: 13px; line-height: 1.6; padding: 1px 0; }
54
- .msg-time { color: #8b949e; font-size: 11px; flex-shrink: 0; padding-top: 3px; min-width: 44px; }
55
- .msg-nick { color: #58a6ff; font-weight: 600; flex-shrink: 0; min-width: 80px; text-align: right; }
56
- .msg-nick.bridge-nick { color: #3fb950; }
57
- .msg-text { color: #e6edf3; word-break: break-word; }
58
- form { display: flex; flex-direction: column; gap: 14px; }
59
- .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
60
- label { display: block; font-size: 12px; color: #8b949e; margin-bottom: 4px; }
61
- input, select, textarea { width: 100%; background: #0d1117; border: 1px solid #30363d; border-radius: 6px; padding: 8px 10px; font-size: 13px; font-family: inherit; color: #e6edf3; outline: none; transition: border-color 0.1s; }
62
- input:focus, select:focus, textarea:focus { border-color: #58a6ff; }
63
- select option { background: #161b22; }
64
- textarea { resize: vertical; min-height: 60px; }
65
- .hint { font-size: 11px; color: #8b949e; margin-top: 3px; }
66
- .alert { border-radius: 6px; padding: 12px 14px; font-size: 13px; display: flex; gap: 10px; align-items: flex-start; }
67
- .alert.info { background: #1f6feb1a; border: 1px solid #1f6feb44; color: #79c0ff; }
68
- .alert.error { background: #f851491a; border: 1px solid #f8514944; color: #ff7b72; }
69
- .alert.success { background: #3fb9501a; border: 1px solid #3fb95044; color: #7ee787; }
70
- .alert .icon { flex-shrink: 0; font-size: 16px; line-height: 1.3; }
71
- .cred-box { background: #0d1117; border: 1px solid #30363d; border-radius: 6px; padding: 12px; font-size: 12px; }
72
- .cred-box .cred-row { display: flex; align-items: baseline; gap: 8px; margin-bottom: 6px; }
73
- .cred-box .cred-row:last-child { margin-bottom: 0; }
74
- .cred-box .cred-key { color: #8b949e; min-width: 90px; }
75
- .cred-box .cred-val { color: #a5d6ff; word-break: break-all; flex: 1; }
76
- .cred-box .copy-btn { flex-shrink: 0; }
77
- .modal-overlay { display: none; position: fixed; inset: 0; background: #0d111788; z-index: 100; align-items: center; justify-content: center; }
78
- .modal-overlay.open { display: flex; }
79
- .modal { background: #161b22; border: 1px solid #30363d; border-radius: 10px; padding: 24px; width: 480px; max-width: 95vw; }
80
- .modal h3 { font-size: 15px; margin-bottom: 16px; }
81
- .modal .btn-row { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
8
+* { box-sizing: border-box; margin: 0; padding: 0; }
9
+body { font-family: ui-monospace,'Cascadia Code','Source Code Pro',monospace; background:#0d1117; color:#e6edf3; height:100vh; display:flex; flex-direction:column; overflow:hidden; }
10
+
11
+/* header */
12
+header { background:#161b22; border-bottom:1px solid #30363d; padding:0 20px; display:flex; align-items:stretch; flex-shrink:0; height:48px; }
13
+.brand { display:flex; align-items:center; gap:8px; padding-right:20px; border-right:1px solid #30363d; margin-right:4px; }
14
+.brand h1 { font-size:14px; color:#58a6ff; letter-spacing:.05em; }
15
+.brand span { font-size:11px; color:#8b949e; }
16
+nav { display:flex; align-items:stretch; flex:1; }
17
+.nav-tab { display:flex; align-items:center; gap:6px; padding:0 14px; font-size:13px; color:#8b949e; cursor:pointer; border-bottom:2px solid transparent; margin-bottom:-1px; transition:color .1s; white-space:nowrap; }
18
+.nav-tab:hover { color:#c9d1d9; }
19
+.nav-tab.active { color:#e6edf3; border-bottom-color:#58a6ff; }
20
+.header-right { display:flex; align-items:center; gap:8px; margin-left:auto; font-size:12px; color:#8b949e; }
21
+.header-right code { background:#21262d; border:1px solid #30363d; border-radius:4px; padding:2px 7px; color:#a5d6ff; max-width:160px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
22
+
23
+/* tab panes */
24
+.tab-pane { display:none; flex:1; min-height:0; overflow-y:auto; }
25
+.tab-pane.active { display:flex; flex-direction:column; }
26
+.pane-scroll { flex:1; overflow-y:auto; }
27
+.pane-inner { max-width:1000px; margin:0 auto; padding:24px; display:flex; flex-direction:column; gap:20px; }
28
+
29
+/* cards */
30
+.card { background:#161b22; border:1px solid #30363d; border-radius:8px; overflow:hidden; }
31
+.card-header { padding:12px 16px; border-bottom:1px solid #30363d; display:flex; align-items:center; gap:8px; cursor:pointer; user-select:none; }
32
+.card-header:hover { background:#1c2128; }
33
+.card-header h2 { font-size:14px; font-weight:600; }
34
+.card-header .collapse-icon { font-size:11px; color:#8b949e; margin-left:2px; transition:transform .15s; }
35
+.card.collapsed .card-header { border-bottom:none; }
36
+.card.collapsed .card-body { display:none; }
37
+.card.collapsed .collapse-icon { transform:rotate(-90deg); }
38
+.card-body { padding:16px; }
39
+/* behavior config panel */
40
+.beh-config { background:#0d1117; border-top:1px solid #21262d; padding:14px 16px 14px 42px; display:none; }
41
+.beh-config.open { display:grid; grid-template-columns:repeat(auto-fill,minmax(220px,1fr)); gap:12px; }
42
+.beh-field label { display:block; font-size:11px; color:#8b949e; margin-bottom:3px; }
43
+.beh-field input[type=text],.beh-field input[type=number],.beh-field select { width:100%; }
44
+.beh-field .hint { font-size:10px; color:#6e7681; margin-top:2px; }
45
+.spacer { flex:1; }
46
+.badge { background:#1f6feb22; border:1px solid #1f6feb44; color:#58a6ff; border-radius:999px; padding:1px 8px; font-size:12px; }
47
+
48
+/* status */
49
+.stat-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:12px; }
50
+.stat { background:#0d1117; border:1px solid #21262d; border-radius:6px; padding:12px 16px; }
51
+.stat .lbl { font-size:11px; color:#8b949e; text-transform:uppercase; letter-spacing:.06em; margin-bottom:4px; }
52
+.stat .val { font-size:20px; color:#58a6ff; font-weight:600; }
53
+.stat .sub { font-size:11px; color:#8b949e; margin-top:2px; }
54
+.dot { display:inline-block; width:8px; height:8px; border-radius:50%; margin-right:5px; }
55
+.dot.green { background:#3fb950; box-shadow:0 0 6px #3fb950aa; }
56
+.dot.red { background:#f85149; }
57
+
58
+/* table */
59
+table { width:100%; border-collapse:collapse; font-size:13px; }
60
+th { text-align:left; padding:8px 12px; font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:#8b949e; border-bottom:1px solid #21262d; white-space:nowrap; }
61
+td { padding:9px 12px; border-bottom:1px solid #21262d; color:#e6edf3; vertical-align:middle; }
62
+tr:last-child td { border-bottom:none; }
63
+tr:hover td { background:#1c2128; }
64
+
65
+/* tags */
66
+.tag { display:inline-block; border-radius:4px; padding:1px 6px; font-size:11px; margin:1px; border:1px solid; }
67
+.tag.ch { background:#1f6feb22; border-color:#1f6feb44; color:#79c0ff; }
68
+.tag.perm{ background:#21262d; border-color:#30363d; color:#8b949e; }
69
+.tag.type-operator { background:#db613622; border-color:#db613644; color:#ffa657; }
70
+.tag.type-orchestrator { background:#8957e522; border-color:#8957e544; color:#d2a8ff; }
71
+.tag.type-worker { background:#1f6feb22; border-color:#1f6feb44; color:#79c0ff; }
72
+.tag.type-observer { background:#21262d; border-color:#30363d; color:#8b949e; }
73
+.tag.revoked { background:#f8514922; border-color:#f8514944; color:#ff7b72; }
74
+
75
+/* buttons */
76
+button { cursor:pointer; border:1px solid #30363d; border-radius:6px; padding:6px 12px; font-size:13px; font-family:inherit; background:#21262d; color:#e6edf3; transition:background .1s; }
77
+button:hover:not(:disabled) { background:#30363d; }
78
+button:disabled { opacity:.5; cursor:default; }
79
+button.primary { background:#1f6feb; border-color:#1f6feb; color:#fff; }
80
+button.primary:hover:not(:disabled) { background:#388bfd; }
81
+button.danger { border-color:#f85149; color:#f85149; }
82
+button.danger:hover:not(:disabled) { background:#3d1f1e; }
83
+button.sm { padding:3px 8px; font-size:12px; }
84
+.actions { display:flex; gap:6px; }
85
+
86
+/* forms */
87
+form { display:flex; flex-direction:column; gap:14px; }
88
+.form-row { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
89
+label { display:block; font-size:12px; color:#8b949e; margin-bottom:4px; }
90
+input,select,textarea { width:100%; background:#0d1117; border:1px solid #30363d; border-radius:6px; padding:8px 10px; font-size:13px; font-family:inherit; color:#e6edf3; outline:none; transition:border-color .1s; }
91
+input:focus,select:focus,textarea:focus { border-color:#58a6ff; }
92
+select option { background:#161b22; }
93
+.hint { font-size:11px; color:#8b949e; margin-top:3px; }
94
+
95
+/* alerts */
96
+.alert { border-radius:6px; padding:12px 14px; font-size:13px; display:flex; gap:10px; align-items:flex-start; }
97
+.alert.info { background:#1f6feb1a; border:1px solid #1f6feb44; color:#79c0ff; }
98
+.alert.error { background:#f851491a; border:1px solid #f8514944; color:#ff7b72; }
99
+.alert.success { background:#3fb9501a; border:1px solid #3fb95044; color:#7ee787; }
100
+.alert .icon { flex-shrink:0; font-size:15px; line-height:1.4; }
101
+.cred-box { background:#0d1117; border:1px solid #30363d; border-radius:6px; padding:12px; font-size:12px; margin-top:10px; }
102
+.cred-row { display:flex; align-items:baseline; gap:8px; margin-bottom:6px; }
103
+.cred-row:last-child { margin-bottom:0; }
104
+.cred-key { color:#8b949e; min-width:90px; }
105
+.cred-val { color:#a5d6ff; word-break:break-all; flex:1; }
106
+
107
+/* search/filter bar */
108
+.filter-bar { display:flex; gap:8px; align-items:center; padding:10px 16px; border-bottom:1px solid #30363d; }
109
+.filter-bar input { max-width:280px; padding:5px 10px; }
110
+
111
+/* empty */
112
+.empty { color:#8b949e; font-size:13px; text-align:center; padding:28px; }
113
+
114
+/* drawer */
115
+.drawer-overlay { display:none; position:fixed; inset:0; background:#0d111760; z-index:50; }
116
+.drawer-overlay.open { display:block; }
117
+.drawer { position:fixed; top:48px; right:0; bottom:0; width:480px; max-width:95vw; background:#161b22; border-left:1px solid #30363d; transform:translateX(100%); transition:transform .2s; z-index:51; display:flex; flex-direction:column; }
118
+.drawer.open { transform:translateX(0); }
119
+.drawer-header { padding:16px 20px; border-bottom:1px solid #30363d; display:flex; align-items:center; gap:8px; flex-shrink:0; }
120
+.drawer-header h3 { font-size:14px; font-weight:600; flex:1; }
121
+.drawer-body { flex:1; overflow-y:auto; padding:20px; }
122
+
123
+/* chat */
124
+#pane-chat { flex-direction:row; overflow:hidden; }
125
+.chat-sidebar { width:180px; min-width:0; flex-shrink:0; border-right:1px solid #30363d; display:flex; flex-direction:column; background:#161b22; overflow:hidden; transition:width .15s; }
126
+.chat-sidebar.collapsed { width:28px; }
127
+.chat-sidebar.collapsed .chan-join,.chat-sidebar.collapsed .chan-list { display:none; }
128
+.sidebar-head { padding:8px 12px; font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:#8b949e; border-bottom:1px solid #30363d; flex-shrink:0; display:flex; align-items:center; gap:4px; }
129
+.sidebar-toggle { margin-left:auto; background:none; border:none; color:#8b949e; cursor:pointer; font-size:14px; padding:0 2px; line-height:1; }
130
+.sidebar-toggle:hover { color:#e6edf3; }
131
+.sidebar-resize { width:4px; flex-shrink:0; cursor:col-resize; background:transparent; transition:background .1s; z-index:10; }
132
+.sidebar-resize:hover,.sidebar-resize.dragging { background:#58a6ff55; }
133
+.chan-join { display:flex; gap:5px; padding:7px 9px; border-bottom:1px solid #21262d; flex-shrink:0; }
134
+.chan-join input { flex:1; padding:4px 7px; font-size:12px; }
135
+.chan-list { flex:1; overflow-y:auto; }
136
+.chan-item { padding:7px 14px; font-size:13px; cursor:pointer; color:#8b949e; border-bottom:1px solid #21262d; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
137
+.chan-item:hover { background:#1c2128; color:#e6edf3; }
138
+.chan-item.active { background:#1f6feb22; color:#58a6ff; border-left:2px solid #58a6ff; padding-left:12px; }
139
+.chat-main { flex:1; display:flex; flex-direction:column; min-width:0; }
140
+.chat-topbar { padding:9px 16px; border-bottom:1px solid #30363d; display:flex; align-items:center; gap:10px; flex-shrink:0; background:#161b22; font-size:13px; }
141
+.chat-ch-name { font-weight:600; color:#58a6ff; }
142
+.stream-badge { font-size:11px; color:#8b949e; margin-left:auto; }
143
+.chat-msgs { flex:1; overflow-y:auto; padding:10px 16px; display:flex; flex-direction:column; gap:1px; }
144
+.msg-row { display:flex; gap:10px; font-size:13px; line-height:1.6; padding:1px 0; }
145
+.msg-time { color:#8b949e; font-size:11px; flex-shrink:0; padding-top:3px; min-width:40px; }
146
+.msg-nick { font-weight:600; flex-shrink:0; min-width:90px; text-align:right; }
147
+.msg-grouped .msg-nick { visibility:hidden; }
148
+.msg-grouped .msg-time { color:transparent; }
149
+.msg-grouped:hover .msg-time { color:#8b949e; transition:color .1s; }
150
+.chat-nicklist { width:148px; min-width:0; flex-shrink:0; border-left:1px solid #30363d; display:flex; flex-direction:column; background:#161b22; overflow-y:auto; overflow-x:hidden; transition:width .15s; }
151
+.chat-nicklist.collapsed { width:28px; overflow:hidden; }
152
+.chat-nicklist.collapsed #nicklist-users { display:none; }
153
+.nicklist-head { padding:8px 12px; font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:#8b949e; border-bottom:1px solid #30363d; flex-shrink:0; display:flex; align-items:center; gap:4px; }
154
+.nicklist-nick { padding:5px 12px; font-size:12px; color:#8b949e; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
155
+.nicklist-nick.is-bot { color:#58a6ff; }
156
+.nicklist-nick::before { content:"● "; font-size:8px; vertical-align:middle; }
157
+.chat-new-banner { align-self:center; margin:4px auto 0; background:#1f6feb; color:#fff; border-radius:20px; padding:3px 14px; font-size:12px; cursor:pointer; display:inline-block; white-space:nowrap; }
158
+/* login screen */
159
+.login-screen { position:fixed; inset:0; background:#0d1117; z-index:200; display:flex; align-items:center; justify-content:center; flex-direction:column; }
160
+.login-box { width:340px; }
161
+.login-brand { text-align:center; margin-bottom:24px; }
162
+.login-brand h1 { font-size:22px; color:#58a6ff; letter-spacing:.05em; }
163
+.login-brand p { color:#8b949e; font-size:13px; margin-top:6px; }
164
+/* unread badge on chat tab */
165
+.nav-tab[data-unread]::after { content:attr(data-unread); background:#f85149; color:#fff; border-radius:999px; padding:1px 5px; font-size:10px; margin-left:5px; vertical-align:middle; }
166
+.msg-text { color:#e6edf3; word-break:break-word; }
167
+.chat-input { padding:9px 13px; border-top:1px solid #30363d; display:flex; gap:7px; flex-shrink:0; background:#161b22; }
168
+
169
+/* channels tab */
170
+.chan-card { display:flex; align-items:center; gap:12px; padding:12px 16px; border-bottom:1px solid #21262d; }
171
+.chan-card:last-child { border-bottom:none; }
172
+.chan-card:hover { background:#1c2128; }
173
+.chan-name { font-size:14px; font-weight:600; color:#58a6ff; }
174
+.chan-meta { font-size:12px; color:#8b949e; }
175
+
176
+/* settings */
177
+.setting-row { display:flex; align-items:center; gap:12px; padding:14px 0; border-bottom:1px solid #21262d; }
178
+.setting-row:last-child { border-bottom:none; }
179
+.setting-label { min-width:160px; font-size:13px; color:#c9d1d9; }
180
+.setting-desc { font-size:12px; color:#8b949e; flex:1; }
181
+.setting-val { font-size:12px; font-family:inherit; color:#a5d6ff; background:#0d1117; border:1px solid #30363d; border-radius:4px; padding:4px 10px; }
182
+
183
+/* modal */
184
+.modal-overlay { display:none; position:fixed; inset:0; background:#0d111788; z-index:100; align-items:center; justify-content:center; }
185
+.modal-overlay.open { display:flex; }
186
+.modal { background:#161b22; border:1px solid #30363d; border-radius:10px; padding:24px; width:480px; max-width:95vw; }
187
+.modal h3 { font-size:15px; margin-bottom:16px; }
188
+.modal .btn-row { display:flex; justify-content:flex-end; gap:8px; margin-top:16px; }
189
+/* charts */
190
+.charts-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:16px; }
191
+.chart-card { background:#161b22; border:1px solid #30363d; border-radius:8px; padding:14px 16px; }
192
+.chart-label { font-size:11px; color:#8b949e; text-transform:uppercase; letter-spacing:.06em; margin-bottom:10px; display:flex; align-items:center; gap:6px; }
193
+.chart-label .val { margin-left:auto; font-size:13px; color:#e6edf3; font-weight:600; letter-spacing:0; text-transform:none; }
194
+canvas { display:block; width:100% !important; }
195
+.bridge-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:12px; }
82196
</style>
197
+<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
83198
</head>
84199
<body>
200
+
201
+<!-- login screen — shown when unauthenticated -->
202
+<div class="login-screen" id="login-screen" style="display:none">
203
+ <div class="login-box">
204
+ <div class="login-brand">
205
+ <h1>⬡ scuttlebot</h1>
206
+ <p>agent coordination backplane</p>
207
+ </div>
208
+ <div class="card">
209
+ <div class="card-body">
210
+ <form id="login-form" onsubmit="handleLogin(event)" style="gap:12px">
211
+ <div>
212
+ <label>username</label>
213
+ <input type="text" id="login-username" autocomplete="username">
214
+ </div>
215
+ <div>
216
+ <label>password</label>
217
+ <input type="password" id="login-password" autocomplete="current-password">
218
+ </div>
219
+ <div id="login-error" style="display:none"></div>
220
+ <button type="submit" class="primary" style="width:100%;margin-top:4px" id="login-btn">sign in</button>
221
+ </form>
222
+ <details style="margin-top:16px;border-top:1px solid #21262d;padding-top:14px">
223
+ <summary style="font-size:12px;color:#8b949e;cursor:pointer;user-select:none">use API token instead</summary>
224
+ <div style="display:flex;gap:8px;margin-top:10px">
225
+ <input type="text" id="token-login-input" placeholder="paste API token" style="flex:1;font-size:12px" autocomplete="off" spellcheck="false">
226
+ <button class="sm primary" onclick="saveTokenLogin()">apply</button>
227
+ </div>
228
+ <div class="hint" style="margin-top:4px">Token is printed to stderr at startup.</div>
229
+ </details>
230
+ </div>
231
+ </div>
232
+ <p style="text-align:center;font-size:11px;color:#6e7681;margin-top:14px">
233
+ <a href="https://scuttlebot.dev" target="_blank" rel="noopener" style="color:#58a6ff;text-decoration:none">ScuttleBot</a> · Powered by <a href="https://weareconflict.com" target="_blank" rel="noopener" style="color:#58a6ff;text-decoration:none">CONFLICT</a>
234
+ </p>
235
+ </div>
236
+</div>
85237
86238
<header>
87
- <h1>⬡ scuttlebot</h1>
88
- <span class="tagline">agent coordination backplane</span>
89
- <div class="spacer"></div>
90
- <div class="token-badge">
91
- <span>token:</span>
92
- <code id="token-display">not set</code>
93
- <button class="small" onclick="openTokenModal()">set</button>
239
+ <div class="brand">
240
+ <h1>⬡ scuttlebot</h1>
241
+ <span>agent coordination backplane</span>
242
+ </div>
243
+ <nav>
244
+ <div class="nav-tab active" id="tab-status" onclick="switchTab('status')">◈ status</div>
245
+ <div class="nav-tab" id="tab-users" onclick="switchTab('users')">◉ users</div>
246
+ <div class="nav-tab" id="tab-agents" onclick="switchTab('agents')">◎ agents</div>
247
+ <div class="nav-tab" id="tab-channels" onclick="switchTab('channels')">◎ channels</div>
248
+ <div class="nav-tab" id="tab-chat" onclick="switchTab('chat')">◌ chat</div>
249
+ <div class="nav-tab" id="tab-ai" onclick="switchTab('ai')">✦ ai</div>
250
+ <div class="nav-tab" id="tab-settings" onclick="switchTab('settings')">⚙ settings</div>
251
+ </nav>
252
+ <div class="header-right">
253
+ <span id="header-user-display" style="font-size:12px;color:#8b949e"></span>
254
+ <button class="sm" onclick="logout()">sign out</button>
94255
</div>
95256
</header>
96257
97
-<main>
98
- <div id="no-token-banner" class="alert info" style="display:none">
99
- <span class="icon">ℹ</span>
100
- <span>Paste your API token to continue. It was printed to stderr when scuttlebot started:<br><code style="color:#a5d6ff">level=INFO msg="api token" token=...</code></span>
101
- </div>
102
-
103
- <!-- Status -->
104
- <div class="card">
105
- <div class="card-header">
106
- <span class="dot green" id="status-dot"></span>
107
- <h2>status</h2>
108
- </div>
109
- <div class="card-body">
110
- <div class="status-grid" id="status-grid">
111
- <div class="stat"><div class="label">state</div><div class="value" id="stat-status">—</div></div>
112
- <div class="stat"><div class="label">uptime</div><div class="value" id="stat-uptime">—</div></div>
113
- <div class="stat"><div class="label">agents</div><div class="value" id="stat-agents">—</div></div>
114
- <div class="stat"><div class="label">started</div><div class="value" style="font-size:13px" id="stat-started">—</div><div class="sub" id="stat-started-rel"></div></div>
115
- </div>
116
- <div id="status-error" style="margin-top:12px;display:none"></div>
117
- </div>
118
- </div>
119
-
120
- <!-- Agents -->
121
- <div class="card">
122
- <div class="card-header">
123
- <h2>agents</h2>
124
- <span class="badge" id="agent-count">0</span>
125
- <div class="spacer"></div>
126
- <button class="small" onclick="loadAgents()">↻ refresh</button>
127
- </div>
128
- <div class="card-body" style="padding:0">
129
- <div id="agents-container"></div>
130
- </div>
131
- </div>
132
-
133
- <!-- Register -->
134
- <div class="card">
135
- <div class="card-header"><h2>register agent</h2></div>
136
- <div class="card-body">
137
- <form id="register-form" onsubmit="handleRegister(event)">
138
- <div class="form-row">
139
- <div>
140
- <label>nick *</label>
141
- <input type="text" id="reg-nick" placeholder="my-agent-01" required>
142
- </div>
143
- <div>
144
- <label>type</label>
145
- <select id="reg-type">
146
- <option value="operator">operator — human, +o + full permissions</option>
147
- <option value="worker">worker — gets +v in channels</option>
148
- <option value="orchestrator">orchestrator — gets +o in channels</option>
149
- <option value="observer">observer — read-only</option>
150
- </select>
151
- </div>
152
- </div>
153
- <div>
154
- <label>channels</label>
155
- <input type="text" id="reg-channels" placeholder="#fleet, #ops, #project.foo">
156
- <div class="hint">comma-separated; must start with #</div>
157
- </div>
158
- <div>
159
- <label>permissions</label>
160
- <input type="text" id="reg-permissions" placeholder="task.create, task.update">
161
- <div class="hint">comma-separated message types this agent is allowed to send</div>
162
- </div>
163
- <div id="register-result" style="display:none"></div>
164
- <div style="display:flex;justify-content:flex-end">
165
- <button type="submit" class="primary">register</button>
166
- </div>
167
- </form>
168
- </div>
169
- </div>
170
-
171
- <!-- Chat -->
172
- <div class="card" id="chat-card" style="display:none">
173
- <div class="card-header">
174
- <h2>chat</h2>
175
- <span class="badge" id="chat-channel-badge" style="display:none"></span>
176
- <div class="spacer"></div>
177
- <span id="chat-stream-status" style="font-size:11px;color:#8b949e"></span>
178
- </div>
179
- <div style="display:flex;height:440px">
180
- <div id="chat-channel-list" style="width:140px;border-right:1px solid #30363d;overflow-y:auto;flex-shrink:0;padding:8px 0;display:flex;flex-direction:column">
181
- <div style="padding:6px 12px;font-size:11px;text-transform:uppercase;letter-spacing:0.06em;color:#8b949e">channels</div>
182
- <div style="padding:6px 8px;border-bottom:1px solid #21262d;display:flex;gap:4px">
183
- <input type="text" id="join-channel-input" placeholder="#channel" style="flex:1;font-size:11px;padding:3px 6px" autocomplete="off">
184
- <button class="small" onclick="joinChannel()" style="padding:3px 6px;font-size:11px">+</button>
185
- </div>
186
- </div>
187
- <div style="display:flex;flex-direction:column;flex:1;min-width:0">
188
- <div id="chat-messages" style="flex:1;overflow-y:auto;padding:12px 16px;display:flex;flex-direction:column;gap:2px">
189
- <div class="empty" id="chat-placeholder">select a channel to view messages</div>
190
- </div>
191
- <div style="padding:10px 14px;border-top:1px solid #30363d;display:flex;gap:8px;align-items:center">
192
- <input type="text" id="chat-nick-input" placeholder="your nick" style="width:110px;flex-shrink:0" autocomplete="off">
193
- <input type="text" id="chat-text-input" placeholder="type a message…" style="flex:1" autocomplete="off">
194
- <button class="primary small" id="chat-send-btn" onclick="sendChatMessage()">send</button>
195
- </div>
196
- </div>
197
- </div>
198
- </div>
199
-</main>
200
-
201
-<!-- Token modal -->
202
-<div class="modal-overlay" id="token-modal">
203
- <div class="modal">
204
- <h3>set API token</h3>
205
- <p style="font-size:13px;color:#8b949e;margin-bottom:14px">The token is printed to stderr when scuttlebot starts:<br><code style="color:#a5d6ff">level=INFO msg="api token" token=&lt;value&gt;</code></p>
206
- <label>token</label>
207
- <input type="text" id="token-input" placeholder="paste token here" autocomplete="off" spellcheck="false">
208
- <div class="btn-row">
209
- <button onclick="closeTokenModal()">cancel</button>
210
- <button class="primary" onclick="saveToken()">save</button>
211
- </div>
212
- </div>
213
-</div>
214
-
215
-<script>
216
-// --- token management ---
217
-function getToken() { return localStorage.getItem('scuttlebot_token') || ''; }
218
-function setToken(t) {
219
- localStorage.setItem('scuttlebot_token', t);
220
- updateTokenDisplay();
221
-}
222
-function updateTokenDisplay() {
223
- const t = getToken();
224
- const el = document.getElementById('token-display');
225
- const banner = document.getElementById('no-token-banner');
226
- if (t) {
227
- el.textContent = t.slice(0, 8) + '…' + t.slice(-4);
228
- banner.style.display = 'none';
229
- } else {
230
- el.textContent = 'not set';
231
- banner.style.display = 'flex';
232
- }
233
-}
234
-function openTokenModal() {
235
- document.getElementById('token-input').value = getToken();
236
- document.getElementById('token-modal').classList.add('open');
237
- setTimeout(() => document.getElementById('token-input').focus(), 50);
238
-}
239
-function closeTokenModal() { document.getElementById('token-modal').classList.remove('open'); }
240
-function saveToken() {
241
- const v = document.getElementById('token-input').value.trim();
242
- if (v) { setToken(v); closeTokenModal(); loadAll(); }
243
-}
244
-document.getElementById('token-modal').addEventListener('click', function(e) {
245
- if (e.target === this) closeTokenModal();
246
-});
247
-document.addEventListener('keydown', function(e) {
248
- if (e.key === 'Escape') closeTokenModal();
249
-});
250
-
251
-// --- API ---
252
-async function api(method, path, body) {
253
- const token = getToken();
254
- const opts = { method, headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' } };
255
- if (body !== undefined) opts.body = JSON.stringify(body);
256
- const res = await fetch(path, opts);
258
+<!-- STATUS -->
259
+<div class="tab-pane active" id="pane-status">
260
+ <div class="pane-inner">
261
+ <div id="no-token-banner" class="alert info" style="display:none">
262
+ <span class="icon">ℹ</span>
263
+ <span>Paste your API token to continue — printed to stderr at startup: <code style="color:#a5d6ff">level=INFO msg="api token" token=…</code></span>
264
+ </div>
265
+
266
+ <!-- server status card -->
267
+ <div class="card" id="card-status">
268
+ <div class="card-header" onclick="toggleCard('card-status',event)">
269
+ <span class="dot green" id="status-dot"></span><h2>server status</h2>
270
+ <span class="collapse-icon">▾</span>
271
+ <div class="spacer"></div>
272
+ <span style="font-size:11px;color:#8b949e" id="metrics-updated"></span>
273
+ <button class="sm" onclick="loadStatus()" title="refresh">↻</button>
274
+ </div>
275
+ <div class="card-body">
276
+ <div class="stat-grid">
277
+ <div class="stat"><div class="lbl">state</div><div class="val" id="stat-status">—</div></div>
278
+ <div class="stat"><div class="lbl">uptime</div><div class="val" id="stat-uptime">—</div></div>
279
+ <div class="stat"><div class="lbl">agents</div><div class="val" id="stat-agents">—</div></div>
280
+ <div class="stat"><div class="lbl">started</div><div class="val" style="font-size:13px" id="stat-started">—</div><div class="sub" id="stat-started-rel"></div></div>
281
+ </div>
282
+ <div id="status-error" style="margin-top:12px;display:none"></div>
283
+ </div>
284
+ </div>
285
+
286
+ <!-- runtime -->
287
+ <div class="card" id="card-runtime">
288
+ <div class="card-header" onclick="toggleCard('card-runtime',event)"><h2>runtime</h2><span class="collapse-icon">▾</span></div>
289
+ <div class="card-body" style="display:flex;flex-direction:column;gap:16px">
290
+ <div class="stat-grid">
291
+ <div class="stat"><div class="lbl">goroutines</div><div class="val" id="stat-goroutines">—</div></div>
292
+ <div class="stat"><div class="lbl">heap alloc</div><div class="val" id="stat-heap">—</div></div>
293
+ <div class="stat"><div class="lbl">heap sys</div><div class="val" id="stat-heapsys">—</div></div>
294
+ <div class="stat"><div class="lbl">GC runs</div><div class="val" id="stat-gc">—</div></div>
295
+ </div>
296
+ <div class="charts-grid">
297
+ <div class="chart-card">
298
+ <div class="chart-label">heap alloc <span class="val" id="chart-heap-val">—</span></div>
299
+ <canvas id="chart-heap" height="80"></canvas>
300
+ </div>
301
+ <div class="chart-card">
302
+ <div class="chart-label">goroutines <span class="val" id="chart-goroutines-val">—</span></div>
303
+ <canvas id="chart-goroutines" height="80"></canvas>
304
+ </div>
305
+ <div class="chart-card">
306
+ <div class="chart-label">messages total <span class="val" id="chart-messages-val">—</span></div>
307
+ <canvas id="chart-messages" height="80"></canvas>
308
+ </div>
309
+ </div>
310
+ </div>
311
+ </div>
312
+
313
+ <!-- bridge -->
314
+ <div class="card" id="bridge-card" style="display:none">
315
+ <div class="card-header" onclick="toggleCard('bridge-card',event)"><h2>bridge</h2><span class="collapse-icon">▾</span></div>
316
+ <div class="card-body">
317
+ <div class="bridge-grid">
318
+ <div class="stat"><div class="lbl">channels</div><div class="val" id="stat-bridge-channels">—</div></div>
319
+ <div class="stat"><div class="lbl">messages total</div><div class="val" id="stat-bridge-msgs">—</div></div>
320
+ <div class="stat"><div class="lbl">active streams</div><div class="val" id="stat-bridge-subs">—</div></div>
321
+ </div>
322
+ </div>
323
+ </div>
324
+
325
+ <!-- registry -->
326
+ <div class="card" id="card-registry">
327
+ <div class="card-header" onclick="toggleCard('card-registry',event)"><h2>registry</h2><span class="collapse-icon">▾</span></div>
328
+ <div class="card-body">
329
+ <div class="stat-grid">
330
+ <div class="stat"><div class="lbl">total</div><div class="val" id="stat-reg-total">—</div></div>
331
+ <div class="stat"><div class="lbl">active</div><div class="val" id="stat-reg-active">—</div></div>
332
+ <div class="stat"><div class="lbl">revoked</div><div class="val" id="stat-reg-revoked">—</div></div>
333
+ </div>
334
+ </div>
335
+ </div>
336
+
337
+ </div>
338
+</div>
339
+
340
+<!-- USERS -->
341
+<div class="tab-pane" id="pane-users">
342
+ <div class="filter-bar">
343
+ <input type="text" id="user-search" placeholder="search by nick or channel…" oninput="renderUsersTable()" style="max-width:320px">
344
+ <div class="spacer"></div>
345
+ <span class="badge" id="user-count" style="margin-right:4px">0</span>
346
+ <button class="sm" onclick="loadAgents()">↻ refresh</button>
347
+ <button class="sm" onclick="openAdoptDrawer()">adopt existing user</button>
348
+ <button class="sm primary" onclick="openRegisterUserDrawer()">+ register user</button>
349
+ </div>
350
+ <div style="flex:1;overflow-y:auto">
351
+ <div id="users-container"></div>
352
+ </div>
353
+</div>
354
+
355
+<!-- AGENTS -->
356
+<div class="tab-pane" id="pane-agents">
357
+ <div class="filter-bar">
358
+ <input type="text" id="agent-search" placeholder="search by nick, type, channel…" oninput="renderAgentTable()" style="max-width:320px">
359
+ <div class="spacer"></div>
360
+ <span class="badge" id="agent-count" style="margin-right:4px">0</span>
361
+ <button class="sm" onclick="loadAgents()">↻ refresh</button>
362
+ <button class="sm primary" onclick="openDrawer()">+ register agent</button>
363
+ </div>
364
+ <div style="flex:1;overflow-y:auto">
365
+ <div id="agents-container"></div>
366
+ </div>
367
+</div>
368
+
369
+<!-- CHANNELS -->
370
+<div class="tab-pane" id="pane-channels">
371
+ <div class="pane-inner">
372
+ <div class="card">
373
+ <div class="card-header">
374
+ <h2>channels</h2>
375
+ <span class="badge" id="chan-count">0</span>
376
+ <div class="spacer"></div>
377
+ <div style="display:flex;gap:6px;align-items:center">
378
+ <input type="text" id="quick-join-input" placeholder="#channel" style="width:160px;padding:5px 8px;font-size:12px" autocomplete="off">
379
+ <button class="sm primary" onclick="quickJoin()">join</button>
380
+ </div>
381
+ </div>
382
+ <div id="channels-list"><div class="empty">no channels joined yet — type a channel name above</div></div>
383
+ </div>
384
+ </div>
385
+</div>
386
+
387
+<!-- CHAT -->
388
+<div class="tab-pane" id="pane-chat">
389
+ <div class="chat-sidebar" id="chat-sidebar-left">
390
+ <div class="sidebar-head">
391
+ <span id="sidebar-left-label">channels</span>
392
+ <button class="sidebar-toggle" id="sidebar-left-toggle" title="collapse" onclick="toggleSidebar('left')">‹</button>
393
+ </div>
394
+ <div class="chan-join">
395
+ <input type="text" id="join-channel-input" placeholder="#general" autocomplete="off">
396
+ <button class="sm" onclick="joinChannel()">+</button>
397
+ </div>
398
+ <div class="chan-list" id="chan-list"></div>
399
+ </div>
400
+ <div class="sidebar-resize" id="resize-left" title="drag to resize"></div>
401
+ <div class="chat-main">
402
+ <div class="chat-topbar">
403
+ <span class="chat-ch-name" id="chat-ch-name">select a channel</span>
404
+ <div class="spacer"></div>
405
+ <span style="font-size:11px;color:#8b949e;margin-right:6px">chatting as</span>
406
+ <select id="chat-identity" style="width:140px;padding:3px 6px;font-size:12px" onchange="saveChatIdentity()">
407
+ <option value="">— pick a user —</option>
408
+ </select>
409
+ <span class="stream-badge" id="chat-stream-status" style="margin-left:8px"></span>
410
+ </div>
411
+ <div class="chat-msgs" id="chat-msgs">
412
+ <div class="empty" id="chat-placeholder">join a channel to start chatting</div>
413
+ </div>
414
+ <div class="chat-input">
415
+ <input type="text" id="chat-text-input" placeholder="type a message…" style="flex:1" autocomplete="off">
416
+ <button class="primary sm" id="chat-send-btn" onclick="sendMsg()">send</button>
417
+ </div>
418
+ </div>
419
+ <div class="sidebar-resize" id="resize-right" title="drag to resize"></div>
420
+ <div class="chat-nicklist" id="chat-nicklist">
421
+ <div class="nicklist-head">
422
+ <button class="sidebar-toggle" id="sidebar-right-toggle" title="collapse" onclick="toggleSidebar('right')">›</button>
423
+ <span id="sidebar-right-label">users</span>
424
+ </div>
425
+ <div id="nicklist-users"></div>
426
+ </div>
427
+</div>
428
+
429
+<!-- SETTINGS -->
430
+<div class="tab-pane" id="pane-settings">
431
+ <div class="pane-inner">
432
+
433
+ <!-- connection -->
434
+ <div class="card" id="card-connection">
435
+ <div class="card-header" style="cursor:default"><h2>connection</h2></div>
436
+ <div class="card-body">
437
+ <div class="setting-row">
438
+ <div class="setting-label">signed in as</div>
439
+ <div class="setting-desc">Current admin session.</div>
440
+ <code class="setting-val" id="settings-username-display">—</code>
441
+ <button class="sm danger" onclick="logout()">sign out</button>
442
+ </div>
443
+ <div class="setting-row">
444
+ <div class="setting-label">API endpoint</div>
445
+ <div class="setting-desc">REST API base URL.</div>
446
+ <code class="setting-val" id="settings-api-url"></code>
447
+ </div>
448
+ <div class="setting-row">
449
+ <div class="setting-label">IRC network</div>
450
+ <div class="setting-desc">Ergo IRC server address.</div>
451
+ <code class="setting-val">localhost:6667</code>
452
+ </div>
453
+ <div class="setting-row">
454
+ <div class="setting-label">MCP server</div>
455
+ <div class="setting-desc">Model Context Protocol endpoint.</div>
456
+ <code class="setting-val">localhost:8081</code>
457
+ </div>
458
+ </div>
459
+ </div>
460
+
461
+ <!-- admin accounts -->
462
+ <div class="card" id="card-admins">
463
+ <div class="card-header" onclick="toggleCard('card-admins',event)"><h2>admin accounts</h2><span class="collapse-icon">▾</span></div>
464
+ <div id="admins-list-container"></div>
465
+ <div class="card-body" style="border-top:1px solid #21262d">
466
+ <p style="font-size:12px;color:#8b949e;margin-bottom:12px">Add an admin account. Admins sign in at the login screen with username + password.</p>
467
+ <form id="add-admin-form" onsubmit="addAdmin(event)" style="flex-direction:row;align-items:flex-end;gap:10px;flex-wrap:wrap">
468
+ <div style="flex:1;min-width:130px"><label>username</label><input type="text" id="new-admin-username" autocomplete="off"></div>
469
+ <div style="flex:1;min-width:130px"><label>password</label><input type="password" id="new-admin-password" autocomplete="new-password"></div>
470
+ <button type="submit" class="primary sm" style="margin-bottom:1px">add admin</button>
471
+ </form>
472
+ <div id="add-admin-result" style="margin-top:10px"></div>
473
+ </div>
474
+ </div>
475
+
476
+ <!-- tls -->
477
+ <div class="card" id="card-tls">
478
+ <div class="card-header" onclick="toggleCard('card-tls',event)"><h2>TLS / SSL</h2><span class="collapse-icon">▾</span><div class="spacer"></div><span id="tls-badge" class="badge">loading…</span></div>
479
+ <div class="card-body">
480
+ <div id="tls-status-rows"></div>
481
+ <div class="alert info" style="margin-top:12px;font-size:12px">
482
+ <span class="icon">ℹ</span>
483
+ <span>TLS is configured in <code style="color:#a5d6ff">scuttlebot.yaml</code> under <code style="color:#a5d6ff">tls:</code>.
484
+ Set <code style="color:#a5d6ff">domain:</code> to enable Let's Encrypt. <code style="color:#a5d6ff">allow_insecure: true</code> keeps HTTP running alongside HTTPS.</span>
485
+ </div>
486
+ </div>
487
+ </div>
488
+
489
+ <!-- system behaviors -->
490
+ <div class="card" id="card-behaviors">
491
+ <div class="card-header" onclick="toggleCard('card-behaviors',event)">
492
+ <h2>system behaviors</h2><span class="collapse-icon">▾</span>
493
+ <div class="spacer"></div>
494
+ <button class="sm primary" onclick="savePolicies()">save</button>
495
+ </div>
496
+ <div class="card-body" style="padding:0">
497
+ <div id="behaviors-list"></div>
498
+ </div>
499
+ </div>
500
+
501
+ <!-- agent policy -->
502
+ <div class="card" id="card-agentpolicy">
503
+ <div class="card-header" onclick="toggleCard('card-agentpolicy',event)"><h2>agent policy</h2><span class="collapse-icon">▾</span><div class="spacer"></div><button class="sm primary" onclick="savePolicies()">save</button></div>
504
+ <div class="card-body">
505
+ <div class="setting-row">
506
+ <div class="setting-label">require check-in</div>
507
+ <div class="setting-desc">Agents must join a coordination channel before others.</div>
508
+ <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
509
+ <input type="checkbox" id="policy-checkin-enabled" onchange="toggleCheckinChannel()">
510
+ <span style="font-size:12px">enabled</span>
511
+ </label>
512
+ </div>
513
+ <div class="setting-row" id="policy-checkin-row" style="display:none">
514
+ <div class="setting-label">check-in channel</div>
515
+ <div class="setting-desc">Channel all agents must join first.</div>
516
+ <input type="text" id="policy-checkin-channel" placeholder="#coordination" style="width:180px;padding:4px 8px;font-size:12px">
517
+ </div>
518
+ <div class="setting-row">
519
+ <div class="setting-label">required channels</div>
520
+ <div class="setting-desc">Channels every agent is added to automatically.</div>
521
+ <input type="text" id="policy-required-channels" placeholder="#fleet, #alerts" style="width:220px;padding:4px 8px;font-size:12px">
522
+ </div>
523
+ </div>
524
+ </div>
525
+
526
+ <!-- bridge -->
527
+ <div class="card" id="card-bridgepolicy">
528
+ <div class="card-header" onclick="toggleCard('card-bridgepolicy',event)"><h2>web bridge</h2><span class="collapse-icon">▾</span><div class="spacer"></div><button class="sm primary" onclick="savePolicies()">save</button></div>
529
+ <div class="card-body">
530
+ <div class="setting-row">
531
+ <div class="setting-label">web user TTL</div>
532
+ <div class="setting-desc">How long HTTP-posted nicks stay visible in the channel user list after their last message.</div>
533
+ <div style="display:flex;align-items:center;gap:6px">
534
+ <input type="number" id="policy-bridge-web-user-ttl" placeholder="5" min="1" style="width:80px;padding:4px 8px;font-size:12px">
535
+ <span style="font-size:12px;color:#8b949e">minutes</span>
536
+ </div>
537
+ </div>
538
+ </div>
539
+ </div>
540
+
541
+ <!-- logging -->
542
+ <div class="card" id="card-logging">
543
+ <div class="card-header" onclick="toggleCard('card-logging',event)"><h2>message logging</h2><span class="collapse-icon">▾</span><div class="spacer"></div><button class="sm primary" onclick="savePolicies()">save</button></div>
544
+ <div class="card-body">
545
+ <div class="setting-row">
546
+ <div class="setting-label">enabled</div>
547
+ <div class="setting-desc">Write every channel message to disk.</div>
548
+ <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
549
+ <input type="checkbox" id="policy-logging-enabled" onchange="toggleLogOptions()">
550
+ <span style="font-size:12px">enabled</span>
551
+ </label>
552
+ </div>
553
+ <div id="policy-log-options" style="display:none">
554
+ <div class="setting-row">
555
+ <div class="setting-label">log directory</div>
556
+ <div class="setting-desc">Directory to write log files into.</div>
557
+ <input type="text" id="policy-log-dir" placeholder="./data/logs" style="width:280px;padding:4px 8px;font-size:12px">
558
+ </div>
559
+ <div class="setting-row">
560
+ <div class="setting-label">format</div>
561
+ <div class="setting-desc">Output format for log lines.</div>
562
+ <select id="policy-log-format" style="width:160px;padding:4px 8px;font-size:12px">
563
+ <option value="jsonl">JSON Lines (.jsonl)</option>
564
+ <option value="csv">CSV (.csv)</option>
565
+ <option value="text">Plain text (.log)</option>
566
+ </select>
567
+ </div>
568
+ <div class="setting-row">
569
+ <div class="setting-label">rotation</div>
570
+ <div class="setting-desc">When to start a new log file.</div>
571
+ <select id="policy-log-rotation" style="width:160px;padding:4px 8px;font-size:12px" onchange="toggleRotationOptions()">
572
+ <option value="none">None</option>
573
+ <option value="daily">Daily</option>
574
+ <option value="weekly">Weekly</option>
575
+ <option value="monthly">Monthly</option>
576
+ <option value="yearly">Yearly</option>
577
+ <option value="size">By size</option>
578
+ </select>
579
+ </div>
580
+ <div class="setting-row" id="policy-log-size-row" style="display:none">
581
+ <div class="setting-label">max file size</div>
582
+ <div class="setting-desc">Rotate when file reaches this size.</div>
583
+ <div style="display:flex;align-items:center;gap:6px">
584
+ <input type="number" id="policy-log-max-size" placeholder="100" min="1" style="width:80px;padding:4px 8px;font-size:12px">
585
+ <span style="font-size:12px;color:#8b949e">MiB</span>
586
+ </div>
587
+ </div>
588
+ <div class="setting-row">
589
+ <div class="setting-label">per-channel files</div>
590
+ <div class="setting-desc">Write a separate file for each channel.</div>
591
+ <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
592
+ <input type="checkbox" id="policy-log-per-channel">
593
+ <span style="font-size:12px">enabled</span>
594
+ </label>
595
+ </div>
596
+ <div class="setting-row">
597
+ <div class="setting-label">max age</div>
598
+ <div class="setting-desc">Delete rotated files older than N days. 0 = keep forever.</div>
599
+ <div style="display:flex;align-items:center;gap:6px">
600
+ <input type="number" id="policy-log-max-age" placeholder="0" min="0" style="width:80px;padding:4px 8px;font-size:12px">
601
+ <span style="font-size:12px;color:#8b949e">days</span>
602
+ </div>
603
+ </div>
604
+ </div>
605
+ </div>
606
+ </div>
607
+
608
+ <div id="policies-save-result" style="display:none"></div>
609
+
610
+ <!-- about -->
611
+ <div class="card">
612
+ <div class="card-header" style="cursor:default"><h2>about</h2></div>
613
+ <div class="card-body" style="font-size:13px;color:#8b949e;line-height:1.8">
614
+ <p><strong style="color:#e6edf3">ScuttleBot</strong> — agent coordination backplane over IRC.</p>
615
+ <p>Agents register, receive SASL credentials, and coordinate in IRC channels.</p>
616
+ <p>Everything is human observable: all activity is visible in the IRC channel log.</p>
617
+ <p style="margin-top:12px;font-size:11px;color:#6e7681">
618
+ Copyright &copy; 2026 CONFLICT LLC. All rights reserved.<br>
619
+ <a href="https://scuttlebot.dev" target="_blank" rel="noopener" style="color:#58a6ff;text-decoration:none">ScuttleBot</a> — Powered by <a href="https://weareconflict.com" target="_blank" rel="noopener" style="color:#58a6ff;text-decoration:none">CONFLICT</a>
620
+ </p>
621
+ </div>
622
+ </div>
623
+
624
+ </div>
625
+</div>
626
+
627
+<!-- AI -->
628
+<div class="tab-pane" id="pane-ai">
629
+ <div class="pane-inner">
630
+
631
+ <!-- LLM backends -->
632
+ <div class="card" id="card-ai-backends">
633
+ <div class="card-header" style="cursor:default">
634
+ <h2>LLM backends</h2>
635
+ <div class="spacer"></div>
636
+ <button class="sm" onclick="loadAI()">↺ refresh</button>
637
+ <button class="sm primary" onclick="openAddBackend()">+ add backend</button>
638
+ </div>
639
+ <div class="card-body" style="padding:0">
640
+ <div id="ai-backends-list" style="padding:16px">
641
+ <div class="empty-state">loading…</div>
642
+ </div>
643
+ </div>
644
+ </div>
645
+
646
+ <!-- add/edit backend form (hidden until opened) -->
647
+ <div class="card" id="card-ai-form" style="display:none">
648
+ <div class="card-header" style="cursor:default">
649
+ <h2 id="ai-form-title">add backend</h2>
650
+ <div class="spacer"></div>
651
+ <button class="sm" onclick="closeBackendForm()">✕ cancel</button>
652
+ </div>
653
+ <div class="card-body">
654
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px 16px">
655
+ <div>
656
+ <label>name *</label>
657
+ <input type="text" id="bf-name" placeholder="openai-main" autocomplete="off">
658
+ <div class="hint">unique identifier — used in oracle's backend field</div>
659
+ </div>
660
+ <div>
661
+ <label>backend type *</label>
662
+ <select id="bf-backend" onchange="onBackendTypeChange()">
663
+ <option value="">— select type —</option>
664
+ <optgroup label="Native APIs">
665
+ <option value="anthropic">anthropic</option>
666
+ <option value="gemini">gemini</option>
667
+ <option value="bedrock">bedrock</option>
668
+ <option value="ollama">ollama</option>
669
+ </optgroup>
670
+ <optgroup label="OpenAI-compatible">
671
+ <option value="openai">openai</option>
672
+ <option value="openrouter">openrouter</option>
673
+ <option value="together">together</option>
674
+ <option value="groq">groq</option>
675
+ <option value="fireworks">fireworks</option>
676
+ <option value="mistral">mistral</option>
677
+ <option value="ai21">ai21</option>
678
+ <option value="huggingface">huggingface</option>
679
+ <option value="deepseek">deepseek</option>
680
+ <option value="cerebras">cerebras</option>
681
+ <option value="xai">xai</option>
682
+ <option value="litellm">litellm (local)</option>
683
+ <option value="lmstudio">lm studio (local)</option>
684
+ <option value="jan">jan (local)</option>
685
+ <option value="localai">localai (local)</option>
686
+ <option value="vllm">vllm (local)</option>
687
+ <option value="anythingllm">anythingllm (local)</option>
688
+ </optgroup>
689
+ </select>
690
+ </div>
691
+
692
+ <!-- shown for non-bedrock backends -->
693
+ <div id="bf-apikey-row">
694
+ <label>API key</label>
695
+ <input type="password" id="bf-apikey" placeholder="sk-…" autocomplete="new-password">
696
+ <div class="hint" id="bf-apikey-hint">Leave blank to use env var or instance role</div>
697
+ </div>
698
+
699
+ <!-- shown for ollama and OpenAI-compat local backends -->
700
+ <div id="bf-baseurl-row">
701
+ <label>base URL</label>
702
+ <input type="text" id="bf-baseurl" placeholder="http://localhost:11434" autocomplete="off">
703
+ <div class="hint">Override default endpoint for self-hosted backends</div>
704
+ </div>
705
+
706
+ <div>
707
+ <label>model</label>
708
+ <div style="display:flex;gap:6px;align-items:flex-start">
709
+ <div style="flex:1">
710
+ <select id="bf-model-select" onchange="onModelSelectChange()" style="width:100%">
711
+ <option value="">— select or load models —</option>
712
+ </select>
713
+ <input type="text" id="bf-model-custom" placeholder="model-id" autocomplete="off" style="display:none;margin-top:6px">
714
+ </div>
715
+ <button type="button" class="sm" id="bf-load-models-btn" onclick="loadLiveModels(this)" style="white-space:nowrap;margin-top:1px">↺ load models</button>
716
+ </div>
717
+ <div class="hint">Pick from list or load live from API. Leave blank to auto-select.</div>
718
+ </div>
719
+
720
+ <div style="display:flex;align-items:flex-end;gap:8px">
721
+ <label style="margin:0;cursor:pointer;display:flex;align-items:center;gap:6px">
722
+ <input type="checkbox" id="bf-default"> mark as default backend
723
+ </label>
724
+ </div>
725
+
726
+ <!-- Bedrock-specific fields -->
727
+ <div id="bf-bedrock-group" style="display:none;grid-column:1/-1">
728
+ <div style="font-size:12px;color:#8b949e;font-weight:500;text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px">AWS / Bedrock</div>
729
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px 16px">
730
+ <div>
731
+ <label>region *</label>
732
+ <input type="text" id="bf-region" placeholder="us-east-1" autocomplete="off">
733
+ </div>
734
+ <div>
735
+ <label>AWS key ID</label>
736
+ <input type="text" id="bf-aws-key-id" placeholder="AKIA… (or leave blank for IAM role)" autocomplete="off">
737
+ <div class="hint">Leave blank — scuttlebot will auto-detect IAM role (ECS/EC2/EKS)</div>
738
+ </div>
739
+ <div>
740
+ <label>AWS secret key</label>
741
+ <input type="password" id="bf-aws-secret" placeholder="(or leave blank for IAM role)" autocomplete="new-password">
742
+ </div>
743
+ </div>
744
+ </div>
745
+
746
+ <!-- allow/block filters -->
747
+ <div style="grid-column:1/-1">
748
+ <div style="font-size:12px;color:#8b949e;font-weight:500;text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px">Model filters (regex, one per line)</div>
749
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px 16px">
750
+ <div>
751
+ <label>allow list</label>
752
+ <textarea id="bf-allow" rows="3" placeholder="^gpt-4&#10;^claude-3" style="font-family:var(--font-mono);font-size:12px"></textarea>
753
+ <div class="hint">Only these models shown. Empty = all.</div>
754
+ </div>
755
+ <div>
756
+ <label>block list</label>
757
+ <textarea id="bf-block" rows="3" placeholder=".*-instruct$&#10;.*-preview$" style="font-family:var(--font-mono);font-size:12px"></textarea>
758
+ <div class="hint">Always hidden.</div>
759
+ </div>
760
+ </div>
761
+ </div>
762
+ </div>
763
+ <div id="ai-form-result" style="display:none;margin-top:12px"></div>
764
+ <div style="display:flex;justify-content:flex-end;gap:8px;margin-top:16px">
765
+ <button class="sm" onclick="closeBackendForm()">cancel</button>
766
+ <button class="sm primary" id="bf-submit-btn" onclick="submitBackendForm()">add backend</button>
767
+ </div>
768
+ </div>
769
+ </div>
770
+
771
+ <!-- supported backends reference -->
772
+ <div class="card" id="card-ai-supported">
773
+ <div class="card-header" onclick="toggleCard('card-ai-supported',event)"><h2>supported backends</h2><span class="collapse-icon">▾</span></div>
774
+ <div class="card-body" id="ai-supported-list">
775
+ <div class="empty-state">loading…</div>
776
+ </div>
777
+ </div>
778
+
779
+ <!-- config example -->
780
+ <div class="card" id="card-ai-example" style="display:none">
781
+ <div class="card-header" onclick="toggleCard('card-ai-example',event)"><h2>YAML example</h2><span class="collapse-icon">▾</span></div>
782
+ <div class="card-body">
783
+ <pre style="font-size:12px;color:#a5d6ff;background:#0d1117;border:1px solid #30363d;border-radius:6px;padding:12px;overflow-x:auto;white-space:pre">llm:
784
+ backends:
785
+ - name: openai-main
786
+ backend: openai
787
+ api_key: sk-...
788
+ model: gpt-4o-mini
789
+ block: [".*-instruct$"] # optional regex filter
790
+
791
+ - name: local-ollama
792
+ backend: ollama
793
+ base_url: http://localhost:11434
794
+ model: llama3.2
795
+ default: true
796
+
797
+ - name: anthropic-claude
798
+ backend: anthropic
799
+ api_key: sk-ant-...
800
+ model: claude-3-5-sonnet-20241022
801
+
802
+ - name: bedrock-us
803
+ backend: bedrock
804
+ region: us-east-1
805
+ aws_key_id: AKIA...
806
+ aws_secret_key: ...
807
+ allow: ["^anthropic\\."] # only Anthropic models
808
+
809
+ - name: groq-fast
810
+ backend: groq
811
+ api_key: gsk_...</pre>
812
+ <p style="font-size:12px;color:#8b949e;margin-top:8px">
813
+ Reference a backend from oracle's behavior config using the <code>backend</code> key.
814
+ </p>
815
+ </div>
816
+ </div>
817
+
818
+ </div>
819
+</div>
820
+
821
+<!-- Register drawer -->
822
+<div class="drawer-overlay" id="drawer-overlay" onclick="closeDrawer()"></div>
823
+<div class="drawer" id="register-drawer">
824
+ <div class="drawer-header">
825
+ <h3>register agent</h3>
826
+ <div class="spacer"></div>
827
+ <button class="sm" onclick="closeDrawer()">✕</button>
828
+ </div>
829
+ <div class="drawer-body">
830
+ <form id="register-form" onsubmit="handleRegister(event)">
831
+ <div class="form-row">
832
+ <div>
833
+ <label>nick *</label>
834
+ <input type="text" id="reg-nick" placeholder="my-agent-01" required autocomplete="off">
835
+ </div>
836
+ <div>
837
+ <label>type</label>
838
+ <select id="reg-type">
839
+ <option value="worker" selected>worker — +v</option>
840
+ <option value="orchestrator">orchestrator — +o</option>
841
+ <option value="observer">observer — read only</option>
842
+ </select>
843
+ </div>
844
+ </div>
845
+ <div>
846
+ <label>channels</label>
847
+ <input type="text" id="reg-channels" placeholder="#fleet, #ops, #project.foo" autocomplete="off">
848
+ <div class="hint">comma-separated; must start with #</div>
849
+ </div>
850
+ <div>
851
+ <label>permissions</label>
852
+ <input type="text" id="reg-permissions" placeholder="task.create, task.update" autocomplete="off">
853
+ <div class="hint">comma-separated message types this agent may send</div>
854
+ </div>
855
+ <div id="register-result" style="display:none"></div>
856
+ <div style="display:flex;justify-content:flex-end;gap:8px">
857
+ <button type="button" onclick="closeDrawer()">cancel</button>
858
+ <button type="submit" class="primary">register</button>
859
+ </div>
860
+ </form>
861
+ </div>
862
+</div>
863
+
864
+<!-- Register user drawer (operator with fresh credentials) -->
865
+<div class="drawer-overlay" id="register-user-overlay" onclick="closeRegisterUserDrawer()"></div>
866
+<div class="drawer" id="register-user-drawer">
867
+ <div class="drawer-header">
868
+ <h3>register user</h3>
869
+ <div class="spacer"></div>
870
+ <button class="sm" onclick="closeRegisterUserDrawer()">✕</button>
871
+ </div>
872
+ <div class="drawer-body">
873
+ <form id="register-user-form" onsubmit="handleRegisterUser(event)">
874
+ <div>
875
+ <label>nick *</label>
876
+ <input type="text" id="regu-nick" placeholder="alice" required autocomplete="off">
877
+ <div class="hint">new NickServ account will be created; credentials returned once</div>
878
+ </div>
879
+ <div>
880
+ <label>channels</label>
881
+ <input type="text" id="regu-channels" placeholder="#ops, #general" autocomplete="off">
882
+ <div class="hint">comma-separated</div>
883
+ </div>
884
+ <div id="register-user-result" style="display:none"></div>
885
+ <div style="display:flex;justify-content:flex-end;gap:8px">
886
+ <button type="button" onclick="closeRegisterUserDrawer()">cancel</button>
887
+ <button type="submit" class="primary">register</button>
888
+ </div>
889
+ </form>
890
+ </div>
891
+</div>
892
+
893
+<!-- Adopt user drawer (claim pre-existing NickServ account) -->
894
+<div class="drawer-overlay" id="adopt-overlay" onclick="closeAdoptDrawer()"></div>
895
+<div class="drawer" id="adopt-drawer">
896
+ <div class="drawer-header">
897
+ <h3>adopt existing user</h3>
898
+ <div class="spacer"></div>
899
+ <button class="sm" onclick="closeAdoptDrawer()">✕</button>
900
+ </div>
901
+ <div class="drawer-body">
902
+ <p style="font-size:12px;color:#8b949e;margin-bottom:16px">Adds a pre-existing NickServ account to the registry without changing its password. Use this for accounts already connected to IRC.</p>
903
+ <form id="adopt-form" onsubmit="handleAdopt(event)">
904
+ <div>
905
+ <label>nick *</label>
906
+ <input type="text" id="adopt-nick" placeholder="existing-irc-nick" required autocomplete="off">
907
+ </div>
908
+ <div>
909
+ <label>channels</label>
910
+ <input type="text" id="adopt-channels" placeholder="#ops, #general" autocomplete="off">
911
+ <div class="hint">comma-separated</div>
912
+ </div>
913
+ <div id="adopt-result" style="display:none"></div>
914
+ <div style="display:flex;justify-content:flex-end;gap:8px">
915
+ <button type="button" onclick="closeAdoptDrawer()">cancel</button>
916
+ <button type="submit" class="primary">adopt</button>
917
+ </div>
918
+ </form>
919
+ </div>
920
+</div>
921
+
922
+
923
+<script>
924
+// --- tabs ---
925
+const TAB_LOADERS = { status: loadStatus, users: loadAgents, agents: loadAgents, channels: loadChanTab, chat: () => { populateChatIdentity(); loadChannels(); }, ai: loadAI, settings: loadSettings };
926
+function switchTab(name) {
927
+ document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
928
+ document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
929
+ document.getElementById('tab-' + name).classList.add('active');
930
+ document.getElementById('pane-' + name).classList.add('active');
931
+ if (name === 'chat') {
932
+ _chatUnread = 0;
933
+ delete document.getElementById('tab-chat').dataset.unread;
934
+ }
935
+ if (TAB_LOADERS[name]) TAB_LOADERS[name]();
936
+}
937
+
938
+// --- auth ---
939
+function getToken() { return localStorage.getItem('sb_token') || ''; }
940
+function getUsername() { return localStorage.getItem('sb_username') || ''; }
941
+
942
+function showLoginScreen() {
943
+ document.getElementById('login-screen').style.display = 'flex';
944
+ setTimeout(() => document.getElementById('login-username')?.focus(), 80);
945
+}
946
+function hideLoginScreen() {
947
+ document.getElementById('login-screen').style.display = 'none';
948
+}
949
+
950
+function updateHeaderUser() {
951
+ const u = getUsername();
952
+ const t = getToken();
953
+ const label = u ? '@' + u : (t ? t.slice(0,8)+'…' : '');
954
+ document.getElementById('header-user-display').textContent = label;
955
+ const su = document.getElementById('settings-username-display');
956
+ if (su) su.textContent = u || 'token auth';
957
+ document.getElementById('settings-api-url').textContent = location.origin;
958
+ document.getElementById('no-token-banner').style.display = t ? 'none' : 'flex';
959
+}
960
+
961
+async function handleLogin(e) {
962
+ e.preventDefault();
963
+ const username = document.getElementById('login-username').value.trim();
964
+ const password = document.getElementById('login-password').value;
965
+ const btn = document.getElementById('login-btn');
966
+ const errEl = document.getElementById('login-error');
967
+ if (!username || !password) return;
968
+ btn.disabled = true; btn.textContent = 'signing in…';
969
+ errEl.style.display = 'none';
970
+ try {
971
+ const resp = await fetch('/login', {
972
+ method: 'POST',
973
+ headers: {'Content-Type':'application/json'},
974
+ body: JSON.stringify({username, password}),
975
+ });
976
+ const data = await resp.json().catch(() => ({}));
977
+ if (!resp.ok) throw new Error(data.error || 'Login failed');
978
+ localStorage.setItem('sb_token', data.token);
979
+ localStorage.setItem('sb_username', data.username || username);
980
+ hideLoginScreen();
981
+ updateHeaderUser();
982
+ loadAll();
983
+ } catch(err) {
984
+ errEl.style.display = 'block';
985
+ errEl.innerHTML = renderAlert('error', err.message);
986
+ btn.disabled = false; btn.textContent = 'sign in';
987
+ }
988
+}
989
+
990
+function saveTokenLogin() {
991
+ const v = document.getElementById('token-login-input').value.trim();
992
+ if (!v) return;
993
+ localStorage.setItem('sb_token', v);
994
+ localStorage.removeItem('sb_username');
995
+ hideLoginScreen();
996
+ updateHeaderUser();
997
+ loadAll();
998
+}
999
+
1000
+function logout() {
1001
+ localStorage.removeItem('sb_token');
1002
+ localStorage.removeItem('sb_username');
1003
+ location.reload();
1004
+}
1005
+
1006
+function initAuth() {
1007
+ if (!getToken()) { showLoginScreen(); return; }
1008
+ hideLoginScreen();
1009
+ updateHeaderUser();
1010
+ loadAll();
1011
+}
1012
+
1013
+document.addEventListener('keydown', e => { if(e.key==='Escape'){ closeDrawer(); closeRegisterUserDrawer(); closeAdoptDrawer(); } });
1014
+
1015
+// --- API ---
1016
+async function api(method, path, body) {
1017
+ const opts = { method, headers: { 'Authorization':'Bearer '+getToken(), 'Content-Type':'application/json' } };
1018
+ if (body !== undefined) opts.body = JSON.stringify(body);
1019
+ const res = await fetch(path, opts);
1020
+ if (res.status === 401) {
1021
+ localStorage.removeItem('sb_token');
1022
+ localStorage.removeItem('sb_username');
1023
+ showLoginScreen();
1024
+ throw new Error('Session expired — please sign in again');
1025
+ }
2571026
if (res.status === 204) return null;
2581027
const data = await res.json().catch(() => ({ error: res.statusText }));
2591028
if (!res.ok) throw Object.assign(new Error(data.error || res.statusText), { status: res.status });
2601029
return data;
2611030
}
262
-
2631031
function copyText(text, btn) {
264
- navigator.clipboard.writeText(text).then(() => {
265
- const orig = btn.textContent;
266
- btn.textContent = '✓';
267
- setTimeout(() => { btn.textContent = orig; }, 1200);
1032
+ navigator.clipboard.writeText(text).then(() => { const o=btn.textContent; btn.textContent='✓'; setTimeout(()=>{btn.textContent=o;},1200); });
1033
+}
1034
+
1035
+// --- charts ---
1036
+const CHART_POINTS = 60; // 5 min at 5s intervals
1037
+const chartData = {
1038
+ labels: Array(CHART_POINTS).fill(''),
1039
+ heap: Array(CHART_POINTS).fill(null),
1040
+ goroutines: Array(CHART_POINTS).fill(null),
1041
+ messages: Array(CHART_POINTS).fill(null),
1042
+};
1043
+let charts = {};
1044
+
1045
+function mkChart(id, label, color) {
1046
+ const ctx = document.getElementById(id).getContext('2d');
1047
+ return new Chart(ctx, {
1048
+ type: 'line',
1049
+ data: {
1050
+ labels: chartData.labels,
1051
+ datasets: [{
1052
+ label,
1053
+ data: chartData[id.replace('chart-','')],
1054
+ borderColor: color,
1055
+ backgroundColor: color+'22',
1056
+ borderWidth: 1.5,
1057
+ pointRadius: 0,
1058
+ tension: 0.3,
1059
+ fill: true,
1060
+ }],
1061
+ },
1062
+ options: {
1063
+ responsive: true,
1064
+ animation: false,
1065
+ plugins: { legend: { display: false } },
1066
+ scales: {
1067
+ x: { display: false },
1068
+ y: { display: true, grid: { color: '#21262d' }, ticks: { color: '#8b949e', font: { size: 10 }, maxTicksLimit: 4 } },
1069
+ },
1070
+ },
2681071
});
2691072
}
1073
+
1074
+function initCharts() {
1075
+ if (charts.heap) return;
1076
+ charts.heap = mkChart('chart-heap', 'heap', '#58a6ff');
1077
+ charts.goroutines = mkChart('chart-goroutines', 'goroutines', '#3fb950');
1078
+ charts.messages = mkChart('chart-messages', 'messages', '#d2a8ff');
1079
+}
1080
+
1081
+function fmtBytes(b) {
1082
+ if (b == null) return '—';
1083
+ if (b < 1024) return b+'B';
1084
+ if (b < 1048576) return (b/1024).toFixed(1)+'KB';
1085
+ return (b/1048576).toFixed(1)+'MB';
1086
+}
1087
+
1088
+function pushMetrics(m) {
1089
+ chartData.heap.push(m.runtime.heap_alloc_bytes/1048576);
1090
+ chartData.heap.shift();
1091
+ chartData.goroutines.push(m.runtime.goroutines);
1092
+ chartData.goroutines.shift();
1093
+ const msgs = m.bridge ? m.bridge.messages_total : null;
1094
+ chartData.messages.push(msgs);
1095
+ chartData.messages.shift();
1096
+
1097
+ // Reassign dataset data arrays (shared reference, Chart.js reads them directly).
1098
+ charts.heap.data.datasets[0].data = chartData.heap;
1099
+ charts.goroutines.data.datasets[0].data = chartData.goroutines;
1100
+ charts.messages.data.datasets[0].data = chartData.messages;
1101
+ charts.heap.update('none');
1102
+ charts.goroutines.update('none');
1103
+ charts.messages.update('none');
1104
+}
2701105
2711106
// --- status ---
2721107
async function loadStatus() {
2731108
try {
274
- const s = await api('GET', '/v1/status');
275
- document.getElementById('stat-status').innerHTML = '<span class="dot green"></span>' + s.status;
1109
+ const [s, m] = await Promise.all([
1110
+ api('GET', '/v1/status'),
1111
+ api('GET', '/v1/metrics'),
1112
+ ]);
1113
+
1114
+ // Status card.
1115
+ document.getElementById('stat-status').innerHTML = '<span class="dot green"></span>'+s.status;
2761116
document.getElementById('stat-uptime').textContent = s.uptime;
2771117
document.getElementById('stat-agents').textContent = s.agents;
278
- const started = new Date(s.started);
279
- document.getElementById('stat-started').textContent = started.toLocaleTimeString();
280
- document.getElementById('stat-started-rel').textContent = started.toLocaleDateString();
1118
+ const d = new Date(s.started);
1119
+ document.getElementById('stat-started').textContent = d.toLocaleTimeString();
1120
+ document.getElementById('stat-started-rel').textContent = d.toLocaleDateString();
2811121
document.getElementById('status-error').style.display = 'none';
282
- } catch (e) {
1122
+ document.getElementById('metrics-updated').textContent = 'updated '+new Date().toLocaleTimeString();
1123
+
1124
+ // Runtime card.
1125
+ document.getElementById('stat-goroutines').textContent = m.runtime.goroutines;
1126
+ document.getElementById('stat-heap').textContent = fmtBytes(m.runtime.heap_alloc_bytes);
1127
+ document.getElementById('stat-heapsys').textContent = fmtBytes(m.runtime.heap_sys_bytes);
1128
+ document.getElementById('stat-gc').textContent = m.runtime.gc_runs;
1129
+ document.getElementById('chart-heap-val').textContent = fmtBytes(m.runtime.heap_alloc_bytes);
1130
+ document.getElementById('chart-goroutines-val').textContent = m.runtime.goroutines;
1131
+ document.getElementById('chart-messages-val').textContent = m.bridge ? m.bridge.messages_total : '—';
1132
+
1133
+ // Bridge card.
1134
+ if (m.bridge) {
1135
+ document.getElementById('bridge-card').style.display = '';
1136
+ document.getElementById('stat-bridge-channels').textContent = m.bridge.channels;
1137
+ document.getElementById('stat-bridge-msgs').textContent = m.bridge.messages_total;
1138
+ document.getElementById('stat-bridge-subs').textContent = m.bridge.active_subscribers;
1139
+ }
1140
+
1141
+ // Registry card.
1142
+ document.getElementById('stat-reg-total').textContent = m.registry.total;
1143
+ document.getElementById('stat-reg-active').textContent = m.registry.active;
1144
+ document.getElementById('stat-reg-revoked').textContent = m.registry.revoked;
1145
+
1146
+ // Push to charts.
1147
+ initCharts();
1148
+ pushMetrics(m);
1149
+ } catch(e) {
2831150
document.getElementById('stat-status').innerHTML = '<span class="dot red"></span>error';
284
- const err = document.getElementById('status-error');
285
- err.style.display = 'block';
286
- err.innerHTML = renderAlert('error', e.message);
1151
+ const el = document.getElementById('status-error');
1152
+ el.style.display = 'block';
1153
+ el.innerHTML = renderAlert('error', e.message);
2871154
}
2881155
}
2891156
290
-// --- agents ---
1157
+let metricsTimer = null;
1158
+function startMetricsPoll() {
1159
+ if (metricsTimer) return;
1160
+ metricsTimer = setInterval(() => {
1161
+ if (document.getElementById('pane-status').classList.contains('active')) loadStatus();
1162
+ }, 5000);
1163
+}
1164
+
1165
+// --- agents + users (shared data) ---
1166
+let allAgents = [];
2911167
async function loadAgents() {
292
- const container = document.getElementById('agents-container');
2931168
try {
2941169
const data = await api('GET', '/v1/agents');
295
- const agents = data.agents || [];
296
- document.getElementById('agent-count').textContent = agents.length;
297
- if (agents.length === 0) {
298
- container.innerHTML = '<div class="empty">no agents registered yet</div>';
299
- return;
300
- }
301
- let rows = agents.map(a => {
302
- const channels = (a.config?.channels || []).map(c => `<span class="tag">${esc(c)}</span>`).join('');
303
- const perms = (a.config?.permissions || []).map(p => `<span class="tag">${esc(p)}</span>`).join('');
304
- const revoked = a.revoked_at ? '<span class="tag revoked">revoked</span>' : '';
305
- return `<tr>
306
- <td><strong>${esc(a.nick)}</strong></td>
307
- <td><span class="tag type-${a.type}">${esc(a.type)}</span>${revoked}</td>
308
- <td>${channels || '<span style="color:#8b949e">—</span>'}</td>
309
- <td>${perms || '<span style="color:#8b949e">—</span>'}</td>
310
- <td>${fmtTime(a.created_at)}</td>
311
- <td>
312
- <div class="actions">
313
- ${!a.revoked_at ? `<button class="small" onclick="rotateAgent('${esc(a.nick)}')">rotate</button>
314
- <button class="small danger" onclick="revokeAgent('${esc(a.nick)}')">revoke</button>` : ''}
315
- </div>
316
- </td>
317
- </tr>`;
318
- }).join('');
319
- container.innerHTML = `<table>
320
- <thead><tr><th>nick</th><th>type</th><th>channels</th><th>permissions</th><th>registered</th><th>actions</th></tr></thead>
321
- <tbody>${rows}</tbody>
322
- </table>`;
323
- } catch (e) {
324
- container.innerHTML = renderAlert('error', e.message);
325
- }
1170
+ allAgents = data.agents || [];
1171
+ renderUsersTable();
1172
+ renderAgentTable();
1173
+ populateChatIdentity();
1174
+ } catch(e) {
1175
+ const msg = '<div style="padding:16px">'+renderAlert('error', e.message)+'</div>';
1176
+ document.getElementById('agents-container').innerHTML = msg;
1177
+ document.getElementById('users-container').innerHTML = msg;
1178
+ }
1179
+}
1180
+
1181
+function renderTable(container, countEl, rows, emptyMsg, cols) {
1182
+ if (rows.length === 0) {
1183
+ document.getElementById(container).innerHTML = '<div class="empty">'+emptyMsg+'</div>';
1184
+ } else {
1185
+ const ths = cols.map(c=>`<th>${c}</th>`).join('');
1186
+ document.getElementById(container).innerHTML =
1187
+ `<table><thead><tr>${ths}</tr></thead><tbody>${rows.join('')}</tbody></table>`;
1188
+ }
1189
+ if (countEl) document.getElementById(countEl).textContent = rows.length;
1190
+}
1191
+
1192
+function renderUsersTable() {
1193
+ const q = (document.getElementById('user-search').value||'').toLowerCase();
1194
+ const users = allAgents.filter(a => a.type === 'operator' && (!q ||
1195
+ a.nick.toLowerCase().includes(q) ||
1196
+ (a.config?.channels||[]).some(c => c.toLowerCase().includes(q))));
1197
+ const rows = users.map(a => {
1198
+ const chs = (a.config?.channels||[]).map(c=>`<span class="tag ch">${esc(c)}</span>`).join('');
1199
+ const rev = a.revoked ? '<span class="tag revoked">revoked</span>' : '';
1200
+ return `<tr>
1201
+ <td><strong>${esc(a.nick)}</strong></td>
1202
+ <td><span class="tag type-operator">operator</span>${rev}</td>
1203
+ <td>${chs||'<span style="color:#8b949e">—</span>'}</td>
1204
+ <td style="white-space:nowrap">${fmtTime(a.created_at)}</td>
1205
+ <td><div class="actions">${!a.revoked?`
1206
+ <button class="sm" onclick="rotateAgent('${esc(a.nick)}')">rotate</button>
1207
+ <button class="sm danger" onclick="revokeAgent('${esc(a.nick)}')">revoke</button>`:``}
1208
+ <button class="sm danger" onclick="deleteAgent('${esc(a.nick)}')">delete</button></div></td>
1209
+ </tr>`;
1210
+ });
1211
+ const all = allAgents.filter(a => a.type === 'operator');
1212
+ const countTxt = all.length + (rows.length !== all.length ? ' / '+rows.length+' shown' : '');
1213
+ document.getElementById('user-count').textContent = countTxt;
1214
+ renderTable('users-container', null, rows,
1215
+ all.length ? 'no users match the filter' : 'no users registered yet',
1216
+ ['nick','type','channels','registered','']);
1217
+}
1218
+
1219
+function renderAgentTable() {
1220
+ const q = (document.getElementById('agent-search').value||'').toLowerCase();
1221
+ const bots = allAgents.filter(a => a.type !== 'operator');
1222
+ const agents = bots.filter(a => !q ||
1223
+ a.nick.toLowerCase().includes(q) ||
1224
+ a.type.toLowerCase().includes(q) ||
1225
+ (a.config?.channels||[]).some(c => c.toLowerCase().includes(q)) ||
1226
+ (a.config?.permissions||[]).some(p => p.toLowerCase().includes(q)));
1227
+ document.getElementById('agent-count').textContent = bots.length + (agents.length !== bots.length ? ' / '+agents.length+' shown' : '');
1228
+ const rows = agents.map(a => {
1229
+ const chs = (a.config?.channels||[]).map(c=>`<span class="tag ch">${esc(c)}</span>`).join('');
1230
+ const perms = (a.config?.permissions||[]).map(p=>`<span class="tag perm">${esc(p)}</span>`).join('');
1231
+ const rev = a.revoked ? '<span class="tag revoked">revoked</span>' : '';
1232
+ return `<tr>
1233
+ <td><strong>${esc(a.nick)}</strong></td>
1234
+ <td><span class="tag type-${a.type}">${esc(a.type)}</span>${rev}</td>
1235
+ <td>${chs||'<span style="color:#8b949e">—</span>'}</td>
1236
+ <td>${perms||'<span style="color:#8b949e">—</span>'}</td>
1237
+ <td style="white-space:nowrap">${fmtTime(a.created_at)}</td>
1238
+ <td><div class="actions">${!a.revoked?`
1239
+ <button class="sm" onclick="rotateAgent('${esc(a.nick)}')">rotate</button>
1240
+ <button class="sm danger" onclick="revokeAgent('${esc(a.nick)}')">revoke</button>`:``}
1241
+ <button class="sm danger" onclick="deleteAgent('${esc(a.nick)}')">delete</button></div></td>
1242
+ </tr>`;
1243
+ });
1244
+ renderTable('agents-container', null, rows,
1245
+ bots.length ? 'no agents match the filter' : 'no agents registered yet',
1246
+ ['nick','type','channels','permissions','registered','']);
3261247
}
3271248
3281249
async function revokeAgent(nick) {
329
- if (!confirm(`Revoke agent "${nick}"? This cannot be undone.`)) return;
330
- try {
331
- await api('POST', `/v1/agents/${nick}/revoke`);
332
- await loadAgents();
333
- await loadStatus();
334
- } catch(e) {
335
- alert('Revoke failed: ' + e.message);
336
- }
337
-}
338
-
1250
+ if (!confirm(`Revoke "${nick}"? This cannot be undone.`)) return;
1251
+ try { await api('POST', `/v1/agents/${nick}/revoke`); await loadAgents(); await loadStatus(); }
1252
+ catch(e) { alert('Revoke failed: '+e.message); }
1253
+}
1254
+async function deleteAgent(nick) {
1255
+ if (!confirm(`Delete "${nick}"? This permanently removes the agent from the registry.`)) return;
1256
+ try { await api('DELETE', `/v1/agents/${nick}`); await loadAgents(); await loadStatus(); }
1257
+ catch(e) { alert('Delete failed: '+e.message); }
1258
+}
3391259
async function rotateAgent(nick) {
3401260
try {
3411261
const creds = await api('POST', `/v1/agents/${nick}/rotate`);
1262
+ // Show result in whichever drawer is relevant.
3421263
showCredentials(nick, creds, null, 'rotate');
343
- } catch(e) {
344
- alert('Rotate failed: ' + e.message);
1264
+ openDrawer();
3451265
}
1266
+ catch(e) { alert('Rotate failed: '+e.message); }
1267
+}
1268
+
1269
+// --- users drawers ---
1270
+function openRegisterUserDrawer() {
1271
+ document.getElementById('register-user-overlay').classList.add('open');
1272
+ document.getElementById('register-user-drawer').classList.add('open');
1273
+ setTimeout(() => document.getElementById('regu-nick').focus(), 100);
1274
+}
1275
+function closeRegisterUserDrawer() {
1276
+ document.getElementById('register-user-overlay').classList.remove('open');
1277
+ document.getElementById('register-user-drawer').classList.remove('open');
1278
+}
1279
+function openAdoptDrawer() {
1280
+ document.getElementById('adopt-overlay').classList.add('open');
1281
+ document.getElementById('adopt-drawer').classList.add('open');
1282
+ setTimeout(() => document.getElementById('adopt-nick').focus(), 100);
1283
+}
1284
+function closeAdoptDrawer() {
1285
+ document.getElementById('adopt-overlay').classList.remove('open');
1286
+ document.getElementById('adopt-drawer').classList.remove('open');
1287
+}
1288
+
1289
+async function handleRegisterUser(e) {
1290
+ e.preventDefault();
1291
+ const nick = document.getElementById('regu-nick').value.trim();
1292
+ const channels = document.getElementById('regu-channels').value.split(',').map(s=>s.trim()).filter(Boolean);
1293
+ const resultEl = document.getElementById('register-user-result');
1294
+ resultEl.style.display = 'none';
1295
+ try {
1296
+ const res = await api('POST', '/v1/agents/register', { nick, type: 'operator', channels, permissions: [] });
1297
+ resultEl.style.display = 'block';
1298
+ const pass = res.credentials?.passphrase || '';
1299
+ resultEl.innerHTML = renderAlert('success',
1300
+ `<div><strong>Registered: ${esc(nick)}</strong>
1301
+ <div class="cred-box">
1302
+ <div class="cred-row"><span class="cred-key">nick</span><span class="cred-val">${esc(nick)}</span><button class="sm" onclick="copyText('${esc(nick)}',this)">copy</button></div>
1303
+ <div class="cred-row"><span class="cred-key">passphrase</span><span class="cred-val">${esc(pass)}</span><button class="sm" onclick="copyText('${esc(pass)}',this)">copy</button></div>
1304
+ </div>
1305
+ <div style="margin-top:8px;font-size:11px;color:#7ee787">⚠ Save the passphrase — shown once only.</div></div>`);
1306
+ document.getElementById('register-user-form').reset();
1307
+ await loadAgents(); await loadStatus();
1308
+ } catch(e) { resultEl.style.display='block'; resultEl.innerHTML=renderAlert('error', e.message); }
1309
+}
1310
+
1311
+async function handleAdopt(e) {
1312
+ e.preventDefault();
1313
+ const nick = document.getElementById('adopt-nick').value.trim();
1314
+ const channels = document.getElementById('adopt-channels').value.split(',').map(s=>s.trim()).filter(Boolean);
1315
+ const resultEl = document.getElementById('adopt-result');
1316
+ resultEl.style.display = 'none';
1317
+ try {
1318
+ await api('POST', `/v1/agents/${nick}/adopt`, { type: 'operator', channels, permissions: [] });
1319
+ resultEl.style.display = 'block';
1320
+ resultEl.innerHTML = renderAlert('success',
1321
+ `<strong>${esc(nick)}</strong> adopted as operator — existing IRC session and passphrase unchanged.`);
1322
+ document.getElementById('adopt-form').reset();
1323
+ await loadAgents(); await loadStatus();
1324
+ } catch(e) { resultEl.style.display='block'; resultEl.innerHTML=renderAlert('error', e.message); }
1325
+}
1326
+
1327
+// --- drawer ---
1328
+function openDrawer() {
1329
+ document.getElementById('drawer-overlay').classList.add('open');
1330
+ document.getElementById('register-drawer').classList.add('open');
1331
+ setTimeout(() => document.getElementById('reg-nick').focus(), 100);
1332
+}
1333
+function closeDrawer() {
1334
+ document.getElementById('drawer-overlay').classList.remove('open');
1335
+ document.getElementById('register-drawer').classList.remove('open');
3461336
}
3471337
3481338
// --- register ---
3491339
async function handleRegister(e) {
3501340
e.preventDefault();
351
- const nick = document.getElementById('reg-nick').value.trim();
352
- const type = document.getElementById('reg-type').value;
353
- const channelsRaw = document.getElementById('reg-channels').value;
354
- const permsRaw = document.getElementById('reg-permissions').value;
355
-
356
- const channels = channelsRaw.split(',').map(s => s.trim()).filter(Boolean);
357
- const permissions = permsRaw.split(',').map(s => s.trim()).filter(Boolean);
358
-
359
- const resultEl = document.getElementById('register-result');
1341
+ const nick = document.getElementById('reg-nick').value.trim();
1342
+ const type = document.getElementById('reg-type').value;
1343
+ const channels = document.getElementById('reg-channels').value.split(',').map(s=>s.trim()).filter(Boolean);
1344
+ const permissions = document.getElementById('reg-permissions').value.split(',').map(s=>s.trim()).filter(Boolean);
1345
+ const resultEl = document.getElementById('register-result');
3601346
resultEl.style.display = 'none';
361
-
3621347
try {
3631348
const res = await api('POST', '/v1/agents/register', { nick, type, channels, permissions });
3641349
showCredentials(nick, res.credentials, res.payload, 'register');
3651350
document.getElementById('register-form').reset();
366
- await loadAgents();
367
- await loadStatus();
1351
+ await loadAgents(); await loadStatus();
1352
+ } catch(e) { resultEl.style.display='block'; resultEl.innerHTML=renderAlert('error', e.message); }
1353
+}
1354
+function showCredentials(nick, creds, payload, mode) {
1355
+ const resultEl = document.getElementById('register-result');
1356
+ resultEl.style.display = 'block';
1357
+ const pass = creds?.passphrase || creds?.Passphrase || '';
1358
+ const sig = payload?.signature || '';
1359
+ resultEl.innerHTML = renderAlert('success',
1360
+ `<div><strong>${mode==='register'?'Registered':'Rotated'}: ${esc(nick)}</strong>
1361
+ <div class="cred-box">
1362
+ <div class="cred-row"><span class="cred-key">nick</span><span class="cred-val">${esc(creds?.nick||nick)}</span><button class="sm" onclick="copyText('${esc(creds?.nick||nick)}',this)">copy</button></div>
1363
+ <div class="cred-row"><span class="cred-key">passphrase</span><span class="cred-val">${esc(pass)}</span><button class="sm" onclick="copyText('${esc(pass)}',this)">copy</button></div>
1364
+ ${sig?`<div class="cred-row"><span class="cred-key">sig</span><span class="cred-val" style="font-size:11px">${esc(sig)}</span></div>`:''}
1365
+ </div>
1366
+ <div style="margin-top:8px;font-size:11px;color:#7ee787">⚠ Save the passphrase — shown once only.</div></div>`
1367
+ );
1368
+}
1369
+
1370
+// --- channels tab ---
1371
+async function loadChanTab() {
1372
+ if (!getToken()) return;
1373
+ try {
1374
+ const data = await api('GET', '/v1/channels');
1375
+ const channels = data.channels || [];
1376
+ document.getElementById('chan-count').textContent = channels.length;
1377
+ if (channels.length === 0) {
1378
+ document.getElementById('channels-list').innerHTML = '<div class="empty">no channels joined yet — type a channel name above and click join</div>';
1379
+ return;
1380
+ }
1381
+ document.getElementById('channels-list').innerHTML = channels.sort().map(ch =>
1382
+ `<div class="chan-card">
1383
+ <div>
1384
+ <div class="chan-name">${esc(ch)}</div>
1385
+ <div class="chan-meta">joined</div>
1386
+ </div>
1387
+ <div class="spacer"></div>
1388
+ <button class="sm" onclick="switchTab('chat');setTimeout(()=>selectChannel('${esc(ch)}'),50)">open chat →</button>
1389
+ </div>`
1390
+ ).join('');
1391
+ } catch(e) {
1392
+ document.getElementById('channels-list').innerHTML = '<div style="padding:16px">'+renderAlert('error', e.message)+'</div>';
1393
+ }
1394
+}
1395
+async function quickJoin() {
1396
+ let ch = document.getElementById('quick-join-input').value.trim();
1397
+ if (!ch) return;
1398
+ if (!ch.startsWith('#')) ch = '#' + ch;
1399
+ const slug = ch.replace(/^#/,'');
1400
+ try {
1401
+ await api('POST', `/v1/channels/${slug}/join`);
1402
+ document.getElementById('quick-join-input').value = '';
1403
+ await loadChanTab();
1404
+ renderChanSidebar((await api('GET','/v1/channels')).channels||[]);
1405
+ } catch(e) { alert('Join failed: '+e.message); }
1406
+}
1407
+document.getElementById('quick-join-input').addEventListener('keydown', e => { if(e.key==='Enter')quickJoin(); });
1408
+
1409
+// --- chat ---
1410
+let chatChannel = null, chatSSE = null;
1411
+
1412
+async function loadChannels() {
1413
+ if (!getToken()) return;
1414
+ try {
1415
+ const data = await api('GET', '/v1/channels');
1416
+ renderChanSidebar(data.channels || []);
1417
+ } catch(e) {}
1418
+}
1419
+function renderChanSidebar(channels) {
1420
+ const list = document.getElementById('chan-list');
1421
+ list.innerHTML = '';
1422
+ channels.sort().forEach(ch => {
1423
+ const el = document.createElement('div');
1424
+ el.className = 'chan-item' + (ch===chatChannel?' active':'');
1425
+ el.textContent = ch;
1426
+ el.onclick = () => selectChannel(ch);
1427
+ list.appendChild(el);
1428
+ });
1429
+}
1430
+async function joinChannel() {
1431
+ let ch = document.getElementById('join-channel-input').value.trim();
1432
+ if (!ch) return;
1433
+ if (!ch.startsWith('#')) ch = '#' + ch;
1434
+ const slug = ch.replace(/^#/,'');
1435
+ try {
1436
+ await api('POST', `/v1/channels/${slug}/join`);
1437
+ document.getElementById('join-channel-input').value = '';
1438
+ const data = await api('GET', '/v1/channels');
1439
+ renderChanSidebar(data.channels||[]);
1440
+ selectChannel(ch);
1441
+ } catch(e) { alert('Join failed: '+e.message); }
1442
+}
1443
+document.getElementById('join-channel-input').addEventListener('keydown', e => { if(e.key==='Enter')joinChannel(); });
1444
+
1445
+async function selectChannel(ch) {
1446
+ _lastMsgNick = null; _lastMsgAt = 0; _hideChatBanner(); _chatUnread = 0;
1447
+ chatChannel = ch;
1448
+ document.getElementById('chat-ch-name').textContent = ch;
1449
+ document.getElementById('chat-placeholder').style.display = 'none';
1450
+ document.querySelectorAll('.chan-item').forEach(el => el.classList.toggle('active', el.textContent===ch));
1451
+
1452
+ const area = document.getElementById('chat-msgs');
1453
+ Array.from(area.children).forEach(el => { if(!el.id) el.remove(); });
1454
+
1455
+ try {
1456
+ const slug = ch.replace(/^#/,'');
1457
+ const data = await api('GET', `/v1/channels/${slug}/messages`);
1458
+ (data.messages||[]).forEach(m => appendMsg(m, true));
1459
+ area.scrollTop = area.scrollHeight;
1460
+ } catch(e) {}
1461
+
1462
+ if (chatSSE) { chatSSE.close(); chatSSE = null; }
1463
+ const slug = ch.replace(/^#/,'');
1464
+ const es = new EventSource(`/v1/channels/${slug}/stream?token=${encodeURIComponent(getToken())}`);
1465
+ chatSSE = es;
1466
+ const badge = document.getElementById('chat-stream-status');
1467
+ es.onopen = () => { badge.textContent='● live'; badge.style.color='#3fb950'; };
1468
+ es.onmessage = ev => { try { appendMsg(JSON.parse(ev.data)); area.scrollTop=area.scrollHeight; } catch(_){} };
1469
+ es.onerror = () => { badge.textContent='○ reconnecting…'; badge.style.color='#8b949e'; };
1470
+
1471
+ loadNicklist(ch);
1472
+ if (_nicklistTimer) clearInterval(_nicklistTimer);
1473
+ _nicklistTimer = setInterval(() => loadNicklist(chatChannel), 10000);
1474
+}
1475
+
1476
+let _nicklistTimer = null;
1477
+async function loadNicklist(ch) {
1478
+ if (!ch) return;
1479
+ try {
1480
+ const slug = ch.replace(/^#/,'');
1481
+ const data = await api('GET', `/v1/channels/${slug}/users`);
1482
+ renderNicklist(data.users || []);
1483
+ } catch(e) {}
1484
+}
1485
+function renderNicklist(users) {
1486
+ const el = document.getElementById('nicklist-users');
1487
+ const knownBots = new Set(['bridge','oracle','sentinel','steward','scribe','warden','snitch','herald','scroll','systembot','auditbot','claude']);
1488
+ el.innerHTML = users.sort((a,b) => a.localeCompare(b)).map(nick => {
1489
+ const isBot = knownBots.has(nick.toLowerCase());
1490
+ return `<div class="nicklist-nick${isBot?' is-bot':''}" title="${esc(nick)}">${esc(nick)}</div>`;
1491
+ }).join('');
1492
+}
1493
+// Nick colors — deterministic hash over a palette
1494
+const NICK_PALETTE = ['#58a6ff','#3fb950','#ffa657','#d2a8ff','#56d364','#79c0ff','#ff7b72','#a5d6ff','#f0883e','#39d353'];
1495
+function nickColor(nick) {
1496
+ let h = 0;
1497
+ for (let i = 0; i < nick.length; i++) h = (h * 31 + nick.charCodeAt(i)) & 0xffff;
1498
+ return NICK_PALETTE[h % NICK_PALETTE.length];
1499
+}
1500
+
1501
+let _lastMsgNick = null, _lastMsgAt = 0;
1502
+const GROUP_MS = 5 * 60 * 1000;
1503
+let _chatNewBanner = null;
1504
+let _chatUnread = 0;
1505
+
1506
+function appendMsg(msg, isHistory) {
1507
+ const area = document.getElementById('chat-msgs');
1508
+
1509
+ // Parse "[nick] text" sent by the bridge bot on behalf of a web user
1510
+ let displayNick = msg.nick;
1511
+ let displayText = msg.text;
1512
+ if (msg.nick === 'bridge') {
1513
+ const m = msg.text.match(/^\[([^\]]+)\] ([\s\S]*)$/);
1514
+ if (m) { displayNick = m[1]; displayText = m[2]; }
1515
+ }
1516
+
1517
+ const atMs = new Date(msg.at).getTime();
1518
+ const grouped = !isHistory && displayNick === _lastMsgNick && (atMs - _lastMsgAt) < GROUP_MS;
1519
+ _lastMsgNick = displayNick;
1520
+ _lastMsgAt = atMs;
1521
+
1522
+ const timeStr = new Date(msg.at).toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'});
1523
+ const color = nickColor(displayNick);
1524
+
1525
+ const row = document.createElement('div');
1526
+ row.className = 'msg-row' + (grouped ? ' msg-grouped' : '');
1527
+ row.innerHTML =
1528
+ `<span class="msg-time" title="${esc(new Date(msg.at).toLocaleString())}">${esc(timeStr)}</span>` +
1529
+ `<span class="msg-nick" style="color:${color}">${esc(displayNick)}</span>` +
1530
+ `<span class="msg-text">${esc(displayText)}</span>`;
1531
+ area.appendChild(row);
1532
+
1533
+ // Unread badge when chat tab not active
1534
+ if (!isHistory && !document.getElementById('tab-chat').classList.contains('active')) {
1535
+ _chatUnread++;
1536
+ document.getElementById('tab-chat').dataset.unread = _chatUnread > 9 ? '9+' : _chatUnread;
1537
+ }
1538
+
1539
+ if (isHistory) {
1540
+ area.scrollTop = area.scrollHeight;
1541
+ } else {
1542
+ const nearBottom = area.scrollHeight - area.clientHeight - area.scrollTop < 100;
1543
+ if (nearBottom) {
1544
+ area.scrollTop = area.scrollHeight;
1545
+ _hideChatBanner();
1546
+ } else {
1547
+ _showChatBanner(area);
1548
+ }
1549
+ }
1550
+}
1551
+
1552
+function _showChatBanner(area) {
1553
+ if (_chatNewBanner) return;
1554
+ _chatNewBanner = document.createElement('div');
1555
+ _chatNewBanner.className = 'chat-new-banner';
1556
+ _chatNewBanner.textContent = '↓ new messages';
1557
+ _chatNewBanner.onclick = () => { area.scrollTop = area.scrollHeight; _hideChatBanner(); };
1558
+ area.appendChild(_chatNewBanner);
1559
+}
1560
+function _hideChatBanner() {
1561
+ if (_chatNewBanner) { _chatNewBanner.remove(); _chatNewBanner = null; }
1562
+}
1563
+function saveChatIdentity() {
1564
+ localStorage.setItem('sb_chat_nick', document.getElementById('chat-identity').value);
1565
+}
1566
+function getChatNick() {
1567
+ return localStorage.getItem('sb_chat_nick') || '';
1568
+}
1569
+function populateChatIdentity() {
1570
+ const sel = document.getElementById('chat-identity');
1571
+ const current = getChatNick();
1572
+ // Operators + any registered nick can send (all types visible, operators first)
1573
+ const operators = allAgents.filter(a => a.type === 'operator' && !a.revoked);
1574
+ const bots = allAgents.filter(a => a.type !== 'operator' && !a.revoked);
1575
+ const options = [...operators, ...bots];
1576
+ sel.innerHTML = '<option value="">— pick a user —</option>' +
1577
+ options.map(a => `<option value="${esc(a.nick)}"${a.nick===current?' selected':''}>${esc(a.nick)} (${esc(a.type)})</option>`).join('');
1578
+ // Restore saved selection.
1579
+ if (current) sel.value = current;
1580
+}
1581
+
1582
+async function sendMsg() {
1583
+ if (!chatChannel) return;
1584
+ const input = document.getElementById('chat-text-input');
1585
+ const nick = document.getElementById('chat-identity').value.trim() || 'web';
1586
+ const text = input.value.trim();
1587
+ if (!text) return;
1588
+ input.disabled = true;
1589
+ document.getElementById('chat-send-btn').disabled = true;
1590
+ try {
1591
+ const slug = chatChannel.replace(/^#/,'');
1592
+ await api('POST', `/v1/channels/${slug}/messages`, { text, nick });
1593
+ input.value = '';
1594
+ } catch(e) { alert('Send failed: '+e.message); }
1595
+ finally { input.disabled=false; document.getElementById('chat-send-btn').disabled=false; input.focus(); }
1596
+}
1597
+// --- chat input: Enter to send, Tab for nick completion ---
1598
+(function() {
1599
+ const input = document.getElementById('chat-text-input');
1600
+ let _tabCandidates = [];
1601
+ let _tabIdx = -1;
1602
+ let _tabPrefix = '';
1603
+
1604
+ input.addEventListener('keydown', e => {
1605
+ if (e.key === 'Enter') { e.preventDefault(); sendMsg(); return; }
1606
+ if (e.key === 'Tab') {
1607
+ e.preventDefault();
1608
+ const val = input.value;
1609
+ const cursor = input.selectionStart;
1610
+ // Find the word being typed up to cursor
1611
+ const before = val.slice(0, cursor);
1612
+ const wordStart = before.search(/\S+$/);
1613
+ const word = wordStart === -1 ? '' : before.slice(wordStart);
1614
+ if (!word) return;
1615
+
1616
+ // On first Tab press with this prefix, build candidate list
1617
+ if (_tabIdx === -1 || word.toLowerCase() !== _tabPrefix.toLowerCase()) {
1618
+ _tabPrefix = word;
1619
+ const nicks = Array.from(document.querySelectorAll('#nicklist-users .nicklist-nick'))
1620
+ .map(el => el.textContent.replace(/^●\s*/, '').trim())
1621
+ .filter(n => n.toLowerCase().startsWith(word.toLowerCase()));
1622
+ if (!nicks.length) return;
1623
+ _tabCandidates = nicks;
1624
+ _tabIdx = 0;
1625
+ } else {
1626
+ _tabIdx = (_tabIdx + 1) % _tabCandidates.length;
1627
+ }
1628
+
1629
+ const chosen = _tabCandidates[_tabIdx];
1630
+ // If at start of message, append ': '
1631
+ const suffix = (wordStart === 0 && before.slice(0, wordStart) === '') ? ': ' : ' ';
1632
+ const newVal = val.slice(0, wordStart === -1 ? 0 : wordStart) + chosen + suffix + val.slice(cursor);
1633
+ input.value = newVal;
1634
+ const newPos = (wordStart === -1 ? 0 : wordStart) + chosen.length + suffix.length;
1635
+ input.setSelectionRange(newPos, newPos);
1636
+ return;
1637
+ }
1638
+ // Any other key resets tab state
1639
+ _tabIdx = -1;
1640
+ _tabPrefix = '';
1641
+ });
1642
+})();
1643
+
1644
+// --- sidebar collapse toggles ---
1645
+function toggleSidebar(side) {
1646
+ if (side === 'left') {
1647
+ const el = document.getElementById('chat-sidebar-left');
1648
+ const btn = document.getElementById('sidebar-left-toggle');
1649
+ const collapsed = el.classList.toggle('collapsed');
1650
+ btn.textContent = collapsed ? '›' : '‹';
1651
+ btn.title = collapsed ? 'expand' : 'collapse';
1652
+ } else {
1653
+ const el = document.getElementById('chat-nicklist');
1654
+ const btn = document.getElementById('sidebar-right-toggle');
1655
+ const collapsed = el.classList.toggle('collapsed');
1656
+ btn.textContent = collapsed ? '‹' : '›';
1657
+ btn.title = collapsed ? 'expand' : 'collapse';
1658
+ }
1659
+}
1660
+
1661
+// --- sidebar drag-to-resize ---
1662
+(function() {
1663
+ function makeResizable(handleId, sidebarId, side) {
1664
+ const handle = document.getElementById(handleId);
1665
+ const sidebar = document.getElementById(sidebarId);
1666
+ if (!handle || !sidebar) return;
1667
+ let startX, startW;
1668
+ handle.addEventListener('mousedown', e => {
1669
+ e.preventDefault();
1670
+ startX = e.clientX;
1671
+ startW = sidebar.offsetWidth;
1672
+ handle.classList.add('dragging');
1673
+ const onMove = mv => {
1674
+ const delta = side === 'left' ? mv.clientX - startX : startX - mv.clientX;
1675
+ const w = Math.max(28, Math.min(400, startW + delta));
1676
+ sidebar.style.width = w + 'px';
1677
+ if (w <= 30) sidebar.classList.add('collapsed');
1678
+ else sidebar.classList.remove('collapsed');
1679
+ };
1680
+ const onUp = () => {
1681
+ handle.classList.remove('dragging');
1682
+ document.removeEventListener('mousemove', onMove);
1683
+ document.removeEventListener('mouseup', onUp);
1684
+ };
1685
+ document.addEventListener('mousemove', onMove);
1686
+ document.addEventListener('mouseup', onUp);
1687
+ });
1688
+ }
1689
+ makeResizable('resize-left', 'chat-sidebar-left', 'left');
1690
+ makeResizable('resize-right', 'chat-nicklist', 'right');
1691
+})();
1692
+
1693
+// --- helpers ---
1694
+function renderAlert(type, msg) {
1695
+ return `<div class="alert ${type}"><span class="icon">${{info:'ℹ',error:'✕',success:'✓'}[type]}</span><div>${msg}</div></div>`;
1696
+}
1697
+function esc(s) {
1698
+ return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
1699
+}
1700
+function fmtTime(iso) {
1701
+ if (!iso) return '—';
1702
+ const d = new Date(iso);
1703
+ return d.toLocaleDateString()+' '+d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
1704
+}
1705
+
1706
+// --- collapsible cards ---
1707
+function toggleCard(id, e) {
1708
+ // Don't collapse when clicking buttons inside the header.
1709
+ if (e && e.target.tagName === 'BUTTON') return;
1710
+ document.getElementById(id).classList.toggle('collapsed');
1711
+}
1712
+
1713
+// --- per-bot config schemas ---
1714
+const BEHAVIOR_SCHEMAS = {
1715
+ snitch: [
1716
+ { key:'alert_channel', label:'Alert channel', type:'text', placeholder:'#ops', hint:'Channel to post alerts in' },
1717
+ { key:'alert_nicks', label:'Alert nicks', type:'text', placeholder:'alice, bob', hint:'Operators to DM (comma-separated)' },
1718
+ { key:'flood_messages', label:'Flood threshold', type:'number', placeholder:'10', hint:'Messages in window that triggers alert' },
1719
+ { key:'flood_window_s', label:'Flood window (s)', type:'number', placeholder:'5', hint:'Rolling window duration in seconds' },
1720
+ { key:'joinpart_threshold',label:'Join/part threshold', type:'number', placeholder:'5', hint:'Join+part events before cycling alert' },
1721
+ { key:'joinpart_window_s', label:'Join/part window (s)',type:'number', placeholder:'30' },
1722
+ ],
1723
+ warden: [
1724
+ { key:'flood_threshold', label:'Flood threshold', type:'number', placeholder:'10', hint:'Messages/window before action' },
1725
+ { key:'window_s', label:'Window (s)', type:'number', placeholder:'5' },
1726
+ { key:'warn_before_mute', label:'Warn before mute', type:'checkbox' },
1727
+ { key:'mute_duration_s', label:'Mute duration (s)', type:'number', placeholder:'300' },
1728
+ { key:'kick_after_mutes', label:'Kick after N mutes',type:'number', placeholder:'3' },
1729
+ ],
1730
+ oracle: [
1731
+ { key:'backend', label:'LLM backend', type:'llm-backend', hint:'Backend configured in the AI tab' },
1732
+ { key:'model', label:'Model override', type:'model-override', backendKey:'backend', hint:'Override the backend default model (optional)' },
1733
+ { key:'scribe_dir', label:'Scribe log dir', type:'text', placeholder:'./data/logs/scribe', hint:'Directory scribe writes to — oracle reads history from here' },
1734
+ { key:'max_messages', label:'Max messages', type:'number', placeholder:'50', hint:'Default message count for summaries' },
1735
+ ],
1736
+ scribe: [
1737
+ { key:'dir', label:'Log directory', type:'text', placeholder:'./data/logs', hint:'Directory to write log files into' },
1738
+ { key:'format', label:'Format', type:'select', options:['jsonl','csv','text'], hint:'jsonl=structured, csv=spreadsheet, text=human-readable' },
1739
+ { key:'rotation', label:'Rotation', type:'select', options:['none','daily','weekly','monthly','yearly','size'], hint:'When to start a new log file' },
1740
+ { key:'max_size_mb', label:'Max size (MiB)', type:'number', placeholder:'100', hint:'Only applies when rotation = size' },
1741
+ { key:'per_channel', label:'Per-channel files',type:'checkbox', hint:'Separate file per channel' },
1742
+ { key:'max_age_days', label:'Max age (days)', type:'number', placeholder:'0', hint:'Prune old rotated files; 0 = keep all' },
1743
+ ],
1744
+ herald: [
1745
+ { key:'webhook_path', label:'Webhook path', type:'text', placeholder:'/webhooks/herald', hint:'HTTP path that receives inbound events' },
1746
+ { key:'rate_limit', label:'Rate limit (msg/min)', type:'number', placeholder:'60' },
1747
+ ],
1748
+ scroll: [
1749
+ { key:'max_replay', label:'Max replay', type:'number', placeholder:'100', hint:'Max messages per request' },
1750
+ { key:'require_auth', label:'Require auth', type:'checkbox', hint:'Only registered agents can query history' },
1751
+ ],
1752
+ systembot: [
1753
+ { key:'log_joins', label:'Log joins', type:'checkbox' },
1754
+ { key:'log_parts', label:'Log parts/quits', type:'checkbox' },
1755
+ { key:'log_modes', label:'Log mode changes', type:'checkbox' },
1756
+ { key:'log_kicks', label:'Log kicks', type:'checkbox' },
1757
+ ],
1758
+ auditbot: [
1759
+ { key:'retention_days', label:'Retention (days)', type:'number', placeholder:'90', hint:'0 = keep forever' },
1760
+ { key:'log_path', label:'Log path', type:'text', placeholder:'/var/log/scuttlebot/audit.log' },
1761
+ ],
1762
+ sentinel: [
1763
+ { key:'backend', label:'LLM backend', type:'llm-backend', hint:'Backend configured in the AI tab' },
1764
+ { key:'model', label:'Model override', type:'model-override', backendKey:'backend', hint:'Override the backend default model (optional)' },
1765
+ { key:'mod_channel', label:'Mod channel', type:'text', placeholder:'#moderation', hint:'Channel where incident reports are posted' },
1766
+ { key:'dm_operators', label:'DM operators', type:'checkbox', hint:'Also send incident reports as DMs to operator nicks' },
1767
+ { key:'alert_nicks', label:'Operator nicks', type:'text', placeholder:'alice,bob', hint:'Comma-separated nicks to DM on incidents (requires DM operators)' },
1768
+ { key:'policy', label:'Policy', type:'text', placeholder:'Flag harassment, hate speech, spam and threats.', hint:'Plain-English description of what to flag' },
1769
+ { key:'min_severity', label:'Min severity', type:'select', options:['low','medium','high'], hint:'Minimum severity level to report' },
1770
+ { key:'window_size', label:'Window size', type:'number', placeholder:'20', hint:'Messages to buffer per channel before analysis' },
1771
+ { key:'window_age_sec', label:'Window age (s)', type:'number', placeholder:'300', hint:'Max seconds before a stale buffer is force-scanned' },
1772
+ { key:'cooldown_sec', label:'Cooldown (s)', type:'number', placeholder:'600', hint:'Min seconds between reports about the same nick' },
1773
+ ],
1774
+ steward: [
1775
+ { key:'mod_channel', label:'Mod channel', type:'text', placeholder:'#moderation', hint:'Channel steward watches for sentinel reports and posts action logs' },
1776
+ { key:'operator_nicks', label:'Operator nicks', type:'text', placeholder:'alice,bob', hint:'Comma-separated nicks allowed to issue direct commands via DM' },
1777
+ { key:'dm_on_action', label:'DM operators', type:'checkbox', hint:'Send a DM to operator nicks when steward takes action' },
1778
+ { key:'auto_act', label:'Auto-act', type:'checkbox', hint:'Automatically act on sentinel incident reports' },
1779
+ { key:'warn_on_low', label:'Warn on low', type:'checkbox', hint:'Send a warning notice for low-severity incidents' },
1780
+ { key:'mute_duration_sec', label:'Mute duration (s)',type:'number', placeholder:'600', hint:'How long medium-severity mutes last' },
1781
+ { key:'cooldown_sec', label:'Cooldown (s)', type:'number', placeholder:'300', hint:'Min seconds between automated actions on the same nick' },
1782
+ ],
1783
+};
1784
+
1785
+function renderBehConfig(b) {
1786
+ const schema = BEHAVIOR_SCHEMAS[b.id];
1787
+ if (!schema) return '';
1788
+ const cfg = b.config || {};
1789
+ const fields = schema.map(f => {
1790
+ const val = cfg[f.key];
1791
+ let input = '';
1792
+ if (f.type === 'checkbox') {
1793
+ input = `<input type="checkbox" ${val?'checked':''} style="accent-color:#58a6ff" onchange="onBehCfg('${esc(b.id)}','${f.key}',this.checked)">`;
1794
+ } else if (f.type === 'select') {
1795
+ input = `<select onchange="onBehCfg('${esc(b.id)}','${f.key}',this.value)">${(f.options||[]).map(o=>`<option ${val===o?'selected':''}>${esc(o)}</option>`).join('')}</select>`;
1796
+ } else if (f.type === 'llm-backend') {
1797
+ const opts = _llmBackendNames.map(n => `<option value="${esc(n)}" ${val===n?'selected':''}>${esc(n)}</option>`).join('');
1798
+ const noMatch = val && !_llmBackendNames.includes(val);
1799
+ input = `<select onchange="onBehCfg('${esc(b.id)}','${f.key}',this.value)">
1800
+ <option value="">— select backend —</option>
1801
+ ${opts}
1802
+ ${noMatch ? `<option value="${esc(val)}" selected>${esc(val)}</option>` : ''}
1803
+ </select>`;
1804
+ } else if (f.type === 'model-override') {
1805
+ const selId = `beh-msel-${esc(b.id)}`;
1806
+ const customId = `beh-mcustom-${esc(b.id)}`;
1807
+ const backendKey = f.backendKey || 'backend';
1808
+ const currentVal = val || '';
1809
+ input = `<div style="display:flex;gap:6px;align-items:flex-start">
1810
+ <div style="flex:1">
1811
+ <select id="${selId}" style="width:100%" onchange="onBehModelSelect('${esc(b.id)}','${f.key}','${selId}','${customId}')">
1812
+ <option value="">— none / auto-select —</option>
1813
+ ${currentVal ? `<option value="${esc(currentVal)}" selected>${esc(currentVal)}</option>` : ''}
1814
+ <option value="__other__">— other (type below) —</option>
1815
+ </select>
1816
+ <input type="text" id="${customId}" placeholder="model-id" autocomplete="off"
1817
+ style="display:none;margin-top:6px"
1818
+ onchange="onBehCfg('${esc(b.id)}','${f.key}',this.value)">
1819
+ </div>
1820
+ <button type="button" class="sm" style="white-space:nowrap;margin-top:1px"
1821
+ onclick="loadBehModels(this,'${esc(b.id)}','${backendKey}','${f.key}','${selId}','${customId}')">↺</button>
1822
+ </div>`;
1823
+ } else {
1824
+ input = `<input type="${f.type}" placeholder="${esc(f.placeholder||'')}" value="${esc(String(val??''))}" onchange="onBehCfg('${esc(b.id)}','${f.key}',this.value${f.type==='number'?'*1':''})">`;
1825
+ }
1826
+ return `<div class="beh-field"><label>${esc(f.label)}</label>${input}${f.hint?`<div class="hint">${esc(f.hint)}</div>`:''}</div>`;
1827
+ }).join('');
1828
+ return `<div class="beh-config" id="beh-cfg-${esc(b.id)}">${fields}</div>`;
1829
+}
1830
+
1831
+function toggleBehConfig(id) {
1832
+ const el = document.getElementById('beh-cfg-' + id);
1833
+ if (!el) return;
1834
+ el.classList.toggle('open');
1835
+ const btn = document.getElementById('beh-cfg-btn-' + id);
1836
+ if (btn) btn.textContent = el.classList.contains('open') ? 'configure ▴' : 'configure ▾';
1837
+}
1838
+
1839
+function onBehCfg(id, key, val) {
1840
+ const b = currentPolicies.behaviors.find(x => x.id === id);
1841
+ if (!b) return;
1842
+ if (!b.config) b.config = {};
1843
+ b.config[key] = val;
1844
+}
1845
+
1846
+function onBehModelSelect(botId, key, selId, customId) {
1847
+ const sel = document.getElementById(selId);
1848
+ const custom = document.getElementById(customId);
1849
+ if (!sel) return;
1850
+ custom.style.display = sel.value === '__other__' ? '' : 'none';
1851
+ if (sel.value !== '__other__') onBehCfg(botId, key, sel.value);
1852
+}
1853
+
1854
+async function loadBehModels(btn, botId, backendKey, modelKey, selId, customId) {
1855
+ const b = currentPolicies && currentPolicies.behaviors.find(x => x.id === botId);
1856
+ const backendName = b && b.config && b.config[backendKey];
1857
+ if (!backendName) {
1858
+ alert('Select a backend first, then click ↺ to load its models.');
1859
+ return;
1860
+ }
1861
+ const origText = btn.textContent;
1862
+ btn.textContent = '…';
1863
+ btn.disabled = true;
1864
+ try {
1865
+ const models = await api('GET', `/v1/llm/backends/${encodeURIComponent(backendName)}/models`);
1866
+ const sel = document.getElementById(selId);
1867
+ const custom = document.getElementById(customId);
1868
+ if (!sel) return;
1869
+ const current = (b.config && b.config[modelKey]) || '';
1870
+ sel.innerHTML = '<option value="">— none / auto-select —</option>';
1871
+ for (const m of (models || [])) {
1872
+ const id = typeof m === 'string' ? m : m.id;
1873
+ const label = (typeof m === 'object' && m.name && m.name !== id) ? `${id} — ${m.name}` : id;
1874
+ const opt = document.createElement('option');
1875
+ opt.value = id;
1876
+ opt.textContent = label;
1877
+ if (id === current) opt.selected = true;
1878
+ sel.appendChild(opt);
1879
+ }
1880
+ const other = document.createElement('option');
1881
+ other.value = '__other__';
1882
+ other.textContent = '— other (type below) —';
1883
+ const matched = (models || []).some(m => (typeof m === 'string' ? m : m.id) === current);
1884
+ if (current && !matched) {
1885
+ other.selected = true;
1886
+ if (custom) { custom.value = current; custom.style.display = ''; }
1887
+ }
1888
+ sel.appendChild(other);
1889
+ } catch(e) {
1890
+ alert('Model discovery failed: ' + e.message);
1891
+ } finally {
1892
+ btn.textContent = origText;
1893
+ btn.disabled = false;
1894
+ }
1895
+}
1896
+
1897
+// --- admin accounts ---
1898
+async function loadAdmins() {
1899
+ try {
1900
+ const data = await api('GET', '/v1/admins');
1901
+ renderAdmins(data.admins || []);
1902
+ } catch(e) {
1903
+ // admins endpoint may not exist on token-only setups
1904
+ document.getElementById('admins-list-container').innerHTML = '';
1905
+ }
1906
+}
1907
+
1908
+function renderAdmins(admins) {
1909
+ const el = document.getElementById('admins-list-container');
1910
+ if (!admins.length) { el.innerHTML = ''; return; }
1911
+ const rows = admins.map(a => `<tr>
1912
+ <td><strong>${esc(a.username)}</strong></td>
1913
+ <td style="color:#8b949e;font-size:12px">${fmtTime(a.created)}</td>
1914
+ <td><div class="actions">
1915
+ <button class="sm" onclick="promptAdminPassword('${esc(a.username)}')">change password</button>
1916
+ <button class="sm danger" onclick="removeAdmin('${esc(a.username)}')">remove</button>
1917
+ </div></td>
1918
+ </tr>`).join('');
1919
+ el.innerHTML = `<table><thead><tr><th>username</th><th>created</th><th></th></tr></thead><tbody>${rows}</tbody></table>`;
1920
+}
1921
+
1922
+async function addAdmin(e) {
1923
+ e.preventDefault();
1924
+ const username = document.getElementById('new-admin-username').value.trim();
1925
+ const password = document.getElementById('new-admin-password').value;
1926
+ const resultEl = document.getElementById('add-admin-result');
1927
+ if (!username || !password) return;
1928
+ try {
1929
+ await api('POST', '/v1/admins', { username, password });
1930
+ resultEl.innerHTML = renderAlert('success', `Admin <strong>${esc(username)}</strong> added.`);
1931
+ resultEl.style.display = 'block';
1932
+ document.getElementById('add-admin-form').reset();
1933
+ await loadAdmins();
1934
+ setTimeout(() => { resultEl.style.display = 'none'; }, 3000);
1935
+ } catch(e) {
1936
+ resultEl.innerHTML = renderAlert('error', e.message);
1937
+ resultEl.style.display = 'block';
1938
+ }
1939
+}
1940
+
1941
+async function removeAdmin(username) {
1942
+ if (!confirm(`Remove admin "${username}"?`)) return;
1943
+ try {
1944
+ await api('DELETE', `/v1/admins/${encodeURIComponent(username)}`);
1945
+ await loadAdmins();
1946
+ } catch(e) { alert('Remove failed: ' + e.message); }
1947
+}
1948
+
1949
+async function promptAdminPassword(username) {
1950
+ const pw = prompt(`New password for ${username}:`);
1951
+ if (!pw) return;
1952
+ try {
1953
+ await api('PUT', `/v1/admins/${encodeURIComponent(username)}/password`, { password: pw });
1954
+ alert('Password updated.');
1955
+ } catch(e) { alert('Failed: ' + e.message); }
1956
+}
1957
+
1958
+// --- AI / LLM tab ---
1959
+async function loadAI() {
1960
+ await Promise.all([loadAIBackends(), loadAIKnown()]);
1961
+}
1962
+
1963
+async function loadAIBackends() {
1964
+ const el = document.getElementById('ai-backends-list');
1965
+ try {
1966
+ const backends = await api('GET', '/v1/llm/backends');
1967
+ if (!backends || backends.length === 0) {
1968
+ el.innerHTML = '<div class="empty-state">No LLM backends configured yet. Click <strong>+ add backend</strong> above or add them to <code>scuttlebot.yaml</code>.</div>';
1969
+ return;
1970
+ }
1971
+ el.innerHTML = backends.map(b => {
1972
+ const sid = CSS.escape(b.name);
1973
+ const editable = b.source === 'policy';
1974
+ const srcBadge = b.source === 'config'
1975
+ ? '<span class="badge" style="background:#21262d;color:#8b949e;border:1px solid #30363d">yaml</span>'
1976
+ : '<span class="badge" style="background:#21262d;color:#58a6ff;border:1px solid #1f6feb">ui</span>';
1977
+ return `<div class="setting-row" style="flex-wrap:wrap;gap:8px;align-items:center">
1978
+ <div style="flex:1;min-width:140px">
1979
+ <div style="font-weight:500;color:#e6edf3">${esc(b.name)} ${srcBadge}${b.default ? ' <span class="badge" style="background:#1f6feb">default</span>' : ''}</div>
1980
+ <div style="font-size:11px;color:#8b949e;margin-top:2px">${esc(b.backend)}${b.region ? ' · ' + esc(b.region) : ''}${b.base_url ? ' · ' + esc(b.base_url) : ''}</div>
1981
+ </div>
1982
+ <div style="min-width:100px;font-size:12px;color:#8b949e">${b.model ? 'model: <code style="color:#a5d6ff">' + esc(b.model) + '</code>' : '<span style="color:#6e7681">model: auto</span>'}</div>
1983
+ <div id="ai-models-${sid}" style="width:100%;display:none"></div>
1984
+ <button class="sm" onclick="discoverModels('${esc(b.name)}', this)">discover models</button>
1985
+ ${editable ? `<button class="sm" onclick="openEditBackend('${esc(b.name)}')">edit</button>
1986
+ <button class="sm danger" onclick="deleteBackend('${esc(b.name)}', this)">delete</button>` : ''}
1987
+ </div>`;
1988
+ }).join('<div style="height:1px;background:#21262d;margin:4px 0"></div>');
1989
+ } catch(e) {
1990
+ el.innerHTML = `<div class="empty-state" style="color:#f85149">${esc(String(e))}</div>`;
1991
+ }
1992
+}
1993
+
1994
+// --- backend form ---
1995
+
1996
+let _editingBackend = null; // null = adding, string = name being edited
1997
+let _backendList = []; // cached for edit lookups
1998
+
1999
+async function openAddBackend() {
2000
+ _editingBackend = null;
2001
+ document.getElementById('ai-form-title').textContent = 'add backend';
2002
+ document.getElementById('bf-submit-btn').textContent = 'add backend';
2003
+ document.getElementById('bf-name').value = '';
2004
+ document.getElementById('bf-name').disabled = false;
2005
+ document.getElementById('bf-backend').value = '';
2006
+ document.getElementById('bf-apikey').value = '';
2007
+ document.getElementById('bf-baseurl').value = '';
2008
+ populateModelSelect([], '');
2009
+ document.getElementById('bf-model-custom').value = '';
2010
+ document.getElementById('bf-model-custom').style.display = 'none';
2011
+ document.getElementById('bf-load-models-btn').textContent = '↺ load models';
2012
+ document.getElementById('bf-default').checked = false;
2013
+ document.getElementById('bf-region').value = '';
2014
+ document.getElementById('bf-aws-key-id').value = '';
2015
+ document.getElementById('bf-aws-secret').value = '';
2016
+ document.getElementById('bf-allow').value = '';
2017
+ document.getElementById('bf-block').value = '';
2018
+ document.getElementById('ai-form-result').style.display = 'none';
2019
+ onBackendTypeChange();
2020
+ const card = document.getElementById('card-ai-form');
2021
+ card.style.display = '';
2022
+ card.scrollIntoView({ behavior: 'smooth', block: 'start' });
2023
+}
2024
+
2025
+async function openEditBackend(name) {
2026
+ let b;
2027
+ try {
2028
+ const backends = await api('GET', '/v1/llm/backends');
2029
+ b = backends.find(x => x.name === name);
2030
+ } catch(e) { return; }
2031
+ if (!b) return;
2032
+
2033
+ _editingBackend = name;
2034
+ document.getElementById('ai-form-title').textContent = 'edit backend — ' + esc(name);
2035
+ document.getElementById('bf-submit-btn').textContent = 'save changes';
2036
+ document.getElementById('bf-name').value = name;
2037
+ document.getElementById('bf-name').disabled = true; // name is immutable
2038
+ document.getElementById('bf-backend').value = b.backend || '';
2039
+ document.getElementById('bf-apikey').value = ''; // never pre-fill secrets
2040
+ document.getElementById('bf-baseurl').value = b.base_url || '';
2041
+ const curated = KNOWN_MODELS[b.backend] || [];
2042
+ populateModelSelect(curated, b.model || '');
2043
+ document.getElementById('bf-model-custom').style.display = 'none';
2044
+ document.getElementById('bf-load-models-btn').textContent = '↺ load models';
2045
+ document.getElementById('bf-default').checked = !!b.default;
2046
+ document.getElementById('bf-region').value = b.region || '';
2047
+ document.getElementById('bf-aws-key-id').value = ''; // never pre-fill
2048
+ document.getElementById('bf-aws-secret').value = '';
2049
+ document.getElementById('bf-allow').value = (b.allow || []).join('\n');
2050
+ document.getElementById('bf-block').value = (b.block || []).join('\n');
2051
+ document.getElementById('ai-form-result').style.display = 'none';
2052
+ onBackendTypeChange();
2053
+ const card = document.getElementById('card-ai-form');
2054
+ card.style.display = '';
2055
+ card.scrollIntoView({ behavior: 'smooth', block: 'start' });
2056
+}
2057
+
2058
+function closeBackendForm() {
2059
+ document.getElementById('card-ai-form').style.display = 'none';
2060
+ _editingBackend = null;
2061
+}
2062
+
2063
+// Curated model lists per backend — shown before live discovery.
2064
+const KNOWN_MODELS = {
2065
+ anthropic: [
2066
+ 'claude-opus-4-6', 'claude-sonnet-4-6', 'claude-haiku-4-5-20251001',
2067
+ 'claude-3-5-sonnet-20241022', 'claude-3-5-haiku-20241022', 'claude-3-opus-20240229',
2068
+ ],
2069
+ gemini: [
2070
+ 'gemini-2.0-flash', 'gemini-2.0-flash-lite', 'gemini-1.5-flash',
2071
+ 'gemini-1.5-flash-8b', 'gemini-1.5-pro',
2072
+ ],
2073
+ openai: [
2074
+ 'gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'o1', 'o1-mini', 'o3-mini', 'gpt-3.5-turbo',
2075
+ ],
2076
+ bedrock: [
2077
+ 'anthropic.claude-3-5-sonnet-20241022-v2:0', 'anthropic.claude-3-5-haiku-20241022-v1:0',
2078
+ 'anthropic.claude-3-opus-20240229-v1:0',
2079
+ 'amazon.nova-pro-v1:0', 'amazon.nova-lite-v1:0', 'amazon.nova-micro-v1:0',
2080
+ 'meta.llama3-70b-instruct-v1:0', 'meta.llama3-8b-instruct-v1:0',
2081
+ 'mistral.mistral-large-2402-v1:0',
2082
+ ],
2083
+ ollama: ['llama3.2', 'llama3.1', 'mistral', 'codellama', 'gemma2', 'qwen2.5', 'phi3'],
2084
+ groq: [
2085
+ 'llama-3.3-70b-versatile', 'llama-3.1-8b-instant',
2086
+ 'mixtral-8x7b-32768', 'gemma2-9b-it',
2087
+ ],
2088
+ mistral: ['mistral-large-latest', 'mistral-small-latest', 'codestral-latest', 'open-mistral-nemo'],
2089
+ deepseek: ['deepseek-chat', 'deepseek-reasoner'],
2090
+ xai: ['grok-2', 'grok-2-mini', 'grok-beta'],
2091
+ cerebras: ['llama3.1-8b', 'llama3.1-70b', 'llama3.3-70b'],
2092
+ together: [
2093
+ 'meta-llama/Llama-3.3-70B-Instruct-Turbo',
2094
+ 'meta-llama/Llama-3.1-8B-Instruct-Turbo',
2095
+ 'mistralai/Mixtral-8x7B-Instruct-v0.1',
2096
+ 'Qwen/Qwen2.5-72B-Instruct-Turbo',
2097
+ ],
2098
+ fireworks: [
2099
+ 'accounts/fireworks/models/llama-v3p3-70b-instruct',
2100
+ 'accounts/fireworks/models/mixtral-8x7b-instruct',
2101
+ ],
2102
+ openrouter: [], // too varied — always load live
2103
+ huggingface: [
2104
+ 'meta-llama/Llama-3.3-70B-Instruct',
2105
+ 'mistralai/Mistral-7B-Instruct-v0.3',
2106
+ 'Qwen/Qwen2.5-72B-Instruct',
2107
+ ],
2108
+};
2109
+
2110
+function populateModelSelect(models, currentVal) {
2111
+ const sel = document.getElementById('bf-model-select');
2112
+ sel.innerHTML = '<option value="">— none / auto-select —</option>';
2113
+ for (const m of models) {
2114
+ const id = typeof m === 'string' ? m : m.id;
2115
+ const label = (typeof m === 'object' && m.name && m.name !== id) ? `${id} — ${m.name}` : id;
2116
+ const opt = document.createElement('option');
2117
+ opt.value = id;
2118
+ opt.textContent = label;
2119
+ if (id === currentVal) opt.selected = true;
2120
+ sel.appendChild(opt);
2121
+ }
2122
+ const other = document.createElement('option');
2123
+ other.value = '__other__';
2124
+ other.textContent = '— other (type below) —';
2125
+ if (currentVal && !models.find(m => (typeof m === 'string' ? m : m.id) === currentVal)) {
2126
+ other.selected = true;
2127
+ document.getElementById('bf-model-custom').value = currentVal;
2128
+ document.getElementById('bf-model-custom').style.display = '';
2129
+ }
2130
+ sel.appendChild(other);
2131
+}
2132
+
2133
+function onModelSelectChange() {
2134
+ const sel = document.getElementById('bf-model-select');
2135
+ const custom = document.getElementById('bf-model-custom');
2136
+ custom.style.display = sel.value === '__other__' ? '' : 'none';
2137
+}
2138
+
2139
+function getModelValue() {
2140
+ const sel = document.getElementById('bf-model-select');
2141
+ if (sel.value === '__other__') return document.getElementById('bf-model-custom').value.trim();
2142
+ return sel.value || '';
2143
+}
2144
+
2145
+function onBackendTypeChange() {
2146
+ const t = document.getElementById('bf-backend').value;
2147
+ const isBedrock = t === 'bedrock';
2148
+ const isLocal = ['ollama','litellm','lmstudio','jan','localai','vllm','anythingllm'].includes(t);
2149
+ const hasKey = !isBedrock;
2150
+
2151
+ document.getElementById('bf-bedrock-group').style.display = isBedrock ? '' : 'none';
2152
+ document.getElementById('bf-apikey-row').style.display = hasKey ? '' : 'none';
2153
+ document.getElementById('bf-baseurl-row').style.display = (isLocal || isBedrock) ? 'none' : '';
2154
+
2155
+ const curated = KNOWN_MODELS[t] || [];
2156
+ populateModelSelect(curated, '');
2157
+}
2158
+
2159
+async function loadLiveModels(btn) {
2160
+ const t = document.getElementById('bf-backend').value;
2161
+ if (!t) { alert('Select a backend type first.'); return; }
2162
+
2163
+ btn.disabled = true;
2164
+ btn.textContent = 'loading…';
2165
+ try {
2166
+ const payload = {
2167
+ backend: t,
2168
+ api_key: document.getElementById('bf-apikey')?.value || '',
2169
+ base_url: document.getElementById('bf-baseurl')?.value.trim() || '',
2170
+ region: document.getElementById('bf-region')?.value.trim() || '',
2171
+ aws_key_id: document.getElementById('bf-aws-key-id')?.value.trim() || '',
2172
+ aws_secret_key: document.getElementById('bf-aws-secret')?.value || '',
2173
+ };
2174
+ const models = await api('POST', '/v1/llm/discover', payload);
2175
+ const current = getModelValue();
2176
+ populateModelSelect(models, current);
2177
+ btn.textContent = `↺ ${models.length} loaded`;
2178
+ } catch(e) {
2179
+ btn.textContent = '✕ failed';
2180
+ setTimeout(() => { btn.textContent = '↺ load models'; }, 2000);
2181
+ alert('Discovery failed: ' + String(e));
2182
+ } finally {
2183
+ btn.disabled = false;
2184
+ }
2185
+}
2186
+
2187
+async function submitBackendForm() {
2188
+ const name = document.getElementById('bf-name').value.trim();
2189
+ const backend = document.getElementById('bf-backend').value;
2190
+ if (!name || !backend) {
2191
+ showFormResult('name and backend type are required', 'error');
2192
+ return;
2193
+ }
2194
+
2195
+ const allow = document.getElementById('bf-allow').value.trim().split('\n').map(s=>s.trim()).filter(Boolean);
2196
+ const block = document.getElementById('bf-block').value.trim().split('\n').map(s=>s.trim()).filter(Boolean);
2197
+
2198
+ const payload = {
2199
+ name, backend,
2200
+ api_key: document.getElementById('bf-apikey').value || undefined,
2201
+ base_url: document.getElementById('bf-baseurl').value.trim() || undefined,
2202
+ model: getModelValue() || undefined,
2203
+ default: document.getElementById('bf-default').checked || undefined,
2204
+ region: document.getElementById('bf-region').value.trim() || undefined,
2205
+ aws_key_id: document.getElementById('bf-aws-key-id').value.trim() || undefined,
2206
+ aws_secret_key: document.getElementById('bf-aws-secret').value || undefined,
2207
+ allow: allow.length ? allow : undefined,
2208
+ block: block.length ? block : undefined,
2209
+ };
2210
+
2211
+ const btn = document.getElementById('bf-submit-btn');
2212
+ btn.disabled = true;
2213
+ try {
2214
+ if (_editingBackend) {
2215
+ await api('PUT', `/v1/llm/backends/${encodeURIComponent(_editingBackend)}`, payload);
2216
+ } else {
2217
+ await api('POST', '/v1/llm/backends', payload);
2218
+ }
2219
+ closeBackendForm();
2220
+ await loadAIBackends();
2221
+ } catch(e) {
2222
+ showFormResult(String(e), 'error');
2223
+ } finally {
2224
+ btn.disabled = false;
2225
+ }
2226
+}
2227
+
2228
+async function deleteBackend(name, btn) {
2229
+ btn.disabled = true;
2230
+ try {
2231
+ await api('DELETE', `/v1/llm/backends/${encodeURIComponent(name)}`);
2232
+ await loadAIBackends();
2233
+ } catch(e) {
2234
+ btn.disabled = false;
2235
+ alert('Delete failed: ' + String(e));
2236
+ }
2237
+}
2238
+
2239
+function showFormResult(msg, type) {
2240
+ const el = document.getElementById('ai-form-result');
2241
+ el.style.display = '';
2242
+ el.className = 'alert ' + (type === 'error' ? 'danger' : 'info');
2243
+ el.innerHTML = `<span class="icon">${type === 'error' ? '✕' : 'ℹ'}</span><span>${esc(msg)}</span>`;
2244
+}
2245
+
2246
+async function discoverModels(name, btn) {
2247
+ const el = document.getElementById('ai-models-' + name);
2248
+ if (!el) return;
2249
+ btn.disabled = true;
2250
+ btn.textContent = 'discovering…';
2251
+ try {
2252
+ const models = await api('GET', `/v1/llm/backends/${encodeURIComponent(name)}/models`);
2253
+ el.style.display = 'block';
2254
+ if (!models || models.length === 0) {
2255
+ el.innerHTML = '<div style="font-size:12px;color:#8b949e;padding:6px 0">No models found (check filters).</div>';
2256
+ } else {
2257
+ el.innerHTML = `<div style="font-size:12px;color:#8b949e;margin-bottom:6px">${models.length} model${models.length !== 1 ? 's' : ''} available:</div>
2258
+ <div style="display:flex;flex-wrap:wrap;gap:4px">${models.map(m =>
2259
+ `<code style="background:#161b22;border:1px solid #30363d;border-radius:4px;padding:2px 6px;font-size:11px;color:#a5d6ff">${esc(m.id)}${m.name && m.name !== m.id ? ' <span style="color:#6e7681">(' + esc(m.name) + ')</span>' : ''}</code>`
2260
+ ).join('')}</div>`;
2261
+ }
2262
+ btn.textContent = '↺ refresh';
2263
+ } catch(e) {
2264
+ el.style.display = 'block';
2265
+ el.innerHTML = `<div style="font-size:12px;color:#f85149">Error: ${esc(String(e))}</div>`;
2266
+ btn.textContent = 'retry';
2267
+ } finally {
2268
+ btn.disabled = false;
2269
+ }
2270
+}
2271
+
2272
+async function loadAIKnown() {
2273
+ const el = document.getElementById('ai-supported-list');
2274
+ try {
2275
+ const known = await api('GET', '/v1/llm/known');
2276
+ const native = known.filter(b => b.native);
2277
+ const compat = known.filter(b => !b.native);
2278
+ native.sort((a,b) => a.name.localeCompare(b.name));
2279
+ compat.sort((a,b) => a.name.localeCompare(b.name));
2280
+ el.innerHTML = `
2281
+ <div style="margin-bottom:12px">
2282
+ <div style="font-size:12px;color:#8b949e;font-weight:500;margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px">native APIs</div>
2283
+ <div style="display:flex;flex-wrap:wrap;gap:4px">${native.map(b =>
2284
+ `<span style="background:#161b22;border:1px solid #30363d;border-radius:4px;padding:3px 8px;font-size:12px;color:#e6edf3">${esc(b.name)}</span>`
2285
+ ).join('')}</div>
2286
+ </div>
2287
+ <div>
2288
+ <div style="font-size:12px;color:#8b949e;font-weight:500;margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px">OpenAI-compatible</div>
2289
+ <div style="display:flex;flex-wrap:wrap;gap:4px">${compat.map(b =>
2290
+ `<span style="background:#161b22;border:1px solid #30363d;border-radius:4px;padding:3px 8px;font-size:12px;color:#e6edf3" title="${esc(b.base_url)}">${esc(b.name)}</span>`
2291
+ ).join('')}</div>
2292
+ </div>`;
2293
+ } catch(e) {
2294
+ el.innerHTML = `<div class="empty-state" style="color:#f85149">${esc(String(e))}</div>`;
2295
+ }
2296
+}
2297
+
2298
+function showAIExample(e) {
2299
+ e.preventDefault();
2300
+ const card = document.getElementById('card-ai-example');
2301
+ card.style.display = '';
2302
+ card.scrollIntoView({ behavior: 'smooth', block: 'start' });
2303
+ // Expand it if collapsed.
2304
+ const body = card.querySelector('.card-body');
2305
+ if (body) body.style.display = '';
2306
+}
2307
+
2308
+// --- settings / policies ---
2309
+let currentPolicies = null;
2310
+let _llmBackendNames = []; // cached backend names for oracle dropdown
2311
+
2312
+async function loadSettings() {
2313
+ try {
2314
+ const [s, backends] = await Promise.all([
2315
+ api('GET', '/v1/settings'),
2316
+ api('GET', '/v1/llm/backends').catch(() => []),
2317
+ ]);
2318
+ _llmBackendNames = (backends || []).map(b => b.name);
2319
+ renderTLSStatus(s.tls);
2320
+ currentPolicies = s.policies;
2321
+ renderBehaviors(s.policies.behaviors || []);
2322
+ renderAgentPolicy(s.policies.agent_policy || {});
2323
+ renderBridgePolicy(s.policies.bridge || {});
2324
+ renderLoggingPolicy(s.policies.logging || {});
2325
+ loadAdmins();
2326
+ } catch(e) {
2327
+ document.getElementById('tls-badge').textContent = 'error';
2328
+ }
2329
+}
2330
+
2331
+function renderTLSStatus(tls) {
2332
+ const badge = document.getElementById('tls-badge');
2333
+ if (tls.enabled) {
2334
+ badge.textContent = 'TLS active';
2335
+ badge.style.background = '#3fb95022'; badge.style.color = '#3fb950'; badge.style.borderColor = '#3fb95044';
2336
+ } else {
2337
+ badge.textContent = 'HTTP only';
2338
+ }
2339
+ document.getElementById('tls-status-rows').innerHTML = `
2340
+ <div class="setting-row">
2341
+ <div class="setting-label">mode</div>
2342
+ <div class="setting-desc"></div>
2343
+ <code class="setting-val">${tls.enabled ? 'HTTPS (Let\'s Encrypt)' : 'HTTP'}</code>
2344
+ </div>
2345
+ ${tls.enabled ? `
2346
+ <div class="setting-row">
2347
+ <div class="setting-label">domain</div>
2348
+ <div class="setting-desc"></div>
2349
+ <code class="setting-val">${esc(tls.domain)}</code>
2350
+ </div>
2351
+ <div class="setting-row">
2352
+ <div class="setting-label">allow insecure</div>
2353
+ <div class="setting-desc">Plain HTTP also accepted.</div>
2354
+ <code class="setting-val">${tls.allow_insecure ? 'yes' : 'no'}</code>
2355
+ </div>` : ''}
2356
+ `;
2357
+}
2358
+
2359
+function renderBehaviors(behaviors) {
2360
+ const hasSchema = id => !!BEHAVIOR_SCHEMAS[id];
2361
+ document.getElementById('behaviors-list').innerHTML = behaviors.map(b => `
2362
+ <div>
2363
+ <div style="display:grid;grid-template-columns:20px 90px 1fr auto;align-items:center;gap:12px;padding:11px 16px;border-bottom:1px solid #21262d">
2364
+ <input type="checkbox" ${b.enabled?'checked':''} onchange="onBehaviorToggle('${esc(b.id)}',this.checked)" style="width:14px;height:14px;cursor:pointer;accent-color:#58a6ff">
2365
+ <strong style="font-size:13px;white-space:nowrap">${esc(b.name)}</strong>
2366
+ <span style="font-size:12px;color:#8b949e">${esc(b.description)}</span>
2367
+ <div style="display:flex;align-items:center;gap:8px;justify-content:flex-end">
2368
+ ${b.enabled ? `
2369
+ <label style="display:flex;align-items:center;gap:4px;font-size:11px;color:#8b949e;cursor:pointer;white-space:nowrap">
2370
+ <input type="checkbox" ${b.join_all_channels?'checked':''} onchange="onBehaviorJoinAll('${esc(b.id)}',this.checked)" style="accent-color:#58a6ff">
2371
+ all channels
2372
+ </label>
2373
+ ${b.join_all_channels
2374
+ ? `<input type="text" placeholder="exclude #private, /regex/" style="width:160px;padding:3px 7px;font-size:11px" title="Exclude: comma-separated names or /regex/" value="${esc((b.exclude_channels||[]).join(', '))}" onchange="onBehaviorExclude('${esc(b.id)}',this.value)">`
2375
+ : `<input type="text" placeholder="#ops, /^#proj-.*/" style="width:160px;padding:3px 7px;font-size:11px" title="Join: comma-separated names or /regex/ patterns" value="${esc((b.required_channels||[]).join(', '))}" onchange="onBehaviorChannels('${esc(b.id)}',this.value)">`
2376
+ }
2377
+ ${hasSchema(b.id) ? `<button class="sm" id="beh-cfg-btn-${esc(b.id)}" onclick="toggleBehConfig('${esc(b.id)}')" style="font-size:11px;white-space:nowrap">configure ▾</button>` : ''}
2378
+ ` : ''}
2379
+ <span class="tag type-observer" style="font-size:11px;min-width:64px;text-align:center">${esc(b.nick)}</span>
2380
+ </div>
2381
+ </div>
2382
+ ${b.enabled && hasSchema(b.id) ? renderBehConfig(b) : ''}
2383
+ </div>
2384
+ `).join('');
2385
+}
2386
+
2387
+function onBehaviorToggle(id, enabled) {
2388
+ const b = currentPolicies.behaviors.find(x => x.id === id);
2389
+ if (b) b.enabled = enabled;
2390
+ renderBehaviors(currentPolicies.behaviors);
2391
+}
2392
+function onBehaviorJoinAll(id, val) {
2393
+ const b = currentPolicies.behaviors.find(x => x.id === id);
2394
+ if (b) b.join_all_channels = val;
2395
+ renderBehaviors(currentPolicies.behaviors);
2396
+}
2397
+function onBehaviorExclude(id, val) {
2398
+ const b = currentPolicies.behaviors.find(x => x.id === id);
2399
+ if (b) b.exclude_channels = val.split(',').map(s=>s.trim()).filter(Boolean);
2400
+}
2401
+function onBehaviorChannels(id, val) {
2402
+ const b = currentPolicies.behaviors.find(x => x.id === id);
2403
+ if (b) b.required_channels = val.split(',').map(s=>s.trim()).filter(Boolean);
2404
+}
2405
+
2406
+function renderAgentPolicy(p) {
2407
+ document.getElementById('policy-checkin-enabled').checked = !!p.require_checkin;
2408
+ document.getElementById('policy-checkin-channel').value = p.checkin_channel || '';
2409
+ document.getElementById('policy-required-channels').value = (p.required_channels||[]).join(', ');
2410
+ toggleCheckinChannel();
2411
+}
2412
+function toggleCheckinChannel() {
2413
+ const on = document.getElementById('policy-checkin-enabled').checked;
2414
+ document.getElementById('policy-checkin-row').style.display = on ? '' : 'none';
2415
+}
2416
+
2417
+function renderBridgePolicy(p) {
2418
+ document.getElementById('policy-bridge-web-user-ttl').value = p.web_user_ttl_minutes || 5;
2419
+}
2420
+
2421
+function renderLoggingPolicy(l) {
2422
+ document.getElementById('policy-logging-enabled').checked = !!l.enabled;
2423
+ document.getElementById('policy-log-dir').value = l.dir || '';
2424
+ document.getElementById('policy-log-format').value = l.format || 'jsonl';
2425
+ document.getElementById('policy-log-rotation').value = l.rotation || 'none';
2426
+ document.getElementById('policy-log-max-size').value = l.max_size_mb || '';
2427
+ document.getElementById('policy-log-per-channel').checked = !!l.per_channel;
2428
+ document.getElementById('policy-log-max-age').value = l.max_age_days || '';
2429
+ toggleLogOptions();
2430
+ toggleRotationOptions();
2431
+}
2432
+function toggleLogOptions() {
2433
+ const on = document.getElementById('policy-logging-enabled').checked;
2434
+ document.getElementById('policy-log-options').style.display = on ? '' : 'none';
2435
+}
2436
+function toggleRotationOptions() {
2437
+ const rot = document.getElementById('policy-log-rotation').value;
2438
+ document.getElementById('policy-log-size-row').style.display = rot === 'size' ? '' : 'none';
2439
+}
2440
+
2441
+async function savePolicies() {
2442
+ if (!currentPolicies) return;
2443
+ const p = JSON.parse(JSON.stringify(currentPolicies)); // deep copy
2444
+ p.agent_policy = {
2445
+ require_checkin: document.getElementById('policy-checkin-enabled').checked,
2446
+ checkin_channel: document.getElementById('policy-checkin-channel').value.trim(),
2447
+ required_channels: document.getElementById('policy-required-channels').value.split(',').map(s=>s.trim()).filter(Boolean),
2448
+ };
2449
+ p.bridge = {
2450
+ web_user_ttl_minutes: parseInt(document.getElementById('policy-bridge-web-user-ttl').value, 10) || 5,
2451
+ };
2452
+ p.logging = {
2453
+ enabled: document.getElementById('policy-logging-enabled').checked,
2454
+ dir: document.getElementById('policy-log-dir').value.trim(),
2455
+ format: document.getElementById('policy-log-format').value,
2456
+ rotation: document.getElementById('policy-log-rotation').value,
2457
+ max_size_mb: parseInt(document.getElementById('policy-log-max-size').value, 10) || 0,
2458
+ per_channel: document.getElementById('policy-log-per-channel').checked,
2459
+ max_age_days: parseInt(document.getElementById('policy-log-max-age').value, 10) || 0,
2460
+ };
2461
+ const resultEl = document.getElementById('policies-save-result');
2462
+ try {
2463
+ currentPolicies = await api('PUT', '/v1/settings/policies', p);
2464
+ resultEl.style.display = 'block';
2465
+ resultEl.innerHTML = renderAlert('success', 'Settings saved.');
2466
+ setTimeout(() => { resultEl.style.display = 'none'; }, 3000);
3682467
} catch(e) {
3692468
resultEl.style.display = 'block';
3702469
resultEl.innerHTML = renderAlert('error', e.message);
3712470
}
3722471
}
3732472
374
-function showCredentials(nick, creds, payload, mode) {
375
- const resultEl = document.getElementById('register-result');
376
- resultEl.style.display = 'block';
377
-
378
- const passphrase = creds?.passphrase || creds?.Passphrase || '';
379
- const payloadSig = payload?.signature || '';
380
- const payloadEnc = payload ? JSON.stringify(payload.payload || payload, null, 2) : '';
381
-
382
- resultEl.innerHTML = renderAlert('success',
383
- `<strong>${mode === 'register' ? 'Agent registered' : 'Credentials rotated'}: ${esc(nick)}</strong>
384
- <div style="margin-top:10px" class="cred-box">
385
- <div class="cred-row">
386
- <span class="cred-key">nick</span>
387
- <span class="cred-val">${esc(creds?.nick || nick)}</span>
388
- <button class="small copy-btn" onclick="copyText('${esc(creds?.nick || nick)}', this)">copy</button>
389
- </div>
390
- <div class="cred-row">
391
- <span class="cred-key">passphrase</span>
392
- <span class="cred-val">${esc(passphrase)}</span>
393
- <button class="small copy-btn" onclick="copyText('${esc(passphrase)}', this)">copy</button>
394
- </div>
395
- ${payloadSig ? `<div class="cred-row">
396
- <span class="cred-key">sig</span>
397
- <span class="cred-val" style="font-size:11px">${esc(payloadSig)}</span>
398
- </div>` : ''}
399
- </div>
400
- <div style="margin-top:8px;font-size:11px;color:#7ee787">⚠ Save the passphrase now — it will not be shown again.</div>`
401
- );
402
-}
403
-
404
-// --- helpers ---
405
-function renderAlert(type, msg) {
406
- const icons = { info: 'ℹ', error: '✕', success: '✓' };
407
- return `<div class="alert ${type}"><span class="icon">${icons[type]}</span><div>${msg}</div></div>`;
408
-}
409
-function esc(s) {
410
- return String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
411
-}
412
-function fmtTime(iso) {
413
- if (!iso) return '—';
414
- const d = new Date(iso);
415
- return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
416
-}
417
-
418
-// --- chat ---
419
-let chatChannel = null;
420
-let chatSSE = null;
421
-
422
-async function loadChannels() {
423
- if (!getToken()) return;
424
- try {
425
- const data = await api('GET', '/v1/channels');
426
- renderChannelList(data.channels || []);
427
- document.getElementById('chat-card').style.display = '';
428
- } catch(e) {
429
- // bridge disabled or error — keep chat card hidden
430
- }
431
-}
432
-
433
-function renderChannelList(channels) {
434
- const list = document.getElementById('chat-channel-list');
435
- // Remove old channel items (keep header div and join input div)
436
- Array.from(list.querySelectorAll('.chan-item')).forEach(el => el.remove());
437
- channels.sort().forEach(ch => {
438
- const el = document.createElement('div');
439
- el.className = 'chan-item' + (ch === chatChannel ? ' active' : '');
440
- el.textContent = ch;
441
- el.onclick = () => selectChannel(ch);
442
- list.appendChild(el);
443
- });
444
-}
445
-
446
-async function joinChannel() {
447
- let ch = document.getElementById('join-channel-input').value.trim();
448
- if (!ch) return;
449
- if (!ch.startsWith('#')) ch = '#' + ch;
450
- const slug = ch.replace(/^#/, '');
451
- try {
452
- await api('POST', `/v1/channels/${slug}/join`);
453
- document.getElementById('join-channel-input').value = '';
454
- await loadChannels();
455
- selectChannel(ch);
456
- } catch(e) {
457
- alert('Join failed: ' + e.message);
458
- }
459
-}
460
-
461
-document.getElementById('join-channel-input').addEventListener('keydown', e => {
462
- if (e.key === 'Enter') joinChannel();
463
-});
464
-
465
-async function selectChannel(ch) {
466
- chatChannel = ch;
467
- document.getElementById('chat-channel-badge').textContent = ch;
468
- document.getElementById('chat-channel-badge').style.display = '';
469
- document.getElementById('chat-placeholder').style.display = 'none';
470
- document.querySelectorAll('.chan-item').forEach(el => {
471
- el.classList.toggle('active', el.textContent === ch);
472
- });
473
-
474
- const area = document.getElementById('chat-messages');
475
- // clear previous messages (keep placeholder)
476
- Array.from(area.children).forEach(el => { if (!el.id) el.remove(); });
477
-
478
- try {
479
- const slug = ch.replace(/^#/, '');
480
- const data = await api('GET', `/v1/channels/${slug}/messages`);
481
- (data.messages || []).forEach(appendMessage);
482
- area.scrollTop = area.scrollHeight;
483
- } catch(e) {}
484
-
485
- if (chatSSE) { chatSSE.close(); chatSSE = null; }
486
- const slug = ch.replace(/^#/, '');
487
- const url = `/v1/channels/${slug}/stream?token=${encodeURIComponent(getToken())}`;
488
- const es = new EventSource(url);
489
- chatSSE = es;
490
- const status = document.getElementById('chat-stream-status');
491
- es.onopen = () => { status.textContent = '● live'; status.style.color = '#3fb950'; };
492
- es.onmessage = (e) => {
493
- try {
494
- const msg = JSON.parse(e.data);
495
- appendMessage(msg);
496
- area.scrollTop = area.scrollHeight;
497
- } catch(_) {}
498
- };
499
- es.onerror = () => { status.textContent = '○ reconnecting…'; status.style.color = '#8b949e'; };
500
-}
501
-
502
-function appendMessage(msg) {
503
- const area = document.getElementById('chat-messages');
504
- const t = new Date(msg.at);
505
- const timeStr = t.toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'});
506
- const isBridge = msg.nick === 'bridge';
507
- const row = document.createElement('div');
508
- row.className = 'msg-row';
509
- row.innerHTML = `<span class="msg-time">${esc(timeStr)}</span>`
510
- + `<span class="msg-nick${isBridge ? ' bridge-nick' : ''}">${esc(msg.nick)}</span>`
511
- + `<span class="msg-text">${esc(msg.text)}</span>`;
512
- area.appendChild(row);
513
-}
514
-
515
-async function sendChatMessage() {
516
- if (!chatChannel) return;
517
- const input = document.getElementById('chat-text-input');
518
- const nick = document.getElementById('chat-nick-input').value.trim() || 'web';
519
- const text = input.value.trim();
520
- if (!text) return;
521
- input.disabled = true;
522
- document.getElementById('chat-send-btn').disabled = true;
523
- try {
524
- const slug = chatChannel.replace(/^#/, '');
525
- await api('POST', `/v1/channels/${slug}/messages`, { text, nick });
526
- input.value = '';
527
- } catch(e) {
528
- alert('Send failed: ' + e.message);
529
- } finally {
530
- input.disabled = false;
531
- document.getElementById('chat-send-btn').disabled = false;
532
- input.focus();
533
- }
534
-}
535
-
536
-document.getElementById('chat-text-input').addEventListener('keydown', e => {
537
- if (e.key === 'Enter') sendChatMessage();
538
-});
539
-
5402473
// --- init ---
541
-function loadAll() { loadStatus(); loadAgents(); loadChannels(); }
542
-updateTokenDisplay();
543
-loadAll();
544
-setInterval(loadStatus, 15000);
2474
+function loadAll() { loadStatus(); loadAgents(); loadSettings(); startMetricsPoll(); }
2475
+initAuth();
5452476
</script>
5462477
</body>
5472478
</html>
5482479
5492480
ADDED internal/auth/admin.go
5502481
ADDED internal/auth/admin_test.go
--- internal/api/ui/index.html
+++ internal/api/ui/index.html
@@ -3,545 +3,2476 @@
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>scuttlebot</title>
7 <style>
8 * { box-sizing: border-box; margin: 0; padding: 0; }
9 body { font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace; background: #0d1117; color: #e6edf3; min-height: 100vh; }
10 header { background: #161b22; border-bottom: 1px solid #30363d; padding: 12px 24px; display: flex; align-items: center; gap: 16px; }
11 header h1 { font-size: 16px; color: #58a6ff; letter-spacing: 0.05em; }
12 header .tagline { font-size: 12px; color: #8b949e; }
13 header .spacer { flex: 1; }
14 .token-badge { font-size: 12px; color: #8b949e; display: flex; align-items: center; gap: 8px; }
15 .token-badge code { background: #21262d; border: 1px solid #30363d; border-radius: 4px; padding: 2px 8px; color: #a5d6ff; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
16 button { cursor: pointer; border: 1px solid #30363d; border-radius: 6px; padding: 6px 12px; font-size: 13px; font-family: inherit; background: #21262d; color: #e6edf3; transition: background 0.1s; }
17 button:hover { background: #30363d; }
18 button.primary { background: #1f6feb; border-color: #1f6feb; color: #fff; }
19 button.primary:hover { background: #388bfd; }
20 button.danger { background: #21262d; border-color: #f85149; color: #f85149; }
21 button.danger:hover { background: #3d1f1e; }
22 button.small { padding: 3px 8px; font-size: 12px; }
23 main { max-width: 960px; margin: 0 auto; padding: 24px; display: flex; flex-direction: column; gap: 24px; }
24 .card { background: #161b22; border: 1px solid #30363d; border-radius: 8px; overflow: hidden; }
25 .card-header { padding: 12px 16px; border-bottom: 1px solid #30363d; display: flex; align-items: center; gap: 8px; }
26 .card-header h2 { font-size: 14px; color: #e6edf3; font-weight: 600; }
27 .card-header .badge { background: #1f6feb22; border: 1px solid #1f6feb44; color: #58a6ff; border-radius: 999px; padding: 1px 8px; font-size: 12px; }
28 .card-body { padding: 16px; }
29 .status-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; }
30 .stat { background: #0d1117; border: 1px solid #21262d; border-radius: 6px; padding: 12px 16px; }
31 .stat .label { font-size: 11px; color: #8b949e; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 4px; }
32 .stat .value { font-size: 20px; color: #58a6ff; font-weight: 600; }
33 .stat .sub { font-size: 11px; color: #8b949e; margin-top: 2px; }
34 .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; }
35 .dot.green { background: #3fb950; box-shadow: 0 0 6px #3fb950aa; }
36 .dot.red { background: #f85149; }
37 table { width: 100%; border-collapse: collapse; font-size: 13px; }
38 th { text-align: left; padding: 8px 12px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #8b949e; border-bottom: 1px solid #21262d; }
39 td { padding: 10px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; vertical-align: top; }
40 tr:last-child td { border-bottom: none; }
41 tr:hover td { background: #1c2128; }
42 .tag { display: inline-block; background: #1f6feb22; border: 1px solid #1f6feb44; color: #79c0ff; border-radius: 4px; padding: 1px 6px; font-size: 11px; margin: 1px; }
43 .tag.type-operator { background: #db613622; border-color: #db613644; color: #ffa657; }
44 .tag.type-orchestrator { background: #8957e522; border-color: #8957e544; color: #d2a8ff; }
45 .tag.type-worker { background: #1f6feb22; border-color: #1f6feb44; color: #79c0ff; }
46 .tag.type-observer { background: #21262d; border-color: #30363d; color: #8b949e; }
47 .tag.revoked { background: #f8514922; border-color: #f8514944; color: #ff7b72; }
48 .actions { display: flex; gap: 6px; flex-wrap: wrap; }
49 .empty { color: #8b949e; font-size: 13px; text-align: center; padding: 24px; }
50 .chan-item { padding: 8px 12px; font-size: 13px; cursor: pointer; color: #8b949e; border-bottom: 1px solid #21262d; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
51 .chan-item:hover { background: #1c2128; color: #e6edf3; }
52 .chan-item.active { background: #1f6feb22; color: #58a6ff; border-left: 2px solid #58a6ff; }
53 .msg-row { display: flex; gap: 8px; font-size: 13px; line-height: 1.6; padding: 1px 0; }
54 .msg-time { color: #8b949e; font-size: 11px; flex-shrink: 0; padding-top: 3px; min-width: 44px; }
55 .msg-nick { color: #58a6ff; font-weight: 600; flex-shrink: 0; min-width: 80px; text-align: right; }
56 .msg-nick.bridge-nick { color: #3fb950; }
57 .msg-text { color: #e6edf3; word-break: break-word; }
58 form { display: flex; flex-direction: column; gap: 14px; }
59 .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
60 label { display: block; font-size: 12px; color: #8b949e; margin-bottom: 4px; }
61 input, select, textarea { width: 100%; background: #0d1117; border: 1px solid #30363d; border-radius: 6px; padding: 8px 10px; font-size: 13px; font-family: inherit; color: #e6edf3; outline: none; transition: border-color 0.1s; }
62 input:focus, select:focus, textarea:focus { border-color: #58a6ff; }
63 select option { background: #161b22; }
64 textarea { resize: vertical; min-height: 60px; }
65 .hint { font-size: 11px; color: #8b949e; margin-top: 3px; }
66 .alert { border-radius: 6px; padding: 12px 14px; font-size: 13px; display: flex; gap: 10px; align-items: flex-start; }
67 .alert.info { background: #1f6feb1a; border: 1px solid #1f6feb44; color: #79c0ff; }
68 .alert.error { background: #f851491a; border: 1px solid #f8514944; color: #ff7b72; }
69 .alert.success { background: #3fb9501a; border: 1px solid #3fb95044; color: #7ee787; }
70 .alert .icon { flex-shrink: 0; font-size: 16px; line-height: 1.3; }
71 .cred-box { background: #0d1117; border: 1px solid #30363d; border-radius: 6px; padding: 12px; font-size: 12px; }
72 .cred-box .cred-row { display: flex; align-items: baseline; gap: 8px; margin-bottom: 6px; }
73 .cred-box .cred-row:last-child { margin-bottom: 0; }
74 .cred-box .cred-key { color: #8b949e; min-width: 90px; }
75 .cred-box .cred-val { color: #a5d6ff; word-break: break-all; flex: 1; }
76 .cred-box .copy-btn { flex-shrink: 0; }
77 .modal-overlay { display: none; position: fixed; inset: 0; background: #0d111788; z-index: 100; align-items: center; justify-content: center; }
78 .modal-overlay.open { display: flex; }
79 .modal { background: #161b22; border: 1px solid #30363d; border-radius: 10px; padding: 24px; width: 480px; max-width: 95vw; }
80 .modal h3 { font-size: 15px; margin-bottom: 16px; }
81 .modal .btn-row { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82 </style>
 
83 </head>
84 <body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
86 <header>
87 <h1>⬡ scuttlebot</h1>
88 <span class="tagline">agent coordination backplane</span>
89 <div class="spacer"></div>
90 <div class="token-badge">
91 <span>token:</span>
92 <code id="token-display">not set</code>
93 <button class="small" onclick="openTokenModal()">set</button>
 
 
 
 
 
 
 
 
 
94 </div>
95 </header>
96
97 <main>
98 <div id="no-token-banner" class="alert info" style="display:none">
99 <span class="icon">ℹ</span>
100 <span>Paste your API token to continue. It was printed to stderr when scuttlebot started:<br><code style="color:#a5d6ff">level=INFO msg="api token" token=...</code></span>
101 </div>
102
103 <!-- Status -->
104 <div class="card">
105 <div class="card-header">
106 <span class="dot green" id="status-dot"></span>
107 <h2>status</h2>
108 </div>
109 <div class="card-body">
110 <div class="status-grid" id="status-grid">
111 <div class="stat"><div class="label">state</div><div class="value" id="stat-status">—</div></div>
112 <div class="stat"><div class="label">uptime</div><div class="value" id="stat-uptime">—</div></div>
113 <div class="stat"><div class="label">agents</div><div class="value" id="stat-agents">—</div></div>
114 <div class="stat"><div class="label">started</div><div class="value" style="font-size:13px" id="stat-started">—</div><div class="sub" id="stat-started-rel"></div></div>
115 </div>
116 <div id="status-error" style="margin-top:12px;display:none"></div>
117 </div>
118 </div>
119
120 <!-- Agents -->
121 <div class="card">
122 <div class="card-header">
123 <h2>agents</h2>
124 <span class="badge" id="agent-count">0</span>
125 <div class="spacer"></div>
126 <button class="small" onclick="loadAgents()">↻ refresh</button>
127 </div>
128 <div class="card-body" style="padding:0">
129 <div id="agents-container"></div>
130 </div>
131 </div>
132
133 <!-- Register -->
134 <div class="card">
135 <div class="card-header"><h2>register agent</h2></div>
136 <div class="card-body">
137 <form id="register-form" onsubmit="handleRegister(event)">
138 <div class="form-row">
139 <div>
140 <label>nick *</label>
141 <input type="text" id="reg-nick" placeholder="my-agent-01" required>
142 </div>
143 <div>
144 <label>type</label>
145 <select id="reg-type">
146 <option value="operator">operator — human, +o + full permissions</option>
147 <option value="worker">worker — gets +v in channels</option>
148 <option value="orchestrator">orchestrator — gets +o in channels</option>
149 <option value="observer">observer — read-only</option>
150 </select>
151 </div>
152 </div>
153 <div>
154 <label>channels</label>
155 <input type="text" id="reg-channels" placeholder="#fleet, #ops, #project.foo">
156 <div class="hint">comma-separated; must start with #</div>
157 </div>
158 <div>
159 <label>permissions</label>
160 <input type="text" id="reg-permissions" placeholder="task.create, task.update">
161 <div class="hint">comma-separated message types this agent is allowed to send</div>
162 </div>
163 <div id="register-result" style="display:none"></div>
164 <div style="display:flex;justify-content:flex-end">
165 <button type="submit" class="primary">register</button>
166 </div>
167 </form>
168 </div>
169 </div>
170
171 <!-- Chat -->
172 <div class="card" id="chat-card" style="display:none">
173 <div class="card-header">
174 <h2>chat</h2>
175 <span class="badge" id="chat-channel-badge" style="display:none"></span>
176 <div class="spacer"></div>
177 <span id="chat-stream-status" style="font-size:11px;color:#8b949e"></span>
178 </div>
179 <div style="display:flex;height:440px">
180 <div id="chat-channel-list" style="width:140px;border-right:1px solid #30363d;overflow-y:auto;flex-shrink:0;padding:8px 0;display:flex;flex-direction:column">
181 <div style="padding:6px 12px;font-size:11px;text-transform:uppercase;letter-spacing:0.06em;color:#8b949e">channels</div>
182 <div style="padding:6px 8px;border-bottom:1px solid #21262d;display:flex;gap:4px">
183 <input type="text" id="join-channel-input" placeholder="#channel" style="flex:1;font-size:11px;padding:3px 6px" autocomplete="off">
184 <button class="small" onclick="joinChannel()" style="padding:3px 6px;font-size:11px">+</button>
185 </div>
186 </div>
187 <div style="display:flex;flex-direction:column;flex:1;min-width:0">
188 <div id="chat-messages" style="flex:1;overflow-y:auto;padding:12px 16px;display:flex;flex-direction:column;gap:2px">
189 <div class="empty" id="chat-placeholder">select a channel to view messages</div>
190 </div>
191 <div style="padding:10px 14px;border-top:1px solid #30363d;display:flex;gap:8px;align-items:center">
192 <input type="text" id="chat-nick-input" placeholder="your nick" style="width:110px;flex-shrink:0" autocomplete="off">
193 <input type="text" id="chat-text-input" placeholder="type a message…" style="flex:1" autocomplete="off">
194 <button class="primary small" id="chat-send-btn" onclick="sendChatMessage()">send</button>
195 </div>
196 </div>
197 </div>
198 </div>
199 </main>
200
201 <!-- Token modal -->
202 <div class="modal-overlay" id="token-modal">
203 <div class="modal">
204 <h3>set API token</h3>
205 <p style="font-size:13px;color:#8b949e;margin-bottom:14px">The token is printed to stderr when scuttlebot starts:<br><code style="color:#a5d6ff">level=INFO msg="api token" token=&lt;value&gt;</code></p>
206 <label>token</label>
207 <input type="text" id="token-input" placeholder="paste token here" autocomplete="off" spellcheck="false">
208 <div class="btn-row">
209 <button onclick="closeTokenModal()">cancel</button>
210 <button class="primary" onclick="saveToken()">save</button>
211 </div>
212 </div>
213 </div>
214
215 <script>
216 // --- token management ---
217 function getToken() { return localStorage.getItem('scuttlebot_token') || ''; }
218 function setToken(t) {
219 localStorage.setItem('scuttlebot_token', t);
220 updateTokenDisplay();
221 }
222 function updateTokenDisplay() {
223 const t = getToken();
224 const el = document.getElementById('token-display');
225 const banner = document.getElementById('no-token-banner');
226 if (t) {
227 el.textContent = t.slice(0, 8) + '…' + t.slice(-4);
228 banner.style.display = 'none';
229 } else {
230 el.textContent = 'not set';
231 banner.style.display = 'flex';
232 }
233 }
234 function openTokenModal() {
235 document.getElementById('token-input').value = getToken();
236 document.getElementById('token-modal').classList.add('open');
237 setTimeout(() => document.getElementById('token-input').focus(), 50);
238 }
239 function closeTokenModal() { document.getElementById('token-modal').classList.remove('open'); }
240 function saveToken() {
241 const v = document.getElementById('token-input').value.trim();
242 if (v) { setToken(v); closeTokenModal(); loadAll(); }
243 }
244 document.getElementById('token-modal').addEventListener('click', function(e) {
245 if (e.target === this) closeTokenModal();
246 });
247 document.addEventListener('keydown', function(e) {
248 if (e.key === 'Escape') closeTokenModal();
249 });
250
251 // --- API ---
252 async function api(method, path, body) {
253 const token = getToken();
254 const opts = { method, headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' } };
255 if (body !== undefined) opts.body = JSON.stringify(body);
256 const res = await fetch(path, opts);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257 if (res.status === 204) return null;
258 const data = await res.json().catch(() => ({ error: res.statusText }));
259 if (!res.ok) throw Object.assign(new Error(data.error || res.statusText), { status: res.status });
260 return data;
261 }
262
263 function copyText(text, btn) {
264 navigator.clipboard.writeText(text).then(() => {
265 const orig = btn.textContent;
266 btn.textContent = '✓';
267 setTimeout(() => { btn.textContent = orig; }, 1200);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268 });
269 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
271 // --- status ---
272 async function loadStatus() {
273 try {
274 const s = await api('GET', '/v1/status');
275 document.getElementById('stat-status').innerHTML = '<span class="dot green"></span>' + s.status;
 
 
 
 
 
276 document.getElementById('stat-uptime').textContent = s.uptime;
277 document.getElementById('stat-agents').textContent = s.agents;
278 const started = new Date(s.started);
279 document.getElementById('stat-started').textContent = started.toLocaleTimeString();
280 document.getElementById('stat-started-rel').textContent = started.toLocaleDateString();
281 document.getElementById('status-error').style.display = 'none';
282 } catch (e) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283 document.getElementById('stat-status').innerHTML = '<span class="dot red"></span>error';
284 const err = document.getElementById('status-error');
285 err.style.display = 'block';
286 err.innerHTML = renderAlert('error', e.message);
287 }
288 }
289
290 // --- agents ---
 
 
 
 
 
 
 
 
 
291 async function loadAgents() {
292 const container = document.getElementById('agents-container');
293 try {
294 const data = await api('GET', '/v1/agents');
295 const agents = data.agents || [];
296 document.getElementById('agent-count').textContent = agents.length;
297 if (agents.length === 0) {
298 container.innerHTML = '<div class="empty">no agents registered yet</div>';
299 return;
300 }
301 let rows = agents.map(a => {
302 const channels = (a.config?.channels || []).map(c => `<span class="tag">${esc(c)}</span>`).join('');
303 const perms = (a.config?.permissions || []).map(p => `<span class="tag">${esc(p)}</span>`).join('');
304 const revoked = a.revoked_at ? '<span class="tag revoked">revoked</span>' : '';
305 return `<tr>
306 <td><strong>${esc(a.nick)}</strong></td>
307 <td><span class="tag type-${a.type}">${esc(a.type)}</span>${revoked}</td>
308 <td>${channels || '<span style="color:#8b949e">—</span>'}</td>
309 <td>${perms || '<span style="color:#8b949e">—</span>'}</td>
310 <td>${fmtTime(a.created_at)}</td>
311 <td>
312 <div class="actions">
313 ${!a.revoked_at ? `<button class="small" onclick="rotateAgent('${esc(a.nick)}')">rotate</button>
314 <button class="small danger" onclick="revokeAgent('${esc(a.nick)}')">revoke</button>` : ''}
315 </div>
316 </td>
317 </tr>`;
318 }).join('');
319 container.innerHTML = `<table>
320 <thead><tr><th>nick</th><th>type</th><th>channels</th><th>permissions</th><th>registered</th><th>actions</th></tr></thead>
321 <tbody>${rows}</tbody>
322 </table>`;
323 } catch (e) {
324 container.innerHTML = renderAlert('error', e.message);
325 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326 }
327
328 async function revokeAgent(nick) {
329 if (!confirm(`Revoke agent "${nick}"? This cannot be undone.`)) return;
330 try {
331 await api('POST', `/v1/agents/${nick}/revoke`);
332 await loadAgents();
333 await loadStatus();
334 } catch(e) {
335 alert('Revoke failed: ' + e.message);
336 }
337 }
338
339 async function rotateAgent(nick) {
340 try {
341 const creds = await api('POST', `/v1/agents/${nick}/rotate`);
 
342 showCredentials(nick, creds, null, 'rotate');
343 } catch(e) {
344 alert('Rotate failed: ' + e.message);
345 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346 }
347
348 // --- register ---
349 async function handleRegister(e) {
350 e.preventDefault();
351 const nick = document.getElementById('reg-nick').value.trim();
352 const type = document.getElementById('reg-type').value;
353 const channelsRaw = document.getElementById('reg-channels').value;
354 const permsRaw = document.getElementById('reg-permissions').value;
355
356 const channels = channelsRaw.split(',').map(s => s.trim()).filter(Boolean);
357 const permissions = permsRaw.split(',').map(s => s.trim()).filter(Boolean);
358
359 const resultEl = document.getElementById('register-result');
360 resultEl.style.display = 'none';
361
362 try {
363 const res = await api('POST', '/v1/agents/register', { nick, type, channels, permissions });
364 showCredentials(nick, res.credentials, res.payload, 'register');
365 document.getElementById('register-form').reset();
366 await loadAgents();
367 await loadStatus();