diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 6c54739d..e64548f9 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "gbrain", - "version": "0.48.5.0", + "version": "0.49.0.0", "description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.", "author": { "name": "Garry Tan", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 0ea19905..5c957810 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "gbrain", - "version": "0.48.5.0", + "version": "0.49.0.0", "description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.", "author": { "name": "Garry Tan", diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index cd05ca89..08a3f21b 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -63,7 +63,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile # This job runs bare `bun test` (not run-e2e.sh), so the snapshot must # be activated here or the restored tar is never read (the engine gates @@ -156,7 +156,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile - name: Select and run diff-relevant E2E files env: @@ -228,7 +228,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile # Bare `bun test` job — activate the restored snapshot (see jsonb-parity). - name: Ensure PGLite snapshot (build-or-validate, non-fatal) @@ -357,7 +357,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile # Bare `bun test` job — activate the restored snapshot (see jsonb-parity). - name: Ensure PGLite snapshot (build-or-validate, non-fatal) @@ -537,7 +537,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile - name: Full e2e glob with coverage (all files, incl. engine-parity) # run-e2e.sh redirects HOME, so COVERAGE_DIR must be absolute; its diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.yml index a59b2611..3cb754d3 100644 --- a/.github/workflows/semgrep.yml +++ b/.github/workflows/semgrep.yml @@ -39,6 +39,9 @@ jobs: env: BASE_SHA: ${{ github.event.pull_request.base.sha }} run: | + # The container user differs from checkout's owner. Trust only this + # workspace so our merge-base lookup works before Semgrep starts. + git config --global --add safe.directory "$GITHUB_WORKSPACE" if [ -n "$BASE_SHA" ]; then # Diff against the MERGE BASE, not the base-branch head captured at # event time: the checkout is the merge ref against current master, diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b44fb2b2..f92f9e7f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -102,7 +102,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile - run: bun run verify # Guard: no bare `bun test` in workflows/scripts — bun ignores @@ -150,7 +150,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile - run: bun run test:serial env: @@ -191,7 +191,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile - name: Ensure PGLite snapshot (build-or-validate, non-fatal) run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-eval && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"' @@ -235,7 +235,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile - name: Ensure PGLite snapshot (build-or-validate, non-fatal) # Absolutized: this file's batch jobs spawn CLI children with varying @@ -326,7 +326,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile - name: Ensure PGLite snapshot (build-or-validate, non-fatal) run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-perf && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"' @@ -408,7 +408,7 @@ jobs: path: | test/fixtures/pglite-snapshot.tar test/fixtures/pglite-snapshot.version - key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} + key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }} - run: bun install --frozen-lockfile - name: Run test shard ${{ matrix.shard }}/10 run: scripts/test-shard.sh ${{ matrix.shard }} 10 diff --git a/AGENTS.md b/AGENTS.md index 6b3695d3..6c1bca36 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,12 +4,13 @@ This is your install + operating protocol. Claude Code reads `./CLAUDE.md` autom Everyone else (Codex, Cursor, OpenClaw, Aider, Continue, or an LLM fetching via URL): start here. -> **Becoming someone's persistent personal agent** (identity + memory + private repo)? -> Follow [`BOOTSTRAP_FOR_AGENTS.md`](./BOOTSTRAP_FOR_AGENTS.md) — the `gbrain bootstrap` -> flow — instead of the plain install below, then come back here for the operating -> protocol. Connecting to an EXISTING remote brain from a laptop agent? -> `gbrain connect https://your-host/mcp --token gbrain_xxx --install` (see the MCP -> table in [`README.md`](./README.md)). +> **Default: add memory to the existing agent.** Preserve its identity and unrelated instructions. Start keyless; automatic capture and paid enrichment are opt-in. No bootstrap interview or private repository is required. +> +> **Inside Grok Bot or Muse:** follow [Grok Bot](docs/guides/grok-bot.md) or [Muse](docs/guides/muse.md), using the isolated [in-agent setup](docs/guides/in-agent-setup.md) entry point. Use the absolute recorded launcher on every call. Sources organize local memory; they do not isolate agents that share files or credentials. Do not mark generated skills or routines as activated without native-harness evidence. +> +> **Existing hosted brain:** follow [hosted harness access](docs/guides/hosted-harness-access.md). Provision on the host; install the private handoff inside the intended harness. A URL or ordinary OAuth token is not administration authority. +> +> **Creating a new personal agent, explicitly requested by the user:** follow [BOOTSTRAP_FOR_AGENTS.md](BOOTSTRAP_FOR_AGENTS.md), then return here for the operating protocol. ## Install (5 min) @@ -35,7 +36,11 @@ start here. exact ask-the-user protocol. Same banner fires on `gbrain post-upgrade` for existing users (search modes were added in v0.32.3). 4. Read [`./INSTALL_FOR_AGENTS.md`](./INSTALL_FOR_AGENTS.md) for the full step-by-step - flow (API keys, identity, cron, verification). + flow (keyless memory, optional API capabilities, maintenance, verification). + +## Memory operating protocol + +Recall relevant saved context before answering. Save explicit requests to remember with provenance; confirm corrections against the stored record. Automatic capture requires opt-in. Withdrawal (`forget`) removes a fact from active memory; history, source material, and private backups may remain. Never promise physical erasure. Verify changes with actual GBrain calls and distinguish a local test from a new-conversation test in the harness. ## Read this order diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md index 80220d0e..a867e7a6 100644 --- a/BOOTSTRAP_FOR_AGENTS.md +++ b/BOOTSTRAP_FOR_AGENTS.md @@ -1,4 +1,4 @@ - + @@ -251,11 +251,15 @@ placeholder). Trust the CLI's detection over your own guesses. Two things the human must UNDERSTAND before you finish — say them plainly, in this order, and confirm they landed: -1. **They own the brain.** Every memory you keep is a markdown file in THEIR - private GitHub repo — name the URL. Owning it means: they can read it any - time, take it to a second machine (`gbrain bootstrap attach`), or delete the - repo and the brain is gone. If they went local-only, say that instead, with - `gbrain bootstrap repo` as the any-time upgrade. +1. **They own the brain.** Their private GitHub repo holds the agent's identity + files and committed Markdown pages — name the URL. They can read those files + or clone the workspace on another machine and run `gbrain bootstrap attach`. + Facts, corrections, jobs, and accounting can exist only in the database, so + a Git clone is not a complete memory backup. Back up and restore the full + database separately. Deleting the repository does not erase database records, + history, source material, or backups. If they went local-only, say the files + and database remain on this machine; `gbrain bootstrap repo` can add a private + GitHub copy of the workspace files later. 2. **The first skill to run is cold-start.** An empty brain is a database; a filled one is a memory — and every flagship skill (book-mirror, briefings, meeting prep) only becomes magical once the brain holds their real life. diff --git a/CHANGELOG.md b/CHANGELOG.md index 69c5ddb8..ee667c95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,109 @@ All notable changes to GBrain will be documented in this file. +## [0.49.0.0] - 2026-09-10 + +**Add GBrain memory to the agent you already use, or connect that agent to +an existing hosted brain.** The setup guides now start with these two choices. +Grok Bot and Muse each have a dedicated walkthrough with a pasteable prompt, +a first memory round trip, recovery steps, and a clear record of what still +needs to be verified inside the actual harness. + +Local setup preserves your agent's identity and starts with keyless memory. +It installs its own runtime and an absolute launcher tied to the selected +brain, so changing folders or inheriting another project's database settings +does not redirect your memory. Repeated setup repairs the recorded software +without resetting the database. A private receipt records ownership, pending +steps, and the recovery command. Generated skills and maintenance instructions +remain pending until you enable and verify them in the harness. + +Hosted access now separates granting permissions on the brain host from +installing credentials in the intended agent. Six named profiles make the +choice explicit, with memory-writer as the default. Existing clients can be +repaired without replacing their ID or secret. Permission previews show the +change before it is applied, and interrupted credential delivery can recover +the original handoff. Delegation requires explicit tools and a write policy; +new delegation defaults to unlimited spending and one concurrent job. Existing +finite spending caps remain in place. + +| Your task | New path | +| --- | --- | +| Add memory inside Grok Bot or Muse | Isolated setup with a retained repair helper | +| Connect to an existing brain | Host grant, private handoff, harness installation | +| Recover local memory | Full private PGLite archive restored into a new root | +| Check an integration | Separate transport, permissions, memory, worker, and harness evidence | + +Backups now include database-only memory and managed files. Restore preserves +the original installation and leaves restored jobs and connectors inactive. +Withdrawing a fact keeps it out of active memory after source synchronization; +history, source material, and backups can remain. Actual Grok Bot and Muse +activation, persistence, and cross-conversation recall are still release checks, +not claims established by repository tests. + +## To take advantage of v0.49.0.0 + +1. **Hosted operators:** pause old servers, workers, and their restart loops; + take a protected backup, then install the new runtime and run + `gbrain apply-migrations --yes`. Follow + [the upgrade playbook](skills/migrations/v0.49.0.0.md) before restarting. + Do not run mixed authorization implementations against the migrated database. +2. **Inspect affected clients:** unusable legacy delegation is disabled with a + persisted repair reason while other access remains. Preview the explicit + repair with `gbrain auth rescope-client CLIENT_ID --dry-run` and the binding + flags from the playbook. Existing tokens gain no newly added scopes through + refresh; issue a new token when the scope grant grows. +3. **Choose your setup path:** start with the [README](README.md#choose-your-setup), + [Grok Bot guide](docs/guides/grok-bot.md), or [Muse guide](docs/guides/muse.md). + Existing local installs use their recorded absolute `bin/gbrain-setup` for + repair and `--upgrade` for an explicit software upgrade. Confirm the required + search-mode choice before enabling paid capabilities. +4. **Verify:** run `gbrain doctor`, then the memory round trip in your guide. + For hosted connections, `gbrain mcp verify ... --json` reports server checks + separately; exit 2 means actual-harness evidence remains incomplete. Read + [the acceptance checklist](docs/guides/harness-validation.md) before promoting + native support. If a step fails, preserve the installation and share redacted + diagnostics in a [GitHub issue](https://github.com/garrytan/gbrain/issues). + +### Itemized changes + +#### Added + +- Isolated Grok Bot and Muse setup, absolute launchers, versioned runtime repair, + ownership receipts, bounded busy errors, and pending native instructions. +- `backup create` and `backup restore` for private full PGLite archives, including + managed files, sanitized configuration, exclusion inventories, checksums, + relocation, and quarantine of unfinished work. Existing backup status/check + commands retain their behavior. +- Shared access profiles, grant revisions and audit records, secure host/client + handoff, credential recovery, adapter-driven configuration, and permission + previews in the CLI and admin UI. Addresses #5006. +- Authenticated `gbrain://capabilities`, public discovery metadata, and a verifier + that separates read/write checks, delegation configuration, worker completion, + cleanup, and actual-harness evidence. The seven-tool surface remains intact. + +#### Changed + +- New grants snapshot eligible operations and source access. Archived sources + are excluded. Renewable connections default to one-hour access tokens; static + adapters keep 30 days. Legacy `NULL` operation snapshots retain compatibility. +- Delegated work retains its submitted restrictions and the current client grant + at execution boundaries. Finite budgets reserve bounded calls and keep unknown + liabilities until reconciliation; unlimited usage remains attributed. +- New onboarding preserves identity and starts keyless. Automatic capture and + paid enrichment are opt-in. Dedicated guides distinguish Grok Bot from Grok + Build, Muse from Muse Code, and native memory from GBrain's explicit records. + +#### Fixed + +- Scope-only delegation without usable bindings is rejected or marked for repair + without broadening other permissions. Ordinary grant patches preserve omitted + restrictions, and stale edits fail before changing the client. +- Interrupted local initialization and upgrades resume schema work without + resetting memory or starting host automation. Local/thin conversion requires + explicit intent and does not copy ambient credentials into configuration. +- Fact withdrawals survive stale source reimport. Verification reconciles + uncertain mutations and confirms cleanup through readback. + ## [0.48.5.0] - 2026-09-07 **The community fix wave: 57 contributor pull requests adopted or reworked diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md index 339ddd24..c499f774 100644 --- a/INSTALL_FOR_AGENTS.md +++ b/INSTALL_FOR_AGENTS.md @@ -1,12 +1,12 @@ # GBrain Installation Guide for AI Agents -Read this entire file, then follow the steps. Ask the user for API keys when needed. -Target: ~30 minutes to a fully working brain. +Read this file, then follow the path appropriate to the user’s request. Default to adding keyless memory to their existing agent, preserving identity and unrelated configuration. API keys, enrichment, automatic capture, and a new personal-agent identity are separate choices. -> **Scope note:** this guide installs the BRAIN (for agent platforms like OpenClaw -> and Hermes, or a standalone brain). If you are Claude Code or Codex and the human -> asked you to become their persistent personal agent — identity + memory + private -> repo — follow `BOOTSTRAP_FOR_AGENTS.md` instead. +> **Choose the installation path first.** Inside **[Grok Bot](docs/guides/grok-bot.md)** or **[Muse](docs/guides/muse.md)**, use their dedicated guide and `scripts/setup-in-agent.sh`; its receipt tracks repair and native enablement. For an **[existing hosted brain](docs/guides/hosted-harness-access.md)**, provision on the host and install the private handoff inside the harness. This guide covers a local brain for other existing agents. +> +> **Memory-only path:** install → initialize → relay and confirm the Step 3.5 search-mode choice → connect the harness → verify memory. Skip identity replacement, private-repo bootstrap, automatic capture, cron installation, and paid enrichment unless requested. A keyword-only brain needs no API key. The required search-mode choice still applies; published API cost examples are not prices for the user’s harness subscription. +> +> Only if the user asks for a **new persistent personal agent** with identity and a private repo, follow `BOOTSTRAP_FOR_AGENTS.md`. ## Step 0: If you are not Claude Code @@ -62,7 +62,7 @@ restart the shell or add the PATH export to the shell profile. ## Step 2: API Keys -Ask the user for these. gbrain defaults to the Voyage embedding + reranker stack +Skip API-key setup for the initial keyless memory path. If the user enables semantic retrieval or paid enrichment, configure the selected provider explicitly. GBrain defaults to the Voyage embedding + reranker stack (`voyage:voyage-4` @ 1024d + `voyage:rerank-2.5` — one key covers both); OpenAI is the main alternative, chosen at init via `--embedding-model `. ZeroEntropy is deprecated (its hosted API shuts down 2026-09-04): init auto-pick and the picker @@ -99,11 +99,7 @@ gbrain doctor --json # verify all checks pass ``` The user's markdown files (notes, docs, brain repo) are SEPARATE from this tool repo. -Ask the user where their files are, or create a new brain repo: - -```bash -mkdir -p ~/brain && cd ~/brain && git init -``` +Use the user's chosen notes directory, or a separate managed memory directory. A Git repository is optional; do not create a private personal-agent repo for a memory-only install. Read `~/gbrain/docs/GBRAIN_RECOMMENDED_SCHEMA.md` and set up the MECE directory structure (people/, companies/, concepts/, etc.) inside the user's brain repo, diff --git a/README.md b/README.md index 1edbd179..6b24f44c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,13 @@ # GBrain -**Search gives you raw pages. GBrain gives you the answer.** It's the brain layer your AI agent has been missing — the only one that does synthesis, graph traversal, and gap analysis in one box. Run a full autonomous agent on top of it, or just wire it into Claude Code or Codex as a supercharged retrieval layer in one command; either way your coding agent stops being amnesiac about everything that isn't code. +**Give the agent you already use a memory you control.** GBrain stores explicit facts with their sources, supports corrections and withdrawal, and makes the same memory available across your agents. Start with keyless memory and keyword retrieval; add semantic search, synthesis, and background enrichment when you need them. + +## Choose your setup + +1. **Add GBrain to my existing agent — recommended.** Keep your agent's identity and save memory inside its environment. No new personal-agent identity or private repository is required. Start with the guide for **[Grok Bot](docs/guides/grok-bot.md)**, **[Muse](docs/guides/muse.md)**, or **[Codex / Claude Code](docs/tutorials/connect-coding-agent.md)**. [Other harnesses](#connect-gbrain-to-your-ai-client-mcp). +2. **Connect my existing hosted brain.** Grant access on the brain host, then install the private connection inside the intended harness. Follow **[hosted harness access](docs/guides/hosted-harness-access.md)**. The default profile can read and write memory; delegation is an explicit choice. + +Grok **Bot** and Grok **Build** are different products. Muse's personal agent and **Muse Code** are different products too. Muse already has native editable memory; GBrain adds an explicit, portable record with provenance and shared access. See each guide's dated evidence and remaining verification steps. I'm Garry Tan, President and CEO of Y Combinator. I built GBrain to run my own AI agents. It's the production brain behind my OpenClaw and Hermes deployments: **155,795 pages, 24,589 people, 5,340 companies**, 66 cron jobs running autonomously. My agent ingests meetings, emails, tweets, voice calls, and original ideas while I sleep. It enriches every person and company it encounters. It fixes its own citations and consolidates memory overnight. I wake up smarter than when I went to bed — and so will you. @@ -15,7 +22,7 @@ The point of building a 150K-page brain is to use it as a strategic moat. To nev It's easier to ship a daemon that runs 24/7 to ingest, enrich, and consolidate than it is to keep an agent in chat working hard. GBrain is that daemon, generalized. Install in 30 minutes. Your agent does the work. As my personal agent gets smarter, so does yours. -> **~15 minutes to a working personal agent** on the recommended Codex / Claude Code path (mostly a short interview); ~30 minutes for the always-on OpenClaw / Hermes setup. Database ready in 2 seconds either way (PGLite, no server). +> **Start keyless.** Your harness subscription and any separately configured model API usage are different costs. The optional personal-agent bootstrap takes about 15 minutes; always-on enrichment needs its own compute and API configuration. > **LLMs:** fetch [`llms.txt`](llms.txt) for the documentation map, or [`llms-full.txt`](llms-full.txt) for the same map with core docs inlined in one fetch. **Agents:** start with [`AGENTS.md`](AGENTS.md) (or [`CLAUDE.md`](CLAUDE.md) if you're Claude Code). @@ -75,9 +82,23 @@ This is the difference between a search engine and a brain. Search finds the pag > `bun remove -g gbrain`, then reinstall from GitHub. `gbrain doctor` detects a > shadowing npm install and prints the fix. -GBrain is designed to be installed and operated by an AI agent. **New to GBrain? Start with Codex** — it runs on the ChatGPT subscription you already have, takes ~15 minutes, and deploys nothing. Already living in Claude Code? Its path is identical. Want GBrain running the way it was designed to run — always on, enriching your brain around the clock? That's OpenClaw or Hermes, at real server + API cost. Each path below is complete on its own. (Wiring it up by hand instead? Jump to [CLI standalone](#cli-standalone-no-agent) or the [MCP table](#connect-gbrain-to-your-ai-client-mcp).) +Start with the agent you already use. For Grok Bot and Muse, the dedicated guides above install an isolated launcher, repairable runtime, and memory in a verified persistent directory. For a coding agent, paste: -### For Codex — the recommended first step +```text +Add GBrain memory to this existing agent. Read and follow: +https://raw.githubusercontent.com/garrytan/gbrain/master/INSTALL_FOR_AGENTS.md +Keep my current identity and instructions. Start keyless, preserve unrelated +configuration, and use the memory-only path. Do not create a personal-agent +identity or private repository. Show me the required search-mode choice. +Verify a unique remember/recall/correction/withdrawal round trip using observed +GBrain calls, then tell me how to verify recall in a new conversation. +``` + +[Codex guide](docs/mcp/CODEX.md) · [Claude Code guide](docs/mcp/CLAUDE_CODE.md) · [Memory-only walkthrough](docs/tutorials/connect-coding-agent.md) · [CLI standalone](#cli-standalone-no-agent). + +The following bootstrap paths are optional: use them when you want GBrain to help create a **new persistent personal agent**, including identity files and a private repository. + +### For Codex — optional personal-agent bootstrap Turn Codex into your persistent personal agent. (Just want the brain + skills without the full agent? `codex plugin marketplace add garrytan/gbrain@codex-plugin` then `codex plugin add gbrain@gbrain` — see [docs/mcp/CODEX.md](docs/mcp/CODEX.md). The paste block below builds the whole agent.) Works in the **ChatGPT desktop app** (open Codex on a folder) and in the **Codex CLI** (`codex` in a terminal) — same install, same result. Open Codex in a **new, empty folder** (not an existing code project) — that folder becomes your agent's own **private GitHub repo**, which bootstrap creates and privacy-verifies for you. Then paste: @@ -92,11 +113,11 @@ answers. Ask before anything destructive. You are not done until Codex will ask for command approvals during the install — approving them is the sandbox working as intended. What you get, in about 15 minutes: a short interview (6 required questions) → your agent's identity (SOUL.md, USER.md, MEMORY.md) rendered from your own answers, never invented → a local PGLite brain (2 seconds, no server, no Docker) → MCP wired so every session can search and write memory → a **private** GitHub repo, created and privacy-verified, as your agent's durable body. Works with **zero API keys** — keyword search plus memory your agent writes itself; one optional key upgrades capabilities (OpenAI: semantic search + automatic fact extraction; Voyage: semantic search; Anthropic: fact extraction). Codex reads brain context through its tools each turn (pull-based). The click moment: tell it one small thing to remember, restart Codex, then ask for it back — the answer comes from the brain, not from this chat's context (which the restart cleared). That cross-session round-trip is the whole product; "what's my name / my top jobs?" is answered from your identity files, which is nice but not the same trick. -Two things worth understanding once it's running: **you own the brain** — every memory is a markdown file in that private repo (read it, clone it to a second machine, delete it and the brain is gone) — and **the first skill to run is `cold-start`**: say "fill my brain" and your agent imports your Gmail, calendar, and contacts — via the native connector (`gbrain google setup`, tokens in gbrain's local credential vault, never held by the agent), via [ClawVisor](https://clawvisor.com) (a hosted OAuth gateway), or from offline archives like Google Takeout — one consented step at a time. An empty brain is a database; a filled one is a memory. +Two things worth understanding once it's running: **you own the brain** — the repo holds managed source files, while the database also holds facts, corrections, jobs, and accounting. A Git clone alone is not a complete backup; use [complete backup and restoration](docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database) — and **the first skill to run is `cold-start`**: say "fill my brain" and your agent imports your Gmail, calendar, and contacts — via the native connector (`gbrain google setup`, tokens in gbrain's local credential vault, never held by the agent), via [ClawVisor](https://clawvisor.com) (a hosted OAuth gateway), or from offline archives like Google Takeout — one consented step at a time. An empty brain is a database; a filled one is a memory. > **Prefer to make the repo yourself?** Create a new **empty** private repo **under your own GitHub account** (no README/.gitignore/license), clone it, open the clone in Codex, and paste the same block — bootstrap detects your empty repo and adopts it instead of creating one. The repo must be empty and personal-account-owned; org-owned repos are refused (create one under your account, or let bootstrap make it). -### For Claude Code — turn it into your persistent personal agent +### For Claude Code — optional personal-agent bootstrap Works in the **desktop app** and in the **CLI** (`claude` in a terminal) — identical harness, identical result. Open Claude Code in a **new, empty folder** (not an existing code project) — that folder becomes your agent's own **private GitHub repo**, created and privacy-verified for you. Then paste the same block: @@ -109,7 +130,7 @@ answers. Ask before anything destructive. You are not done until `gbrain bootstrap verify` exits 0. ``` -Everything from the Codex path applies — interview, identity from your own answers, local brain, private repo, keyless mode — plus Claude Code gets **per-turn context hooks** (on by default, with an opt-out): your brain loads automatically into every prompt, and your work persists to your private repo on a per-turn cadence (debounced ~5 min locally, every turn in a cloud sandbox — this covers the `/exit` case the harness never fires a session-end hook on), with a notice on your next turn if a push ever fails. This works in a **Claude Code cloud session** too, not just on your laptop: verification falls back to pure git protocol when the sandbox blocks the GitHub API, and `gbrain bootstrap cloud-setup-script` prints the environment setup recipe. The click moment: tell it one small thing to remember, restart the session, then ask for it back — a fresh session has no chat context, so the answer can only come from the brain. That cross-session round-trip is the whole product ("what's my name?" is answered from your identity files — nice, but not the same trick). Same two follow-ups as the Codex path: you own the brain (markdown in your private repo), and `cold-start` is the first skill to run — "fill my brain" imports your email, calendar, and contacts (ClawVisor) or offline archives, one consented step at a time. Full contract, security posture, cloud sandboxes, and uninstall: [docs/guides/bootstrap.md](docs/guides/bootstrap.md). +Everything from the Codex path applies — interview, identity from your own answers, local brain, private repo, keyless mode — plus Claude Code gets **per-turn context hooks** (on by default, with an opt-out): your brain loads automatically into every prompt, and your work persists to your private repo on a per-turn cadence (debounced ~5 min locally, every turn in a cloud sandbox — this covers the `/exit` case the harness never fires a session-end hook on), with a notice on your next turn if a push ever fails. This works in a **Claude Code cloud session** too, not just on your laptop: verification falls back to pure git protocol when the sandbox blocks the GitHub API, and `gbrain bootstrap cloud-setup-script` prints the environment setup recipe. The click moment: tell it one small thing to remember, restart the session, then ask for it back — a fresh session has no chat context, so the answer can only come from the brain. That cross-session round-trip is the whole product ("what's my name?" is answered from your identity files — nice, but not the same trick). Same two follow-ups as the Codex path: you own the brain (managed markdown plus database state; use a full database backup), and `cold-start` is the first skill to run — "fill my brain" imports your email, calendar, and contacts (ClawVisor) or offline archives, one consented step at a time. Full contract, security posture, cloud sandboxes, and uninstall: [docs/guides/bootstrap.md](docs/guides/bootstrap.md). > **Prefer to make the repo yourself?** Create a new **empty** private repo **under your own GitHub account** (no README/.gitignore/license), clone it, open the clone in Claude Code (CLI or the desktop app's open-a-repo flow), and paste the same block — bootstrap adopts your empty repo instead of creating one. The repo must be empty and personal-account-owned; org-owned repos are refused. @@ -169,7 +190,9 @@ Postgres-at-scale, Supabase, and thin-client setup paths live in [`docs/INSTALL. ### Connect GBrain to your AI client (MCP) -GBrain exposes nearly all of its 100+ operations as MCP tools (stdio and HTTP; a handful of local-only ops stay CLI-side) — or exactly the seven memory verbs with `--surface verbs`. The specific snippet depends on which client you use: +For a hosted brain, start with the [private handoff and profile guide](docs/guides/hosted-harness-access.md). A **profile** controls authority; a **surface** controls which granted tools are visible. New memory profiles use the starter surface. `--surface verbs` retains exactly the seven memory verbs, with orientation available through `gbrain://capabilities`. Thin CLI connections use the full surface and remain restricted by their grants. + +The existing connection commands below remain supported. Choose the instructions for your actual product: **Upgrading an existing brain:** existing search chunks need rebuilding before remote chunk retrieval resumes. Semantic result caching is temporarily disabled; @@ -179,9 +202,11 @@ commands, embedding costs, and the restrictions that remain after rebuilding. **Say to your agent:** *"Upgrade gbrain and check whether my search index needs rebuilding."* - **[Claude Code](docs/mcp/CLAUDE_CODE.md)** — plugin: `/plugin marketplace add garrytan/gbrain` + `/plugin install gbrain@gbrain` (MCP + skills; persona variants `gbrain-coding` / `gbrain-daily` install curated subsets — pick exactly one gbrain plugin). Marketplace-free skills: `gbrain skillpack scaffold --harness claude-code` copies a persona-curated skill set into your user-scope skills dir with a local-edit-respecting update lens. Or local one-liner: `claude mcp add gbrain -- gbrain serve` (zero server, zero tunnel). Remote with just a bearer token: `gbrain connect https://your-host/mcp --token gbrain_xxx` prints a paste-ready block (or `--install` wires it up and smoke-tests the token). -- **[Codex](docs/mcp/CODEX.md)** — plugin (recommended): `codex plugin marketplace add garrytan/gbrain@codex-plugin` + `codex plugin add gbrain@gbrain` installs the MCP server AND the curated skill set. Or connect-only: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex` (or `--install`); Codex reads the bearer from `$GBRAIN_REMOTE_TOKEN` at runtime, so the token never lands in Codex config. +- **[Codex](docs/mcp/CODEX.md)** — plugin (recommended): `codex plugin marketplace add garrytan/gbrain@codex-plugin` + `codex plugin add gbrain@gbrain` installs the MCP server AND the curated skill set. Or connect-only: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex` (or `--install`); That legacy path reads `$GBRAIN_REMOTE_TOKEN` at runtime. The new private-handoff installer writes a private managed HTTP header so the connection survives a new shell. - **[Cursor / Windsurf / any stdio MCP client](docs/mcp/CLAUDE_CODE.md)** — same shape, add `{"command": "gbrain", "args": ["serve"]}` to your MCP config. - **[Hermes](docs/mcp/HERMES.md)** — `printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve`. Keep `--args` last, and verify with `hermes mcp test gbrain` (the add exits 0 even on failure). +- **[Grok Bot](docs/guides/grok-bot.md)** — install memory inside the Bot computer at `/workspace/gbrain`, or connect a hosted brain through an isolated CLI. Bots share local files and credentials; sources organize memory without isolating Bots. +- **[Muse personal agent](docs/guides/muse.md)** — first verify its durable user-files location, then install the local CLI. Native MCP configuration and skill activation are not assumed. - **[Grok Build](docs/mcp/GROK.md)** — `grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- gbrain serve --surface verbs`. The add is lazy (exit 0 without connecting) — verify with `grok mcp doctor gbrain`, which spawns the server and reports `7 tools discovered`. Verified against Grok Build v1.0.4. - **[opencode](docs/mcp/OPENCODE.md)** (opencode.ai / SST — not OpenClaw) — `opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- gbrain serve --surface verbs`, or let `gbrain bootstrap hooks --harness opencode` write the config for you (opencode is a bootstrap-supported harness — it reads AGENTS.md natively). The add is lazy — verify with `opencode mcp list`, which spawns the server (`✓ gbrain connected`). Remote: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent opencode [--install]` — the config stores only the `{env:GBRAIN_REMOTE_TOKEN}` interpolation. Verified against opencode v1.18.18. - **[OpenClaw](docs/mcp/OPENCLAW.md)** — the ClawHub bundle plugin registers gbrain automatically (`openclaw.plugin.json` ships in this repo), or add `{"command": "gbrain", "args": ["serve"]}` to `~/.openclaw/config.json`'s `mcpServers`. @@ -198,7 +223,7 @@ gbrain serve --http # HTTP MCP with OAuth 2.1 + admin dashboard at /admin # (required for Claude Desktop, Cowork, Perplexity, ChatGPT) ``` -The HTTP server includes DCR-style client registration, scope-gated access (`read` / `write` / `admin`), and rate limiting. Deployment guides (ngrok, Railway, Fly.io) live under [`docs/mcp/`](docs/mcp/). +The HTTP server includes optional dynamic client registration, scope-gated access (`read` / `write` / `admin` / `agent`), owner-approved OAuth authorization, and rate limiting. Dynamic registration cannot grant delegation; `admin` does not imply `agent`. Deployment guides (ngrok, Railway, Fly.io) live under [`docs/mcp/`](docs/mcp/). Running several brains behind one tool catalog? Give each one an identity: `gbrain config set mcp.instructions "Team wiki brain — route product and roadmap questions here"` rides every transport's initialize response under a `Deployment identity:` banner, so a connected agent can tell your brains apart. Restart `gbrain serve` to pick it up; `GBRAIN_MCP_INSTRUCTIONS` in the serve process's environment overrides it for that process, and `gbrain config unset mcp.instructions` returns to the bare contract. **Say to your agent:** *"Tell connected agents which brain this is"* — your agent runs `gbrain config set mcp.instructions ""`. @@ -363,7 +388,7 @@ Want to see a tutorial that isn't here yet? [Open an issue](https://github.com/g message) retrieval) by context) timeline) + backlinks) keeps fresh) ``` -- **Signal detector** runs on every message your agent receives. Captures ideas, entity mentions, time-sensitive todos, names, links. +- **Signal detector**, after you opt in, captures durable ideas and entity mentions from substantive messages. Explicit remembering works without automatic capture; paid enrichment is a separate choice. - **Brain-first lookup** before any external API call. The cheapest, fastest, most personal information source you have. - **Auto-link** fires on every page write. No LLM calls; pure pattern matching on `[[wiki/people/bob]]` style references. New entity → new page stub → graph grows. - **Cron-driven enrichment** runs while you sleep: dedup people pages, fix citations, score salience, find contradictions, prep tomorrow's tasks. @@ -435,7 +460,7 @@ memorable show procedures/ab12cd34-fix-failing-order-tests # ./test.sh verified it — the steps, in order, with real outcomes ``` -Your agent skips the diagnosis it already did once and goes straight to the fix. That's the whole product: **capture is automatic** (nothing to remember at the end of a session), and **recall is one command** at the start of the next. +Your agent skips the diagnosis it already did once and goes straight to the fix. After you explicitly enable Memorable's capture, **capture is automatic** for that integration, and **recall is one command** at the start of the next. Installing GBrain alone does not enable automatic conversation capture. **Say to your agent:** *"Set up Memorable so you remember how tasks were done"* — your agent installs and initializes the CLI (`npm i -g memorable-cli`, `memorable init`, `memorable enable`); you then run the one consent step below yourself. Day to day: *"Before you start, check Memorable for how we did this last time"* — your agent runs `memorable recall ""` — and *"What has Memorable stored so far?"* — your agent runs `memorable list`. diff --git a/TODOS.md b/TODOS.md index 6eca0662..5f14fe79 100644 --- a/TODOS.md +++ b/TODOS.md @@ -1473,18 +1473,6 @@ deferred M-effort issues above are NOT repeated here. base-phase.ts. **Effort:** S each. **P3.** ## Multi-agent wave follow-ups (cathedral-6, `gbrain agent register`) -- [ ] **P2 — archived sources keep previously-granted federated reads until - re-registration.** **What:** grants are validated at mint time only — a - client whose `federated_read` names a source that is archived AFTER - registration keeps reading it; there is no per-request archived-source - filtering and no grant invalidation on archive. **How:** this is a - platform-wide read-path decision affecting every federated op (recall, - search, entity, boundary verbs), not just recall — either fold an - `archived = false` join into the shared source-scope resolution or sweep - grants on `sources archive`; decide once, apply everywhere. **Where:** - `src/core/ops/context.ts` (sourceScopeOpts consumers), engine read paths, - `src/core/destructive-guard.ts` (archive lifecycle). **Effort:** M. - **Priority:** P2. - [ ] **P2 — federate the remaining read verbs across allowedSources.** **What:** `recall` now honors a federated grant (every fact arm fans out across `ctx.auth.allowedSources` and merges per-arm — see the `factSources` @@ -7128,6 +7116,23 @@ keeping both skills' triggers intact for chaining. ## Completed +- [x] **P2 — archived sources keep previously-granted federated reads until + re-registration.** **What:** grants are validated at mint time only — a + client whose `federated_read` names a source that is archived AFTER + registration keeps reading it; there is no per-request archived-source + filtering and no grant invalidation on archive. **How:** this is a + platform-wide read-path decision affecting every federated op (recall, + search, entity, boundary verbs), not just recall — either fold an + `archived = false` join into the shared source-scope resolution or sweep + grants on `sources archive`; decide once, apply everywhere. **Where:** + `src/core/ops/context.ts` (sourceScopeOpts consumers), engine read paths, + `src/core/destructive-guard.ts` (archive lifecycle). **Effort:** M. + **Priority:** P2. + **Completed:** v0.49.0.0 (2026-09-10). OAuth clients, including legacy NULL + operation snapshots, now recheck active sources on every authenticated + request. The scalar archived source also clears effective scopes. + + ### ~~(v0.42.20.0 follow-up) Decouple the op-dispatch force-exit timer~~ **Completed:** v0.42.39.0 (2026-06-10) diff --git a/VERSION b/VERSION index b8afe4c1..f44b94e1 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.48.5.0 +0.49.0.0 diff --git a/admin/dist/assets/index-B5gNvpC1.js b/admin/dist/assets/index-B5gNvpC1.js new file mode 100644 index 00000000..5bb9faa2 --- /dev/null +++ b/admin/dist/assets/index-B5gNvpC1.js @@ -0,0 +1,52 @@ +(function(){const E=document.createElement("link").relList;if(E&&E.supports&&E.supports("modulepreload"))return;for(const D of document.querySelectorAll('link[rel="modulepreload"]'))r(D);new MutationObserver(D=>{for(const _ of D)if(_.type==="childList")for(const H of _.addedNodes)H.tagName==="LINK"&&H.rel==="modulepreload"&&r(H)}).observe(document,{childList:!0,subtree:!0});function T(D){const _={};return D.integrity&&(_.integrity=D.integrity),D.referrerPolicy&&(_.referrerPolicy=D.referrerPolicy),D.crossOrigin==="use-credentials"?_.credentials="include":D.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function r(D){if(D.ep)return;D.ep=!0;const _=T(D);fetch(D.href,_)}})();function Cd(f){return f&&f.__esModule&&Object.prototype.hasOwnProperty.call(f,"default")?f.default:f}var sf={exports:{}},zn={};/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var bd;function fy(){if(bd)return zn;bd=1;var f=Symbol.for("react.transitional.element"),E=Symbol.for("react.fragment");function T(r,D,_){var H=null;if(_!==void 0&&(H=""+_),D.key!==void 0&&(H=""+D.key),"key"in D){_={};for(var G in D)G!=="key"&&(_[G]=D[G])}else _=D;return D=_.ref,{$$typeof:f,type:r,key:H,ref:D!==void 0?D:null,props:_}}return zn.Fragment=E,zn.jsx=T,zn.jsxs=T,zn}var Sd;function sy(){return Sd||(Sd=1,sf.exports=fy()),sf.exports}var c=sy(),of={exports:{}},K={};/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var xd;function oy(){if(xd)return K;xd=1;var f=Symbol.for("react.transitional.element"),E=Symbol.for("react.portal"),T=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),D=Symbol.for("react.profiler"),_=Symbol.for("react.consumer"),H=Symbol.for("react.context"),G=Symbol.for("react.forward_ref"),O=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),C=Symbol.for("react.lazy"),M=Symbol.for("react.activity"),N=Symbol.iterator;function w(m){return m===null||typeof m!="object"?null:(m=N&&m[N]||m["@@iterator"],typeof m=="function"?m:null)}var J={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},il=Object.assign,jl={};function ul(m,A,R){this.props=m,this.context=A,this.refs=jl,this.updater=R||J}ul.prototype.isReactComponent={},ul.prototype.setState=function(m,A){if(typeof m!="object"&&typeof m!="function"&&m!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,m,A,"setState")},ul.prototype.forceUpdate=function(m){this.updater.enqueueForceUpdate(this,m,"forceUpdate")};function k(){}k.prototype=ul.prototype;function Z(m,A,R){this.props=m,this.context=A,this.refs=jl,this.updater=R||J}var Tl=Z.prototype=new k;Tl.constructor=Z,il(Tl,ul.prototype),Tl.isPureReactComponent=!0;var wl=Array.isArray;function Hl(){}var al={H:null,A:null,T:null,S:null},kl=Object.prototype.hasOwnProperty;function _e(m,A,R){var q=R.ref;return{$$typeof:f,type:m,key:A,ref:q!==void 0?q:null,props:R}}function Lt(m,A){return _e(m.type,A,m.props)}function Oe(m){return typeof m=="object"&&m!==null&&m.$$typeof===f}function Wl(m){var A={"=":"=0",":":"=2"};return"$"+m.replace(/[=:]/g,function(R){return A[R]})}var zt=/\/+/g;function Ue(m,A){return typeof m=="object"&&m!==null&&m.key!=null?Wl(""+m.key):A.toString(36)}function ze(m){switch(m.status){case"fulfilled":return m.value;case"rejected":throw m.reason;default:switch(typeof m.status=="string"?m.then(Hl,Hl):(m.status="pending",m.then(function(A){m.status==="pending"&&(m.status="fulfilled",m.value=A)},function(A){m.status==="pending"&&(m.status="rejected",m.reason=A)})),m.status){case"fulfilled":return m.value;case"rejected":throw m.reason}}throw m}function x(m,A,R,q,W){var I=typeof m;(I==="undefined"||I==="boolean")&&(m=null);var ol=!1;if(m===null)ol=!0;else switch(I){case"bigint":case"string":case"number":ol=!0;break;case"object":switch(m.$$typeof){case f:case E:ol=!0;break;case C:return ol=m._init,x(ol(m._payload),A,R,q,W)}}if(ol)return W=W(m),ol=q===""?"."+Ue(m,0):q,wl(W)?(R="",ol!=null&&(R=ol.replace(zt,"$&/")+"/"),x(W,A,R,"",function(Na){return Na})):W!=null&&(Oe(W)&&(W=Lt(W,R+(W.key==null||m&&m.key===W.key?"":(""+W.key).replace(zt,"$&/")+"/")+ol)),A.push(W)),1;ol=0;var Kl=q===""?".":q+":";if(wl(m))for(var _l=0;_l>>1,gl=x[hl];if(0>>1;hlD(R,V))qD(W,R)?(x[hl]=W,x[q]=V,hl=q):(x[hl]=R,x[A]=V,hl=A);else if(qD(W,V))x[hl]=W,x[q]=V,hl=q;else break l}}return U}function D(x,U){var V=x.sortIndex-U.sortIndex;return V!==0?V:x.id-U.id}if(f.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var _=performance;f.unstable_now=function(){return _.now()}}else{var H=Date,G=H.now();f.unstable_now=function(){return H.now()-G}}var O=[],h=[],C=1,M=null,N=3,w=!1,J=!1,il=!1,jl=!1,ul=typeof setTimeout=="function"?setTimeout:null,k=typeof clearTimeout=="function"?clearTimeout:null,Z=typeof setImmediate<"u"?setImmediate:null;function Tl(x){for(var U=T(h);U!==null;){if(U.callback===null)r(h);else if(U.startTime<=x)r(h),U.sortIndex=U.expirationTime,E(O,U);else break;U=T(h)}}function wl(x){if(il=!1,Tl(x),!J)if(T(O)!==null)J=!0,Hl||(Hl=!0,Wl());else{var U=T(h);U!==null&&ze(wl,U.startTime-x)}}var Hl=!1,al=-1,kl=5,_e=-1;function Lt(){return jl?!0:!(f.unstable_now()-_ex&&Lt());){var hl=M.callback;if(typeof hl=="function"){M.callback=null,N=M.priorityLevel;var gl=hl(M.expirationTime<=x);if(x=f.unstable_now(),typeof gl=="function"){M.callback=gl,Tl(x),U=!0;break e}M===T(O)&&r(O),Tl(x)}else r(O);M=T(O)}if(M!==null)U=!0;else{var m=T(h);m!==null&&ze(wl,m.startTime-x),U=!1}}break l}finally{M=null,N=V,w=!1}U=void 0}}finally{U?Wl():Hl=!1}}}var Wl;if(typeof Z=="function")Wl=function(){Z(Oe)};else if(typeof MessageChannel<"u"){var zt=new MessageChannel,Ue=zt.port2;zt.port1.onmessage=Oe,Wl=function(){Ue.postMessage(null)}}else Wl=function(){ul(Oe,0)};function ze(x,U){al=ul(function(){x(f.unstable_now())},U)}f.unstable_IdlePriority=5,f.unstable_ImmediatePriority=1,f.unstable_LowPriority=4,f.unstable_NormalPriority=3,f.unstable_Profiling=null,f.unstable_UserBlockingPriority=2,f.unstable_cancelCallback=function(x){x.callback=null},f.unstable_forceFrameRate=function(x){0>x||125hl?(x.sortIndex=V,E(h,x),T(O)===null&&x===T(h)&&(il?(k(al),al=-1):il=!0,ze(wl,V-hl))):(x.sortIndex=gl,E(O,x),J||w||(J=!0,Hl||(Hl=!0,Wl()))),x},f.unstable_shouldYield=Lt,f.unstable_wrapCallback=function(x){var U=N;return function(){var V=N;N=U;try{return x.apply(this,arguments)}finally{N=V}}}})(hf)),hf}var Td;function dy(){return Td||(Td=1,df.exports=ry()),df.exports}var mf={exports:{}},Vl={};/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Ad;function hy(){if(Ad)return Vl;Ad=1;var f=vf();function E(O){var h="https://react.dev/errors/"+O;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(f)}catch(E){console.error(E)}}return f(),mf.exports=hy(),mf.exports}/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var _d;function yy(){if(_d)return Tn;_d=1;var f=dy(),E=vf(),T=my();function r(l){var e="https://react.dev/errors/"+l;if(1gl||(l.current=hl[gl],hl[gl]=null,gl--)}function R(l,e){gl++,hl[gl]=l.current,l.current=e}var q=m(null),W=m(null),I=m(null),ol=m(null);function Kl(l,e){switch(R(I,e),R(W,l),R(q,null),e.nodeType){case 9:case 11:l=(l=e.documentElement)&&(l=l.namespaceURI)?Zr(l):0;break;default:if(l=e.tagName,e=e.namespaceURI)e=Zr(e),l=Lr(e,l);else switch(l){case"svg":l=1;break;case"math":l=2;break;default:l=0}}A(q),R(q,l)}function _l(){A(q),A(W),A(I)}function Na(l){l.memoizedState!==null&&R(ol,l);var e=q.current,t=Lr(e,l.type);e!==t&&(R(W,l),R(q,t))}function An(l){W.current===l&&(A(q),A(W)),ol.current===l&&(A(ol),bn._currentValue=V)}var Vu,gf;function Tt(l){if(Vu===void 0)try{throw Error()}catch(t){var e=t.stack.trim().match(/\n( *(at )?)/);Vu=e&&e[1]||"",gf=-1)":-1n||o[a]!==g[n]){var S=` +`+o[a].replace(" at new "," at ");return l.displayName&&S.includes("")&&(S=S.replace("",l.displayName)),S}while(1<=a&&0<=n);break}}}finally{Ku=!1,Error.prepareStackTrace=t}return(t=l?l.displayName||l.name:"")?Tt(t):""}function Gd(l,e){switch(l.tag){case 26:case 27:case 5:return Tt(l.type);case 16:return Tt("Lazy");case 13:return l.child!==e&&e!==null?Tt("Suspense Fallback"):Tt("Suspense");case 19:return Tt("SuspenseList");case 0:case 15:return Ju(l.type,!1);case 11:return Ju(l.type.render,!1);case 1:return Ju(l.type,!0);case 31:return Tt("Activity");default:return""}}function pf(l){try{var e="",t=null;do e+=Gd(l,t),t=l,l=l.return;while(l);return e}catch(a){return` +Error generating stack: `+a.message+` +`+a.stack}}var wu=Object.prototype.hasOwnProperty,ku=f.unstable_scheduleCallback,Wu=f.unstable_cancelCallback,Xd=f.unstable_shouldYield,Qd=f.unstable_requestPaint,ae=f.unstable_now,Zd=f.unstable_getCurrentPriorityLevel,bf=f.unstable_ImmediatePriority,Sf=f.unstable_UserBlockingPriority,En=f.unstable_NormalPriority,Ld=f.unstable_LowPriority,xf=f.unstable_IdlePriority,Vd=f.log,Kd=f.unstable_setDisableYieldValue,Da=null,ne=null;function Ie(l){if(typeof Vd=="function"&&Kd(l),ne&&typeof ne.setStrictMode=="function")try{ne.setStrictMode(Da,l)}catch{}}var ue=Math.clz32?Math.clz32:kd,Jd=Math.log,wd=Math.LN2;function kd(l){return l>>>=0,l===0?32:31-(Jd(l)/wd|0)|0}var _n=256,On=262144,Nn=4194304;function At(l){var e=l&42;if(e!==0)return e;switch(l&-l){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return l&261888;case 262144:case 524288:case 1048576:case 2097152:return l&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return l&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return l}}function Dn(l,e,t){var a=l.pendingLanes;if(a===0)return 0;var n=0,u=l.suspendedLanes,i=l.pingedLanes;l=l.warmLanes;var s=a&134217727;return s!==0?(a=s&~u,a!==0?n=At(a):(i&=s,i!==0?n=At(i):t||(t=s&~l,t!==0&&(n=At(t))))):(s=a&~u,s!==0?n=At(s):i!==0?n=At(i):t||(t=a&~l,t!==0&&(n=At(t)))),n===0?0:e!==0&&e!==n&&(e&u)===0&&(u=n&-n,t=e&-e,u>=t||u===32&&(t&4194048)!==0)?e:n}function Ma(l,e){return(l.pendingLanes&~(l.suspendedLanes&~l.pingedLanes)&e)===0}function Wd(l,e){switch(l){case 1:case 2:case 4:case 8:case 64:return e+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function jf(){var l=Nn;return Nn<<=1,(Nn&62914560)===0&&(Nn=4194304),l}function $u(l){for(var e=[],t=0;31>t;t++)e.push(l);return e}function Ca(l,e){l.pendingLanes|=e,e!==268435456&&(l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0)}function $d(l,e,t,a,n,u){var i=l.pendingLanes;l.pendingLanes=t,l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0,l.expiredLanes&=t,l.entangledLanes&=t,l.errorRecoveryDisabledLanes&=t,l.shellSuspendCounter=0;var s=l.entanglements,o=l.expirationTimes,g=l.hiddenUpdates;for(t=i&~t;0"u")return null;try{return l.activeElement||l.body}catch{return l.body}}var th=/[\n"\\]/g;function me(l){return l.replace(th,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function ti(l,e,t,a,n,u,i,s){l.name="",i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"?l.type=i:l.removeAttribute("type"),e!=null?i==="number"?(e===0&&l.value===""||l.value!=e)&&(l.value=""+he(e)):l.value!==""+he(e)&&(l.value=""+he(e)):i!=="submit"&&i!=="reset"||l.removeAttribute("value"),e!=null?ai(l,i,he(e)):t!=null?ai(l,i,he(t)):a!=null&&l.removeAttribute("value"),n==null&&u!=null&&(l.defaultChecked=!!u),n!=null&&(l.checked=n&&typeof n!="function"&&typeof n!="symbol"),s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"?l.name=""+he(s):l.removeAttribute("name")}function Hf(l,e,t,a,n,u,i,s){if(u!=null&&typeof u!="function"&&typeof u!="symbol"&&typeof u!="boolean"&&(l.type=u),e!=null||t!=null){if(!(u!=="submit"&&u!=="reset"||e!=null)){ei(l);return}t=t!=null?""+he(t):"",e=e!=null?""+he(e):t,s||e===l.value||(l.value=e),l.defaultValue=e}a=a??n,a=typeof a!="function"&&typeof a!="symbol"&&!!a,l.checked=s?l.checked:!!a,l.defaultChecked=!!a,i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(l.name=i),ei(l)}function ai(l,e,t){e==="number"&&Un(l.ownerDocument)===l||l.defaultValue===""+t||(l.defaultValue=""+t)}function Wt(l,e,t,a){if(l=l.options,e){e={};for(var n=0;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),fi=!1;if(Be)try{var Ba={};Object.defineProperty(Ba,"passive",{get:function(){fi=!0}}),window.addEventListener("test",Ba,Ba),window.removeEventListener("test",Ba,Ba)}catch{fi=!1}var lt=null,si=null,Hn=null;function Zf(){if(Hn)return Hn;var l,e=si,t=e.length,a,n="value"in lt?lt.value:lt.textContent,u=n.length;for(l=0;l=Ga),kf=" ",Wf=!1;function $f(l,e){switch(l){case"keyup":return Dh.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ff(l){return l=l.detail,typeof l=="object"&&"data"in l?l.data:null}var Pt=!1;function Ch(l,e){switch(l){case"compositionend":return Ff(e);case"keypress":return e.which!==32?null:(Wf=!0,kf);case"textInput":return l=e.data,l===kf&&Wf?null:l;default:return null}}function Uh(l,e){if(Pt)return l==="compositionend"||!mi&&$f(l,e)?(l=Zf(),Hn=si=lt=null,Pt=!1,l):null;switch(l){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:t,offset:e-l};l=a}l:{for(;t;){if(t.nextSibling){t=t.nextSibling;break l}t=t.parentNode}t=void 0}t=us(t)}}function cs(l,e){return l&&e?l===e?!0:l&&l.nodeType===3?!1:e&&e.nodeType===3?cs(l,e.parentNode):"contains"in l?l.contains(e):l.compareDocumentPosition?!!(l.compareDocumentPosition(e)&16):!1:!1}function fs(l){l=l!=null&&l.ownerDocument!=null&&l.ownerDocument.defaultView!=null?l.ownerDocument.defaultView:window;for(var e=Un(l.document);e instanceof l.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)l=e.contentWindow;else break;e=Un(l.document)}return e}function gi(l){var e=l&&l.nodeName&&l.nodeName.toLowerCase();return e&&(e==="input"&&(l.type==="text"||l.type==="search"||l.type==="tel"||l.type==="url"||l.type==="password")||e==="textarea"||l.contentEditable==="true")}var Qh=Be&&"documentMode"in document&&11>=document.documentMode,la=null,pi=null,La=null,bi=!1;function ss(l,e,t){var a=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;bi||la==null||la!==Un(a)||(a=la,"selectionStart"in a&&gi(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),La&&Za(La,a)||(La=a,a=Ou(pi,"onSelect"),0>=i,n-=i,Ne=1<<32-ue(e)+n|t<F?(tl=X,X=null):tl=X.sibling;var fl=p(y,X,v[F],j);if(fl===null){X===null&&(X=tl);break}l&&X&&fl.alternate===null&&e(y,X),d=u(fl,d,F),cl===null?Q=fl:cl.sibling=fl,cl=fl,X=tl}if(F===v.length)return t(y,X),nl&&Ye(y,F),Q;if(X===null){for(;FF?(tl=X,X=null):tl=X.sibling;var jt=p(y,X,fl.value,j);if(jt===null){X===null&&(X=tl);break}l&&X&&jt.alternate===null&&e(y,X),d=u(jt,d,F),cl===null?Q=jt:cl.sibling=jt,cl=jt,X=tl}if(fl.done)return t(y,X),nl&&Ye(y,F),Q;if(X===null){for(;!fl.done;F++,fl=v.next())fl=z(y,fl.value,j),fl!==null&&(d=u(fl,d,F),cl===null?Q=fl:cl.sibling=fl,cl=fl);return nl&&Ye(y,F),Q}for(X=a(X);!fl.done;F++,fl=v.next())fl=b(X,y,F,fl.value,j),fl!==null&&(l&&fl.alternate!==null&&X.delete(fl.key===null?F:fl.key),d=u(fl,d,F),cl===null?Q=fl:cl.sibling=fl,cl=fl);return l&&X.forEach(function(cy){return e(y,cy)}),nl&&Ye(y,F),Q}function vl(y,d,v,j){if(typeof v=="object"&&v!==null&&v.type===il&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case w:l:{for(var Q=v.key;d!==null;){if(d.key===Q){if(Q=v.type,Q===il){if(d.tag===7){t(y,d.sibling),j=n(d,v.props.children),j.return=y,y=j;break l}}else if(d.elementType===Q||typeof Q=="object"&&Q!==null&&Q.$$typeof===kl&&Bt(Q)===d.type){t(y,d.sibling),j=n(d,v.props),Wa(j,v),j.return=y,y=j;break l}t(y,d);break}else e(y,d);d=d.sibling}v.type===il?(j=Mt(v.props.children,y.mode,j,v.key),j.return=y,y=j):(j=Kn(v.type,v.key,v.props,null,y.mode,j),Wa(j,v),j.return=y,y=j)}return i(y);case J:l:{for(Q=v.key;d!==null;){if(d.key===Q)if(d.tag===4&&d.stateNode.containerInfo===v.containerInfo&&d.stateNode.implementation===v.implementation){t(y,d.sibling),j=n(d,v.children||[]),j.return=y,y=j;break l}else{t(y,d);break}else e(y,d);d=d.sibling}j=Ei(v,y.mode,j),j.return=y,y=j}return i(y);case kl:return v=Bt(v),vl(y,d,v,j)}if(ze(v))return B(y,d,v,j);if(Wl(v)){if(Q=Wl(v),typeof Q!="function")throw Error(r(150));return v=Q.call(v),L(y,d,v,j)}if(typeof v.then=="function")return vl(y,d,In(v),j);if(v.$$typeof===Z)return vl(y,d,kn(y,v),j);Pn(y,v)}return typeof v=="string"&&v!==""||typeof v=="number"||typeof v=="bigint"?(v=""+v,d!==null&&d.tag===6?(t(y,d.sibling),j=n(d,v),j.return=y,y=j):(t(y,d),j=Ai(v,y.mode,j),j.return=y,y=j),i(y)):t(y,d)}return function(y,d,v,j){try{ka=0;var Q=vl(y,d,v,j);return ra=null,Q}catch(X){if(X===oa||X===$n)throw X;var cl=ce(29,X,null,y.mode);return cl.lanes=j,cl.return=y,cl}finally{}}}var Yt=Cs(!0),Us=Cs(!1),ut=!1;function Yi(l){l.updateQueue={baseState:l.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Gi(l,e){l=l.updateQueue,e.updateQueue===l&&(e.updateQueue={baseState:l.baseState,firstBaseUpdate:l.firstBaseUpdate,lastBaseUpdate:l.lastBaseUpdate,shared:l.shared,callbacks:null})}function it(l){return{lane:l,tag:0,payload:null,callback:null,next:null}}function ct(l,e,t){var a=l.updateQueue;if(a===null)return null;if(a=a.shared,(sl&2)!==0){var n=a.pending;return n===null?e.next=e:(e.next=n.next,n.next=e),a.pending=e,e=Vn(l),vs(l,null,t),e}return Ln(l,a,e,t),Vn(l)}function $a(l,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194048)!==0)){var a=e.lanes;a&=l.pendingLanes,t|=a,e.lanes=t,Tf(l,t)}}function Xi(l,e){var t=l.updateQueue,a=l.alternate;if(a!==null&&(a=a.updateQueue,t===a)){var n=null,u=null;if(t=t.firstBaseUpdate,t!==null){do{var i={lane:t.lane,tag:t.tag,payload:t.payload,callback:null,next:null};u===null?n=u=i:u=u.next=i,t=t.next}while(t!==null);u===null?n=u=e:u=u.next=e}else n=u=e;t={baseState:a.baseState,firstBaseUpdate:n,lastBaseUpdate:u,shared:a.shared,callbacks:a.callbacks},l.updateQueue=t;return}l=t.lastBaseUpdate,l===null?t.firstBaseUpdate=e:l.next=e,t.lastBaseUpdate=e}var Qi=!1;function Fa(){if(Qi){var l=sa;if(l!==null)throw l}}function Ia(l,e,t,a){Qi=!1;var n=l.updateQueue;ut=!1;var u=n.firstBaseUpdate,i=n.lastBaseUpdate,s=n.shared.pending;if(s!==null){n.shared.pending=null;var o=s,g=o.next;o.next=null,i===null?u=g:i.next=g,i=o;var S=l.alternate;S!==null&&(S=S.updateQueue,s=S.lastBaseUpdate,s!==i&&(s===null?S.firstBaseUpdate=g:s.next=g,S.lastBaseUpdate=o))}if(u!==null){var z=n.baseState;i=0,S=g=o=null,s=u;do{var p=s.lane&-536870913,b=p!==s.lane;if(b?(el&p)===p:(a&p)===p){p!==0&&p===fa&&(Qi=!0),S!==null&&(S=S.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});l:{var B=l,L=s;p=e;var vl=t;switch(L.tag){case 1:if(B=L.payload,typeof B=="function"){z=B.call(vl,z,p);break l}z=B;break l;case 3:B.flags=B.flags&-65537|128;case 0:if(B=L.payload,p=typeof B=="function"?B.call(vl,z,p):B,p==null)break l;z=M({},z,p);break l;case 2:ut=!0}}p=s.callback,p!==null&&(l.flags|=64,b&&(l.flags|=8192),b=n.callbacks,b===null?n.callbacks=[p]:b.push(p))}else b={lane:p,tag:s.tag,payload:s.payload,callback:s.callback,next:null},S===null?(g=S=b,o=z):S=S.next=b,i|=p;if(s=s.next,s===null){if(s=n.shared.pending,s===null)break;b=s,s=b.next,b.next=null,n.lastBaseUpdate=b,n.shared.pending=null}}while(!0);S===null&&(o=z),n.baseState=o,n.firstBaseUpdate=g,n.lastBaseUpdate=S,u===null&&(n.shared.lanes=0),dt|=i,l.lanes=i,l.memoizedState=z}}function Rs(l,e){if(typeof l!="function")throw Error(r(191,l));l.call(e)}function Hs(l,e){var t=l.callbacks;if(t!==null)for(l.callbacks=null,l=0;lu?u:8;var i=x.T,s={};x.T=s,ic(l,!1,e,t);try{var o=n(),g=x.S;if(g!==null&&g(s,o),o!==null&&typeof o=="object"&&typeof o.then=="function"){var S=$h(o,a);en(l,e,S,de(l))}else en(l,e,a,de(l))}catch(z){en(l,e,{then:function(){},status:"rejected",reason:z},de())}finally{U.p=u,i!==null&&s.types!==null&&(i.types=s.types),x.T=i}}function tm(){}function nc(l,e,t,a){if(l.tag!==5)throw Error(r(476));var n=mo(l).queue;ho(l,n,e,V,t===null?tm:function(){return yo(l),t(a)})}function mo(l){var e=l.memoizedState;if(e!==null)return e;e={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ze,lastRenderedState:V},next:null};var t={};return e.next={memoizedState:t,baseState:t,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ze,lastRenderedState:t},next:null},l.memoizedState=e,l=l.alternate,l!==null&&(l.memoizedState=e),e}function yo(l){var e=mo(l);e.next===null&&(e=l.alternate.memoizedState),en(l,e.next.queue,{},de())}function uc(){return Ql(bn)}function vo(){return Nl().memoizedState}function go(){return Nl().memoizedState}function am(l){for(var e=l.return;e!==null;){switch(e.tag){case 24:case 3:var t=de();l=it(t);var a=ct(e,l,t);a!==null&&(te(a,e,t),$a(a,e,t)),e={cache:Ri()},l.payload=e;return}e=e.return}}function nm(l,e,t){var a=de();t={lane:a,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null},su(l)?bo(e,t):(t=zi(l,e,t,a),t!==null&&(te(t,l,a),So(t,e,a)))}function po(l,e,t){var a=de();en(l,e,t,a)}function en(l,e,t,a){var n={lane:a,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null};if(su(l))bo(e,n);else{var u=l.alternate;if(l.lanes===0&&(u===null||u.lanes===0)&&(u=e.lastRenderedReducer,u!==null))try{var i=e.lastRenderedState,s=u(i,t);if(n.hasEagerState=!0,n.eagerState=s,ie(s,i))return Ln(l,e,n,0),pl===null&&Zn(),!1}catch{}finally{}if(t=zi(l,e,n,a),t!==null)return te(t,l,a),So(t,e,a),!0}return!1}function ic(l,e,t,a){if(a={lane:2,revertLane:Yc(),gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},su(l)){if(e)throw Error(r(479))}else e=zi(l,t,a,2),e!==null&&te(e,l,2)}function su(l){var e=l.alternate;return l===$||e!==null&&e===$}function bo(l,e){ha=tu=!0;var t=l.pending;t===null?e.next=e:(e.next=t.next,t.next=e),l.pending=e}function So(l,e,t){if((t&4194048)!==0){var a=e.lanes;a&=l.pendingLanes,t|=a,e.lanes=t,Tf(l,t)}}var tn={readContext:Ql,use:uu,useCallback:Al,useContext:Al,useEffect:Al,useImperativeHandle:Al,useLayoutEffect:Al,useInsertionEffect:Al,useMemo:Al,useReducer:Al,useRef:Al,useState:Al,useDebugValue:Al,useDeferredValue:Al,useTransition:Al,useSyncExternalStore:Al,useId:Al,useHostTransitionStatus:Al,useFormState:Al,useActionState:Al,useOptimistic:Al,useMemoCache:Al,useCacheRefresh:Al};tn.useEffectEvent=Al;var xo={readContext:Ql,use:uu,useCallback:function(l,e){return Jl().memoizedState=[l,e===void 0?null:e],l},useContext:Ql,useEffect:ao,useImperativeHandle:function(l,e,t){t=t!=null?t.concat([l]):null,cu(4194308,4,co.bind(null,e,l),t)},useLayoutEffect:function(l,e){return cu(4194308,4,l,e)},useInsertionEffect:function(l,e){cu(4,2,l,e)},useMemo:function(l,e){var t=Jl();e=e===void 0?null:e;var a=l();if(Gt){Ie(!0);try{l()}finally{Ie(!1)}}return t.memoizedState=[a,e],a},useReducer:function(l,e,t){var a=Jl();if(t!==void 0){var n=t(e);if(Gt){Ie(!0);try{t(e)}finally{Ie(!1)}}}else n=e;return a.memoizedState=a.baseState=n,l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:l,lastRenderedState:n},a.queue=l,l=l.dispatch=nm.bind(null,$,l),[a.memoizedState,l]},useRef:function(l){var e=Jl();return l={current:l},e.memoizedState=l},useState:function(l){l=Pi(l);var e=l.queue,t=po.bind(null,$,e);return e.dispatch=t,[l.memoizedState,t]},useDebugValue:tc,useDeferredValue:function(l,e){var t=Jl();return ac(t,l,e)},useTransition:function(){var l=Pi(!1);return l=ho.bind(null,$,l.queue,!0,!1),Jl().memoizedState=l,[!1,l]},useSyncExternalStore:function(l,e,t){var a=$,n=Jl();if(nl){if(t===void 0)throw Error(r(407));t=t()}else{if(t=e(),pl===null)throw Error(r(349));(el&127)!==0||Qs(a,e,t)}n.memoizedState=t;var u={value:t,getSnapshot:e};return n.queue=u,ao(Ls.bind(null,a,u,l),[l]),a.flags|=2048,ya(9,{destroy:void 0},Zs.bind(null,a,u,t,e),null),t},useId:function(){var l=Jl(),e=pl.identifierPrefix;if(nl){var t=De,a=Ne;t=(a&~(1<<32-ue(a)-1)).toString(32)+t,e="_"+e+"R_"+t,t=au++,0<\/script>",u=u.removeChild(u.firstChild);break;case"select":u=typeof a.is=="string"?i.createElement("select",{is:a.is}):i.createElement("select"),a.multiple?u.multiple=!0:a.size&&(u.size=a.size);break;default:u=typeof a.is=="string"?i.createElement(n,{is:a.is}):i.createElement(n)}}u[Gl]=e,u[$l]=a;l:for(i=e.child;i!==null;){if(i.tag===5||i.tag===6)u.appendChild(i.stateNode);else if(i.tag!==4&&i.tag!==27&&i.child!==null){i.child.return=i,i=i.child;continue}if(i===e)break l;for(;i.sibling===null;){if(i.return===null||i.return===e)break l;i=i.return}i.sibling.return=i.return,i=i.sibling}e.stateNode=u;l:switch(Ll(u,n,a),n){case"button":case"input":case"select":case"textarea":a=!!a.autoFocus;break l;case"img":a=!0;break l;default:a=!1}a&&Ve(e)}}return Sl(e),Sc(e,e.type,l===null?null:l.memoizedProps,e.pendingProps,t),null;case 6:if(l&&e.stateNode!=null)l.memoizedProps!==a&&Ve(e);else{if(typeof a!="string"&&e.stateNode===null)throw Error(r(166));if(l=I.current,ia(e)){if(l=e.stateNode,t=e.memoizedProps,a=null,n=Xl,n!==null)switch(n.tag){case 27:case 5:a=n.memoizedProps}l[Gl]=e,l=!!(l.nodeValue===t||a!==null&&a.suppressHydrationWarning===!0||Xr(l.nodeValue,t)),l||at(e,!0)}else l=Nu(l).createTextNode(a),l[Gl]=e,e.stateNode=l}return Sl(e),null;case 31:if(t=e.memoizedState,l===null||l.memoizedState!==null){if(a=ia(e),t!==null){if(l===null){if(!a)throw Error(r(318));if(l=e.memoizedState,l=l!==null?l.dehydrated:null,!l)throw Error(r(557));l[Gl]=e}else Ct(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Sl(e),l=!1}else t=Di(),l!==null&&l.memoizedState!==null&&(l.memoizedState.hydrationErrors=t),l=!0;if(!l)return e.flags&256?(se(e),e):(se(e),null);if((e.flags&128)!==0)throw Error(r(558))}return Sl(e),null;case 13:if(a=e.memoizedState,l===null||l.memoizedState!==null&&l.memoizedState.dehydrated!==null){if(n=ia(e),a!==null&&a.dehydrated!==null){if(l===null){if(!n)throw Error(r(318));if(n=e.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(r(317));n[Gl]=e}else Ct(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Sl(e),n=!1}else n=Di(),l!==null&&l.memoizedState!==null&&(l.memoizedState.hydrationErrors=n),n=!0;if(!n)return e.flags&256?(se(e),e):(se(e),null)}return se(e),(e.flags&128)!==0?(e.lanes=t,e):(t=a!==null,l=l!==null&&l.memoizedState!==null,t&&(a=e.child,n=null,a.alternate!==null&&a.alternate.memoizedState!==null&&a.alternate.memoizedState.cachePool!==null&&(n=a.alternate.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==n&&(a.flags|=2048)),t!==l&&t&&(e.child.flags|=8192),mu(e,e.updateQueue),Sl(e),null);case 4:return _l(),l===null&&Zc(e.stateNode.containerInfo),Sl(e),null;case 10:return Xe(e.type),Sl(e),null;case 19:if(A(Ol),a=e.memoizedState,a===null)return Sl(e),null;if(n=(e.flags&128)!==0,u=a.rendering,u===null)if(n)nn(a,!1);else{if(El!==0||l!==null&&(l.flags&128)!==0)for(l=e.child;l!==null;){if(u=eu(l),u!==null){for(e.flags|=128,nn(a,!1),l=u.updateQueue,e.updateQueue=l,mu(e,l),e.subtreeFlags=0,l=t,t=e.child;t!==null;)gs(t,l),t=t.sibling;return R(Ol,Ol.current&1|2),nl&&Ye(e,a.treeForkCount),e.child}l=l.sibling}a.tail!==null&&ae()>bu&&(e.flags|=128,n=!0,nn(a,!1),e.lanes=4194304)}else{if(!n)if(l=eu(u),l!==null){if(e.flags|=128,n=!0,l=l.updateQueue,e.updateQueue=l,mu(e,l),nn(a,!0),a.tail===null&&a.tailMode==="hidden"&&!u.alternate&&!nl)return Sl(e),null}else 2*ae()-a.renderingStartTime>bu&&t!==536870912&&(e.flags|=128,n=!0,nn(a,!1),e.lanes=4194304);a.isBackwards?(u.sibling=e.child,e.child=u):(l=a.last,l!==null?l.sibling=u:e.child=u,a.last=u)}return a.tail!==null?(l=a.tail,a.rendering=l,a.tail=l.sibling,a.renderingStartTime=ae(),l.sibling=null,t=Ol.current,R(Ol,n?t&1|2:t&1),nl&&Ye(e,a.treeForkCount),l):(Sl(e),null);case 22:case 23:return se(e),Li(),a=e.memoizedState!==null,l!==null?l.memoizedState!==null!==a&&(e.flags|=8192):a&&(e.flags|=8192),a?(t&536870912)!==0&&(e.flags&128)===0&&(Sl(e),e.subtreeFlags&6&&(e.flags|=8192)):Sl(e),t=e.updateQueue,t!==null&&mu(e,t.retryQueue),t=null,l!==null&&l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(t=l.memoizedState.cachePool.pool),a=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(a=e.memoizedState.cachePool.pool),a!==t&&(e.flags|=2048),l!==null&&A(Ht),null;case 24:return t=null,l!==null&&(t=l.memoizedState.cache),e.memoizedState.cache!==t&&(e.flags|=2048),Xe(Ml),Sl(e),null;case 25:return null;case 30:return null}throw Error(r(156,e.tag))}function sm(l,e){switch(Oi(e),e.tag){case 1:return l=e.flags,l&65536?(e.flags=l&-65537|128,e):null;case 3:return Xe(Ml),_l(),l=e.flags,(l&65536)!==0&&(l&128)===0?(e.flags=l&-65537|128,e):null;case 26:case 27:case 5:return An(e),null;case 31:if(e.memoizedState!==null){if(se(e),e.alternate===null)throw Error(r(340));Ct()}return l=e.flags,l&65536?(e.flags=l&-65537|128,e):null;case 13:if(se(e),l=e.memoizedState,l!==null&&l.dehydrated!==null){if(e.alternate===null)throw Error(r(340));Ct()}return l=e.flags,l&65536?(e.flags=l&-65537|128,e):null;case 19:return A(Ol),null;case 4:return _l(),null;case 10:return Xe(e.type),null;case 22:case 23:return se(e),Li(),l!==null&&A(Ht),l=e.flags,l&65536?(e.flags=l&-65537|128,e):null;case 24:return Xe(Ml),null;case 25:return null;default:return null}}function Ko(l,e){switch(Oi(e),e.tag){case 3:Xe(Ml),_l();break;case 26:case 27:case 5:An(e);break;case 4:_l();break;case 31:e.memoizedState!==null&&se(e);break;case 13:se(e);break;case 19:A(Ol);break;case 10:Xe(e.type);break;case 22:case 23:se(e),Li(),l!==null&&A(Ht);break;case 24:Xe(Ml)}}function un(l,e){try{var t=e.updateQueue,a=t!==null?t.lastEffect:null;if(a!==null){var n=a.next;t=n;do{if((t.tag&l)===l){a=void 0;var u=t.create,i=t.inst;a=u(),i.destroy=a}t=t.next}while(t!==n)}}catch(s){dl(e,e.return,s)}}function ot(l,e,t){try{var a=e.updateQueue,n=a!==null?a.lastEffect:null;if(n!==null){var u=n.next;a=u;do{if((a.tag&l)===l){var i=a.inst,s=i.destroy;if(s!==void 0){i.destroy=void 0,n=e;var o=t,g=s;try{g()}catch(S){dl(n,o,S)}}}a=a.next}while(a!==u)}}catch(S){dl(e,e.return,S)}}function Jo(l){var e=l.updateQueue;if(e!==null){var t=l.stateNode;try{Hs(e,t)}catch(a){dl(l,l.return,a)}}}function wo(l,e,t){t.props=Xt(l.type,l.memoizedProps),t.state=l.memoizedState;try{t.componentWillUnmount()}catch(a){dl(l,e,a)}}function cn(l,e){try{var t=l.ref;if(t!==null){switch(l.tag){case 26:case 27:case 5:var a=l.stateNode;break;case 30:a=l.stateNode;break;default:a=l.stateNode}typeof t=="function"?l.refCleanup=t(a):t.current=a}}catch(n){dl(l,e,n)}}function Me(l,e){var t=l.ref,a=l.refCleanup;if(t!==null)if(typeof a=="function")try{a()}catch(n){dl(l,e,n)}finally{l.refCleanup=null,l=l.alternate,l!=null&&(l.refCleanup=null)}else if(typeof t=="function")try{t(null)}catch(n){dl(l,e,n)}else t.current=null}function ko(l){var e=l.type,t=l.memoizedProps,a=l.stateNode;try{l:switch(e){case"button":case"input":case"select":case"textarea":t.autoFocus&&a.focus();break l;case"img":t.src?a.src=t.src:t.srcSet&&(a.srcset=t.srcSet)}}catch(n){dl(l,l.return,n)}}function xc(l,e,t){try{var a=l.stateNode;Mm(a,l.type,t,e),a[$l]=e}catch(n){dl(l,l.return,n)}}function Wo(l){return l.tag===5||l.tag===3||l.tag===26||l.tag===27&>(l.type)||l.tag===4}function jc(l){l:for(;;){for(;l.sibling===null;){if(l.return===null||Wo(l.return))return null;l=l.return}for(l.sibling.return=l.return,l=l.sibling;l.tag!==5&&l.tag!==6&&l.tag!==18;){if(l.tag===27&>(l.type)||l.flags&2||l.child===null||l.tag===4)continue l;l.child.return=l,l=l.child}if(!(l.flags&2))return l.stateNode}}function zc(l,e,t){var a=l.tag;if(a===5||a===6)l=l.stateNode,e?(t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t).insertBefore(l,e):(e=t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t,e.appendChild(l),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=He));else if(a!==4&&(a===27&>(l.type)&&(t=l.stateNode,e=null),l=l.child,l!==null))for(zc(l,e,t),l=l.sibling;l!==null;)zc(l,e,t),l=l.sibling}function yu(l,e,t){var a=l.tag;if(a===5||a===6)l=l.stateNode,e?t.insertBefore(l,e):t.appendChild(l);else if(a!==4&&(a===27&>(l.type)&&(t=l.stateNode),l=l.child,l!==null))for(yu(l,e,t),l=l.sibling;l!==null;)yu(l,e,t),l=l.sibling}function $o(l){var e=l.stateNode,t=l.memoizedProps;try{for(var a=l.type,n=e.attributes;n.length;)e.removeAttributeNode(n[0]);Ll(e,a,t),e[Gl]=l,e[$l]=t}catch(u){dl(l,l.return,u)}}var Ke=!1,Rl=!1,Tc=!1,Fo=typeof WeakSet=="function"?WeakSet:Set,Yl=null;function om(l,e){if(l=l.containerInfo,Kc=Bu,l=fs(l),gi(l)){if("selectionStart"in l)var t={start:l.selectionStart,end:l.selectionEnd};else l:{t=(t=l.ownerDocument)&&t.defaultView||window;var a=t.getSelection&&t.getSelection();if(a&&a.rangeCount!==0){t=a.anchorNode;var n=a.anchorOffset,u=a.focusNode;a=a.focusOffset;try{t.nodeType,u.nodeType}catch{t=null;break l}var i=0,s=-1,o=-1,g=0,S=0,z=l,p=null;e:for(;;){for(var b;z!==t||n!==0&&z.nodeType!==3||(s=i+n),z!==u||a!==0&&z.nodeType!==3||(o=i+a),z.nodeType===3&&(i+=z.nodeValue.length),(b=z.firstChild)!==null;)p=z,z=b;for(;;){if(z===l)break e;if(p===t&&++g===n&&(s=i),p===u&&++S===a&&(o=i),(b=z.nextSibling)!==null)break;z=p,p=z.parentNode}z=b}t=s===-1||o===-1?null:{start:s,end:o}}else t=null}t=t||{start:0,end:0}}else t=null;for(Jc={focusedElem:l,selectionRange:t},Bu=!1,Yl=e;Yl!==null;)if(e=Yl,l=e.child,(e.subtreeFlags&1028)!==0&&l!==null)l.return=e,Yl=l;else for(;Yl!==null;){switch(e=Yl,u=e.alternate,l=e.flags,e.tag){case 0:if((l&4)!==0&&(l=e.updateQueue,l=l!==null?l.events:null,l!==null))for(t=0;t title"))),Ll(u,a,t),u[Gl]=l,ql(u),a=u;break l;case"link":var i=ad("link","href",n).get(a+(t.href||""));if(i){for(var s=0;svl&&(i=vl,vl=L,L=i);var y=is(s,L),d=is(s,vl);if(y&&d&&(b.rangeCount!==1||b.anchorNode!==y.node||b.anchorOffset!==y.offset||b.focusNode!==d.node||b.focusOffset!==d.offset)){var v=z.createRange();v.setStart(y.node,y.offset),b.removeAllRanges(),L>vl?(b.addRange(v),b.extend(d.node,d.offset)):(v.setEnd(d.node,d.offset),b.addRange(v))}}}}for(z=[],b=s;b=b.parentNode;)b.nodeType===1&&z.push({element:b,left:b.scrollLeft,top:b.scrollTop});for(typeof s.focus=="function"&&s.focus(),s=0;st?32:t,x.T=null,t=Mc,Mc=null;var u=mt,i=$e;if(Bl=0,Sa=mt=null,$e=0,(sl&6)!==0)throw Error(r(331));var s=sl;if(sl|=4,fr(u.current),ur(u,u.current,i,t),sl=s,hn(0,!1),ne&&typeof ne.onPostCommitFiberRoot=="function")try{ne.onPostCommitFiberRoot(Da,u)}catch{}return!0}finally{U.p=n,x.T=a,Er(l,e)}}function Or(l,e,t){e=ve(t,e),e=oc(l.stateNode,e,2),l=ct(l,e,2),l!==null&&(Ca(l,2),Ce(l))}function dl(l,e,t){if(l.tag===3)Or(l,l,t);else for(;e!==null;){if(e.tag===3){Or(e,l,t);break}else if(e.tag===1){var a=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof a.componentDidCatch=="function"&&(ht===null||!ht.has(a))){l=ve(t,l),t=No(2),a=ct(e,t,2),a!==null&&(Do(t,a,e,l),Ca(a,2),Ce(a));break}}e=e.return}}function Hc(l,e,t){var a=l.pingCache;if(a===null){a=l.pingCache=new hm;var n=new Set;a.set(e,n)}else n=a.get(e),n===void 0&&(n=new Set,a.set(e,n));n.has(t)||(_c=!0,n.add(t),l=pm.bind(null,l,e,t),e.then(l,l))}function pm(l,e,t){var a=l.pingCache;a!==null&&a.delete(e),l.pingedLanes|=l.suspendedLanes&t,l.warmLanes&=~t,pl===l&&(el&t)===t&&(El===4||El===3&&(el&62914560)===el&&300>ae()-pu?(sl&2)===0&&xa(l,0):Oc|=t,ba===el&&(ba=0)),Ce(l)}function Nr(l,e){e===0&&(e=jf()),l=Dt(l,e),l!==null&&(Ca(l,e),Ce(l))}function bm(l){var e=l.memoizedState,t=0;e!==null&&(t=e.retryLane),Nr(l,t)}function Sm(l,e){var t=0;switch(l.tag){case 31:case 13:var a=l.stateNode,n=l.memoizedState;n!==null&&(t=n.retryLane);break;case 19:a=l.stateNode;break;case 22:a=l.stateNode._retryCache;break;default:throw Error(r(314))}a!==null&&a.delete(e),Nr(l,t)}function xm(l,e){return ku(l,e)}var Au=null,za=null,Bc=!1,Eu=!1,qc=!1,vt=0;function Ce(l){l!==za&&l.next===null&&(za===null?Au=za=l:za=za.next=l),Eu=!0,Bc||(Bc=!0,zm())}function hn(l,e){if(!qc&&Eu){qc=!0;do for(var t=!1,a=Au;a!==null;){if(l!==0){var n=a.pendingLanes;if(n===0)var u=0;else{var i=a.suspendedLanes,s=a.pingedLanes;u=(1<<31-ue(42|l)+1)-1,u&=n&~(i&~s),u=u&201326741?u&201326741|1:u?u|2:0}u!==0&&(t=!0,Ur(a,u))}else u=el,u=Dn(a,a===pl?u:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),(u&3)===0||Ma(a,u)||(t=!0,Ur(a,u));a=a.next}while(t);qc=!1}}function jm(){Dr()}function Dr(){Eu=Bc=!1;var l=0;vt!==0&&Um()&&(l=vt);for(var e=ae(),t=null,a=Au;a!==null;){var n=a.next,u=Mr(a,e);u===0?(a.next=null,t===null?Au=n:t.next=n,n===null&&(za=t)):(t=a,(l!==0||(u&3)!==0)&&(Eu=!0)),a=n}Bl!==0&&Bl!==5||hn(l),vt!==0&&(vt=0)}function Mr(l,e){for(var t=l.suspendedLanes,a=l.pingedLanes,n=l.expirationTimes,u=l.pendingLanes&-62914561;0s)break;var S=o.transferSize,z=o.initiatorType;S&&Qr(z)&&(o=o.responseEnd,i+=S*(o"u"?null:document;function Pr(l,e,t){var a=Ta;if(a&&typeof e=="string"&&e){var n=me(e);n='link[rel="'+l+'"][href="'+n+'"]',typeof t=="string"&&(n+='[crossorigin="'+t+'"]'),Ir.has(n)||(Ir.add(n),l={rel:l,crossOrigin:t,href:e},a.querySelector(n)===null&&(e=a.createElement("link"),Ll(e,"link",l),ql(e),a.head.appendChild(e)))}}function Zm(l){Fe.D(l),Pr("dns-prefetch",l,null)}function Lm(l,e){Fe.C(l,e),Pr("preconnect",l,e)}function Vm(l,e,t){Fe.L(l,e,t);var a=Ta;if(a&&l&&e){var n='link[rel="preload"][as="'+me(e)+'"]';e==="image"&&t&&t.imageSrcSet?(n+='[imagesrcset="'+me(t.imageSrcSet)+'"]',typeof t.imageSizes=="string"&&(n+='[imagesizes="'+me(t.imageSizes)+'"]')):n+='[href="'+me(l)+'"]';var u=n;switch(e){case"style":u=Aa(l);break;case"script":u=Ea(l)}je.has(u)||(l=M({rel:"preload",href:e==="image"&&t&&t.imageSrcSet?void 0:l,as:e},t),je.set(u,l),a.querySelector(n)!==null||e==="style"&&a.querySelector(gn(u))||e==="script"&&a.querySelector(pn(u))||(e=a.createElement("link"),Ll(e,"link",l),ql(e),a.head.appendChild(e)))}}function Km(l,e){Fe.m(l,e);var t=Ta;if(t&&l){var a=e&&typeof e.as=="string"?e.as:"script",n='link[rel="modulepreload"][as="'+me(a)+'"][href="'+me(l)+'"]',u=n;switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":u=Ea(l)}if(!je.has(u)&&(l=M({rel:"modulepreload",href:l},e),je.set(u,l),t.querySelector(n)===null)){switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(t.querySelector(pn(u)))return}a=t.createElement("link"),Ll(a,"link",l),ql(a),t.head.appendChild(a)}}}function Jm(l,e,t){Fe.S(l,e,t);var a=Ta;if(a&&l){var n=wt(a).hoistableStyles,u=Aa(l);e=e||"default";var i=n.get(u);if(!i){var s={loading:0,preload:null};if(i=a.querySelector(gn(u)))s.loading=5;else{l=M({rel:"stylesheet",href:l,"data-precedence":e},t),(t=je.get(u))&&Pc(l,t);var o=i=a.createElement("link");ql(o),Ll(o,"link",l),o._p=new Promise(function(g,S){o.onload=g,o.onerror=S}),o.addEventListener("load",function(){s.loading|=1}),o.addEventListener("error",function(){s.loading|=2}),s.loading|=4,Mu(i,e,a)}i={type:"stylesheet",instance:i,count:1,state:s},n.set(u,i)}}}function wm(l,e){Fe.X(l,e);var t=Ta;if(t&&l){var a=wt(t).hoistableScripts,n=Ea(l),u=a.get(n);u||(u=t.querySelector(pn(n)),u||(l=M({src:l,async:!0},e),(e=je.get(n))&&lf(l,e),u=t.createElement("script"),ql(u),Ll(u,"link",l),t.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},a.set(n,u))}}function km(l,e){Fe.M(l,e);var t=Ta;if(t&&l){var a=wt(t).hoistableScripts,n=Ea(l),u=a.get(n);u||(u=t.querySelector(pn(n)),u||(l=M({src:l,async:!0,type:"module"},e),(e=je.get(n))&&lf(l,e),u=t.createElement("script"),ql(u),Ll(u,"link",l),t.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},a.set(n,u))}}function ld(l,e,t,a){var n=(n=I.current)?Du(n):null;if(!n)throw Error(r(446));switch(l){case"meta":case"title":return null;case"style":return typeof t.precedence=="string"&&typeof t.href=="string"?(e=Aa(t.href),t=wt(n).hoistableStyles,a=t.get(e),a||(a={type:"style",instance:null,count:0,state:null},t.set(e,a)),a):{type:"void",instance:null,count:0,state:null};case"link":if(t.rel==="stylesheet"&&typeof t.href=="string"&&typeof t.precedence=="string"){l=Aa(t.href);var u=wt(n).hoistableStyles,i=u.get(l);if(i||(n=n.ownerDocument||n,i={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},u.set(l,i),(u=n.querySelector(gn(l)))&&!u._p&&(i.instance=u,i.state.loading=5),je.has(l)||(t={rel:"preload",as:"style",href:t.href,crossOrigin:t.crossOrigin,integrity:t.integrity,media:t.media,hrefLang:t.hrefLang,referrerPolicy:t.referrerPolicy},je.set(l,t),u||Wm(n,l,t,i.state))),e&&a===null)throw Error(r(528,""));return i}if(e&&a!==null)throw Error(r(529,""));return null;case"script":return e=t.async,t=t.src,typeof t=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=Ea(t),t=wt(n).hoistableScripts,a=t.get(e),a||(a={type:"script",instance:null,count:0,state:null},t.set(e,a)),a):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,l))}}function Aa(l){return'href="'+me(l)+'"'}function gn(l){return'link[rel="stylesheet"]['+l+"]"}function ed(l){return M({},l,{"data-precedence":l.precedence,precedence:null})}function Wm(l,e,t,a){l.querySelector('link[rel="preload"][as="style"]['+e+"]")?a.loading=1:(e=l.createElement("link"),a.preload=e,e.addEventListener("load",function(){return a.loading|=1}),e.addEventListener("error",function(){return a.loading|=2}),Ll(e,"link",t),ql(e),l.head.appendChild(e))}function Ea(l){return'[src="'+me(l)+'"]'}function pn(l){return"script[async]"+l}function td(l,e,t){if(e.count++,e.instance===null)switch(e.type){case"style":var a=l.querySelector('style[data-href~="'+me(t.href)+'"]');if(a)return e.instance=a,ql(a),a;var n=M({},t,{"data-href":t.href,"data-precedence":t.precedence,href:null,precedence:null});return a=(l.ownerDocument||l).createElement("style"),ql(a),Ll(a,"style",n),Mu(a,t.precedence,l),e.instance=a;case"stylesheet":n=Aa(t.href);var u=l.querySelector(gn(n));if(u)return e.state.loading|=4,e.instance=u,ql(u),u;a=ed(t),(n=je.get(n))&&Pc(a,n),u=(l.ownerDocument||l).createElement("link"),ql(u);var i=u;return i._p=new Promise(function(s,o){i.onload=s,i.onerror=o}),Ll(u,"link",a),e.state.loading|=4,Mu(u,t.precedence,l),e.instance=u;case"script":return u=Ea(t.src),(n=l.querySelector(pn(u)))?(e.instance=n,ql(n),n):(a=t,(n=je.get(u))&&(a=M({},t),lf(a,n)),l=l.ownerDocument||l,n=l.createElement("script"),ql(n),Ll(n,"link",a),l.head.appendChild(n),e.instance=n);case"void":return null;default:throw Error(r(443,e.type))}else e.type==="stylesheet"&&(e.state.loading&4)===0&&(a=e.instance,e.state.loading|=4,Mu(a,t.precedence,l));return e.instance}function Mu(l,e,t){for(var a=t.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),n=a.length?a[a.length-1]:null,u=n,i=0;i title"):null)}function $m(l,e,t){if(t===1||e.itemProp!=null)return!1;switch(l){case"meta":case"title":return!0;case"style":if(typeof e.precedence!="string"||typeof e.href!="string"||e.href==="")break;return!0;case"link":if(typeof e.rel!="string"||typeof e.href!="string"||e.href===""||e.onLoad||e.onError)break;switch(e.rel){case"stylesheet":return l=e.disabled,typeof e.precedence=="string"&&l==null;default:return!0}case"script":if(e.async&&typeof e.async!="function"&&typeof e.async!="symbol"&&!e.onLoad&&!e.onError&&e.src&&typeof e.src=="string")return!0}return!1}function ud(l){return!(l.type==="stylesheet"&&(l.state.loading&3)===0)}function Fm(l,e,t,a){if(t.type==="stylesheet"&&(typeof a.media!="string"||matchMedia(a.media).matches!==!1)&&(t.state.loading&4)===0){if(t.instance===null){var n=Aa(a.href),u=e.querySelector(gn(n));if(u){e=u._p,e!==null&&typeof e=="object"&&typeof e.then=="function"&&(l.count++,l=Uu.bind(l),e.then(l,l)),t.state.loading|=4,t.instance=u,ql(u);return}u=e.ownerDocument||e,a=ed(a),(n=je.get(n))&&Pc(a,n),u=u.createElement("link"),ql(u);var i=u;i._p=new Promise(function(s,o){i.onload=s,i.onerror=o}),Ll(u,"link",a),t.instance=u}l.stylesheets===null&&(l.stylesheets=new Map),l.stylesheets.set(t,e),(e=t.state.preload)&&(t.state.loading&3)===0&&(l.count++,t=Uu.bind(l),e.addEventListener("load",t),e.addEventListener("error",t))}}var ef=0;function Im(l,e){return l.stylesheets&&l.count===0&&Hu(l,l.stylesheets),0ef?50:800)+e);return l.unsuspend=t,function(){l.unsuspend=null,clearTimeout(a),clearTimeout(n)}}:null}function Uu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Hu(this,this.stylesheets);else if(this.unsuspend){var l=this.unsuspend;this.unsuspend=null,l()}}}var Ru=null;function Hu(l,e){l.stylesheets=null,l.unsuspend!==null&&(l.count++,Ru=new Map,e.forEach(Pm,l),Ru=null,Uu.call(l))}function Pm(l,e){if(!(e.state.loading&4)){var t=Ru.get(l);if(t)var a=t.get(null);else{t=new Map,Ru.set(l,t);for(var n=l.querySelectorAll("link[data-precedence],style[data-precedence]"),u=0;u"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(f)}catch(E){console.error(E)}}return f(),rf.exports=yy(),rf.exports}var gy=vy();const py=Cd(gy),Rd="";async function Dl(f,E){const T=await fetch(`${Rd}${f}`,{...E,credentials:"same-origin",headers:{"Content-Type":"application/json",...E==null?void 0:E.headers}});if(T.status===401)throw window.location.hash="#login",new Error("Unauthorized");if(!T.ok){const r=await T.json().catch(()=>({}));throw new Error(r.message||r.error||`HTTP ${T.status}`)}return T.json()}async function by(f){const E=await fetch(`${Rd}${f}`,{credentials:"same-origin"});if(E.status===401)throw window.location.hash="#login",new Error("Unauthorized");if(!E.ok)throw new Error(`HTTP ${E.status}`);return E.text()}const xl={login:f=>Dl("/admin/login",{method:"POST",body:JSON.stringify({token:f})}),signOutEverywhere:()=>Dl("/admin/api/sign-out-everywhere",{method:"POST"}),stats:()=>Dl("/admin/api/stats"),health:()=>Dl("/admin/api/health-indicators"),agents:()=>Dl("/admin/api/agents"),agentsSpend:()=>Dl("/admin/api/agents/spend"),sources:()=>Dl("/admin/api/sources"),grantCatalog:()=>Dl("/admin/api/grant-catalog"),clientGrant:f=>Dl(`/admin/api/grants/${encodeURIComponent(f)}`),registerClient:f=>Dl("/admin/api/register-client",{method:"POST",body:JSON.stringify(f)}),recoverClient:f=>Dl("/admin/api/recover-client",{method:"POST",body:JSON.stringify({clientId:f})}),updateClientGrant:(f,E)=>Dl("/admin/api/rescope-client",{method:"POST",body:JSON.stringify({...E,clientId:f})}),requests:(f=1,E="")=>Dl(`/admin/api/requests?page=${f}${E}`),apiKeys:()=>Dl("/admin/api/api-keys"),createApiKey(f){return Dl("/admin/api/api-keys",{method:"POST",body:JSON.stringify({name:f})})},revokeApiKey(f){return Dl("/admin/api/api-keys/revoke",{method:"POST",body:JSON.stringify({name:f})})},updateClientTtl:(f,E)=>Dl("/admin/api/update-client-ttl",{method:"POST",body:JSON.stringify({clientId:f,tokenTtl:E})}),rescopeClient:(f,E,T)=>Dl("/admin/api/rescope-client",{method:"POST",body:JSON.stringify({clientId:f,sourceId:E,federatedRead:T})}),revokeClient:f=>Dl("/admin/api/revoke-client",{method:"POST",body:JSON.stringify({clientId:f})}),calibrationProfile:f=>Dl(`/admin/api/calibration/profile${f?`?holder=${encodeURIComponent(f)}`:""}`),calibrationChart:(f,E)=>by(`/admin/api/calibration/charts/${encodeURIComponent(f)}${E?`?holder=${encodeURIComponent(E)}`:""}`),jobsWatch:()=>Dl("/admin/api/jobs/watch")};function Sy({onLogin:f}){const[E,T]=Y.useState(""),[r,D]=Y.useState(""),[_,H]=Y.useState(!1),G=async O=>{O.preventDefault(),D(""),H(!0);try{await xl.login(E),T(""),f()}catch{D("Invalid token.")}finally{H(!1)}};return c.jsx("div",{className:"login-page",children:c.jsxs("div",{className:"login-box",children:[c.jsx("div",{className:"login-logo",children:"GBrain"}),c.jsxs("div",{style:{background:"rgba(136, 170, 255, 0.08)",border:"1px solid rgba(136, 170, 255, 0.2)",borderRadius:8,padding:"14px 16px",marginBottom:20,fontSize:13,lineHeight:1.5,color:"var(--text-secondary)"},children:[c.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:6},children:"🔒 This is a protected dashboard"}),"Ask your AI agent for the admin login link:",c.jsx("div",{style:{background:"rgba(0,0,0,0.3)",borderRadius:6,padding:"8px 12px",marginTop:8,fontFamily:"var(--font-mono)",fontSize:12,color:"#88aaff",wordBreak:"break-all"},children:'"Give me the GBrain admin login link"'}),c.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-muted)"},children:"Each link is single-use. Your agent generates a fresh one each time."})]}),c.jsxs("details",{style:{marginBottom:16},children:[c.jsx("summary",{style:{cursor:"pointer",fontSize:13,color:"var(--text-muted)"},children:"Or paste bootstrap token manually"}),c.jsxs("form",{onSubmit:G,style:{marginTop:12},children:[c.jsx("div",{style:{marginBottom:12},children:c.jsx("input",{type:"password",placeholder:"Admin Token",value:E,onChange:O=>T(O.target.value)})}),c.jsx("button",{className:"btn btn-primary",style:{width:"100%"},disabled:_,children:_?"Authenticating...":"Submit"}),r&&c.jsx("div",{className:"login-error",children:r})]})]})]})})}function xy(){const[f,E]=Y.useState({connected_agents:0,requests_today:0,active_tokens:0}),[T,r]=Y.useState({expiring_soon:0,error_rate:"0%"}),[D,_]=Y.useState([]),[H,G]=Y.useState("connecting"),O=Y.useRef(null);Y.useEffect(()=>{xl.stats().then(E).catch(()=>{}),xl.health().then(r).catch(()=>{});const C=new EventSource("/admin/events",{withCredentials:!0});O.current=C,C.onopen=()=>G("connected"),C.onmessage=N=>{try{const w=JSON.parse(N.data);_(J=>[w,...J].slice(0,50))}catch{}},C.onerror=()=>{G("disconnected"),setTimeout(()=>{G("connecting"),C.close()},3e3)};const M=setInterval(()=>{xl.stats().then(E).catch(()=>{}),xl.health().then(r).catch(()=>{})},3e4);return()=>{C.close(),clearInterval(M)}},[]);const h=C=>{const M=Date.now()-new Date(C).getTime();return M<6e4?`${Math.floor(M/1e3)}s ago`:M<36e5?`${Math.floor(M/6e4)} min ago`:`${Math.floor(M/36e5)}h ago`};return c.jsxs(c.Fragment,{children:[c.jsx("h1",{className:"page-title",children:"Dashboard"}),c.jsxs("div",{style:{display:"flex",gap:24},children:[c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{className:"metrics",children:[c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:f.connected_agents}),c.jsx("div",{className:"metric-label",children:"Connected Agents"})]}),c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:f.requests_today}),c.jsx("div",{className:"metric-label",children:"Requests Today"})]}),c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:f.active_tokens}),c.jsx("div",{className:"metric-label",children:"Active Tokens"})]})]}),c.jsxs("h2",{className:"section-title",children:["Live Activity",c.jsx("span",{style:{marginLeft:8,fontSize:10,color:H==="connected"?"var(--success)":H==="connecting"?"var(--warning)":"var(--error)"},children:H==="connected"?"● connected":H==="connecting"?"● connecting...":"● disconnected"})]}),c.jsx("div",{className:"feed",children:D.length===0?c.jsx("div",{className:"feed-empty",children:H==="connected"?"No requests yet. Agents will appear when they connect.":"Connecting..."}):c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Agent"}),c.jsx("th",{children:"Operation"}),c.jsx("th",{children:"Scopes"}),c.jsx("th",{children:"Latency"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Time"})]})}),c.jsx("tbody",{children:D.map((C,M)=>c.jsxs("tr",{children:[c.jsx("td",{className:"mono",children:C.agent}),c.jsx("td",{className:"mono",children:C.operation}),c.jsx("td",{children:C.scopes.split(",").map(N=>c.jsx("span",{className:`badge badge-${N.trim()}`,style:{marginRight:4},children:N.trim()},N))}),c.jsxs("td",{className:"mono",children:[C.latency_ms," ms"]}),c.jsx("td",{children:c.jsx("span",{className:`badge badge-${C.status}`,children:C.status})}),c.jsx("td",{style:{color:"var(--text-secondary)"},children:h(C.timestamp)})]},M))})]})})]}),c.jsxs("div",{style:{width:220},children:[c.jsx("h2",{className:"section-title",children:"Token Health"}),c.jsxs("div",{className:"health-panel",children:[c.jsxs("div",{className:"health-row",children:[c.jsx("span",{style:{color:"var(--warning)"},children:"Expiring Soon"}),c.jsx("span",{className:"mono",children:T.expiring_soon})]}),c.jsxs("div",{className:"health-row",children:[c.jsx("span",{style:{color:"var(--error)"},children:"Error Rate"}),c.jsx("span",{className:"mono",children:T.error_rate})]})]})]})]})]})}const Oa=f=>f.split(/[\s,]+/).filter(Boolean);function yf(f){var E,T,r;return{profile:(f==null?void 0:f.profile)??"memory-writer",applyProfile:!f,source:(f==null?void 0:f.sourceId)??"default",reads:(f==null?void 0:f.federatedRead)??["default"],scopes:(f==null?void 0:f.scopes.join(" "))??"",directPrefixes:((E=f==null?void 0:f.boundSlugPrefixes)==null?void 0:E.join(` +`))??"",tools:(f==null?void 0:f.boundTools)??[],namespace:(f==null?void 0:f.delegatedNamespace)??"job",delegatedPrefixes:((T=f==null?void 0:f.delegatedSlugPrefixes)==null?void 0:T.join(` +`))??"",concurrency:String((f==null?void 0:f.boundMaxConcurrent)??1),budget:(f==null?void 0:f.budgetUsdPerDay)??"unlimited",ttl:f?String(f.tokenTtlSeconds??0):"3600",surface:(f==null?void 0:f.surface)??"starter",operationSnapshot:((r=f==null?void 0:f.allowedOperations)==null?void 0:r.join(` +`))??"",editOperations:!1}}function Hd(f){const E=f.scopes?Oa(f.scopes).includes("agent"):["full","delegating-agent"].includes(f.profile);return{...f.applyProfile?{profile:f.profile}:{},sourceId:f.source,federatedRead:f.reads,boundSlugPrefixes:f.directPrefixes.trim()?Oa(f.directPrefixes):null,...f.scopes.trim()?{scopes:Oa(f.scopes)}:{},...f.editOperations?{allowedOperations:Oa(f.operationSnapshot)}:{},...E?{boundTools:f.tools,boundSourceId:f.source,delegatedNamespace:f.namespace,delegatedSlugPrefixes:f.namespace==="job"?null:Oa(f.delegatedPrefixes)}:{},boundMaxConcurrent:Number(f.concurrency),budgetUsdPerDay:f.budget==="unlimited"?null:f.budget,tokenTtl:f.ttl==="0"?null:Number(f.ttl),surface:f.surface==="default"?null:f.surface}}function Bd(f){return{...f.profile?{profile:f.profile}:{},scopes:f.scopes,sourceId:f.sourceId,federatedRead:f.federatedRead,boundSlugPrefixes:f.boundSlugPrefixes,allowedOperations:f.allowedOperations,boundTools:f.boundTools,boundSourceId:f.boundSourceId,boundBrainId:f.boundBrainId,delegatedNamespace:f.delegatedNamespace,delegatedSlugPrefixes:f.delegatedSlugPrefixes,boundMaxConcurrent:f.boundMaxConcurrent,budgetUsdPerDay:f.budgetUsdPerDay,tokenTtlSeconds:f.tokenTtlSeconds,surface:f.surface}}function qd({draft:f,setDraft:E,sources:T,catalog:r,existing:D=!1}){const _=(h,C)=>E({...f,[h]:C}),H=new Set(T.map(h=>h.id)),G=f.scopes?Oa(f.scopes).includes("agent"):["full","delegating-agent"].includes(f.profile),O={marginBottom:14};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-profile",children:"Permission profile"}),c.jsx("select",{id:"grant-profile",value:f.profile,onChange:h=>E({...f,profile:h.target.value,applyProfile:!0,scopes:"",editOperations:!1,surface:["operator","full"].includes(h.target.value)?"full":"starter"}),children:r.profiles.map(h=>c.jsx("option",{children:h},h))}),c.jsx("p",{className:"grant-help",children:"Memory writer lets this agent recall, save, correct, and withdraw memory. Delegating profiles also allow selected server tools to run jobs."}),D&&c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:f.applyProfile,onChange:h=>_("applyProfile",h.target.checked)}),"Apply this profile's current operation snapshot"]})]}),c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-source",children:"Primary / write source"}),c.jsxs("select",{id:"grant-source",value:f.source,onChange:h=>_("source",h.target.value),children:[!H.has(f.source)&&c.jsxs("option",{value:f.source,children:[f.source," · unavailable"]}),T.map(h=>c.jsxs("option",{value:h.id,children:[h.name," (",h.id,")"]},h.id))]})]}),c.jsxs("fieldset",{style:{border:0,padding:0,margin:"0 0 14px"},children:[c.jsx("legend",{children:"Readable sources"}),[...T,...f.reads.filter(h=>!H.has(h)).map(h=>({id:h,name:`${h} · unavailable`}))].map(h=>c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:f.reads.includes(h.id),onChange:C=>_("reads",C.target.checked?[...f.reads,h.id]:f.reads.filter(M=>M!==h.id))}),h.name]},h.id))]}),c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-direct-prefixes",children:"Direct write prefixes (one per line)"}),c.jsx("textarea",{id:"grant-direct-prefixes",rows:2,value:f.directPrefixes,onChange:h=>_("directPrefixes",h.target.value),placeholder:"work-example/"}),c.jsx("p",{className:"grant-help",children:"Blank grants the whole primary source. Coding agent requires an explicit prefix."})]}),G&&c.jsxs("fieldset",{style:{border:"1px solid var(--border)",padding:12,marginBottom:14},children:[c.jsx("legend",{children:"Delegated jobs"}),c.jsx("p",{className:"grant-help",children:"Choose every tool explicitly. Jobs stay in the primary source; existing jobs retain their original limits."}),c.jsx("div",{className:"checkbox-group",style:{maxHeight:180,overflowY:"auto"},children:[...new Set([...r.delegatedTools,...f.tools])].map(h=>c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:f.tools.includes(h),onChange:C=>_("tools",C.target.checked?[...f.tools,h]:f.tools.filter(M=>M!==h))}),h,r.delegatedTools.includes(h)?"":" · unavailable"]},h))}),c.jsx("label",{htmlFor:"grant-namespace",children:"Delegated write namespace"}),c.jsxs("select",{id:"grant-namespace",value:f.namespace,onChange:h=>_("namespace",h.target.value),children:[c.jsx("option",{value:"job",children:"Each job's own wiki/agents/ directory"}),c.jsx("option",{value:"prefixes",children:"Explicit prefixes"})]}),f.namespace==="prefixes"&&c.jsx("textarea",{"aria-label":"Delegated prefixes",rows:2,value:f.delegatedPrefixes,onChange:h=>_("delegatedPrefixes",h.target.value),placeholder:"work-example/"})]}),c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,...O},children:[c.jsxs("div",{children:[c.jsx("label",{htmlFor:"grant-concurrency",children:"Concurrent jobs"}),c.jsx("input",{id:"grant-concurrency",type:"number",min:1,step:1,value:f.concurrency,onChange:h=>_("concurrency",h.target.value)})]}),c.jsxs("div",{children:[c.jsx("label",{htmlFor:"grant-budget",children:"Daily delegated spend (USD)"}),c.jsx("input",{id:"grant-budget",value:f.budget,onChange:h=>_("budget",h.target.value),placeholder:"unlimited"}),c.jsx("p",{className:"grant-help",children:"Use unlimited for no spending cap, or an amount such as 2.50."})]})]}),c.jsxs("div",{style:O,children:[c.jsx("label",{htmlFor:"grant-ttl",children:"Future access token lifetime (seconds)"}),c.jsx("input",{id:"grant-ttl",type:"number",min:0,max:7776e3,step:1,value:f.ttl,onChange:h=>_("ttl",h.target.value)}),c.jsx("p",{className:"grant-help",children:"Renewable: 3600 (1 hour). Static bearer: 2592000 (30 days). 0 uses the server default. Existing tokens keep their expiry."})]}),c.jsxs("details",{style:O,children:[c.jsx("summary",{children:"Advanced permissions"}),c.jsx("label",{htmlFor:"grant-scopes",children:"Scope override"}),c.jsx("input",{id:"grant-scopes",value:f.scopes,onChange:h=>_("scopes",h.target.value),placeholder:"Use profile scopes"}),c.jsx("p",{className:"grant-help",children:"read, write, admin, and agent are distinct grants. Admin does not authorize delegation."}),c.jsx("label",{htmlFor:"grant-surface",children:"Visible tool catalog"}),c.jsx("select",{id:"grant-surface",value:f.surface,onChange:h=>_("surface",h.target.value),children:["verbs","starter","full","default"].map(h=>c.jsx("option",{children:h},h))}),c.jsx("p",{className:"grant-help",children:"Full shows all eligible tools; it does not grant additional authority."}),c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:f.editOperations,onChange:h=>_("editOperations",h.target.checked)}),"Replace operation authority snapshot"]}),f.editOperations&&c.jsxs(c.Fragment,{children:[c.jsx("textarea",{"aria-label":"Allowed operations",rows:5,value:f.operationSnapshot,onChange:h=>_("operationSnapshot",h.target.value)}),c.jsx("p",{className:"grant-help",children:"One operation name per line. An empty list denies every operation, including delegated tools."})]})]})]})}const jy=[["Profile","profile"],["Scopes","scopes"],["Write source","sourceId"],["Readable sources","federatedRead"],["Direct prefixes","boundSlugPrefixes"],["Visible catalog","surface"],["Operation authority","allowedOperations"],["Delegated tools","boundTools"],["Delegated source","boundSourceId"],["Delegated brain","boundBrainId"],["Delegated namespace","delegatedNamespace"],["Delegated prefixes","delegatedSlugPrefixes"],["Concurrent jobs","boundMaxConcurrent"],["Daily USD cap","budgetUsdPerDay"],["Future token TTL","tokenTtlSeconds"]];function zy(f,E){return f===null?E==="budgetUsdPerDay"?"Unlimited":E==="allowedOperations"?"Legacy scope-based catalog":"Unset":Array.isArray(f)?f.join(", ")||"(none)":String(f)}function Nd({grant:f,field:E}){const T=f[E];return E==="allowedOperations"&&Array.isArray(T)&&T.length>8?c.jsxs("details",{children:[c.jsxs("summary",{children:[T.length," operations · inspect list"]}),c.jsx("div",{style:{maxHeight:160,overflowY:"auto",marginTop:8},children:T.join(", ")})]}):c.jsx(c.Fragment,{children:zy(T,E)})}function Yd({preview:f}){return c.jsxs("div",{"aria-live":"polite",style:{margin:"16px 0"},children:[c.jsx("h3",{children:"Review permissions"}),c.jsx("div",{style:{overflowX:"auto"},children:c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Permission"}),f.before&&c.jsx("th",{children:"Current"}),c.jsx("th",{children:"Proposed"})]})}),c.jsx("tbody",{children:jy.filter(([,E])=>!f.before||JSON.stringify(f.before[E])!==JSON.stringify(f.after[E])).map(([E,T])=>c.jsxs("tr",{children:[c.jsx("th",{children:E}),f.before&&c.jsx("td",{style:{overflowWrap:"anywhere",maxWidth:200},children:c.jsx(Nd,{grant:f.before,field:T})}),c.jsx("td",{style:{overflowWrap:"anywhere",maxWidth:280},children:c.jsx(Nd,{grant:f.after,field:T})})]},T))})]})}),c.jsx("p",{className:"grant-help",children:f.tokenImplications})]})}function Ty({clientId:f,sources:E,onRescoped:T}){const[r,D]=Y.useState(),[_,H]=Y.useState(),[G,O]=Y.useState(),[h,C]=Y.useState(),[M,N]=Y.useState(""),[w,J]=Y.useState(!1),[il,jl]=Y.useState(!1),ul=async()=>{const[Z,Tl]=await Promise.all([xl.clientGrant(f),xl.grantCatalog()]);D(Z.grant),H(yf(Z.grant)),O(Tl),C(void 0),N("")};Y.useEffect(()=>{ul().catch(Z=>N(Z.message))},[f]);const k=async()=>{if(!(!_||!r)){J(!0),N(""),jl(!1);try{const Z=await xl.updateClientGrant(f,{...h?Bd(h.after):Hd(_),expectedRevision:r.revision,dryRun:!h});h?(D(Z.after),H(yf(Z.after)),C(void 0),jl(!0),T(Z.after)):C(Z)}catch(Z){C(void 0),N(Z instanceof Error?Z.message:"Grant update failed")}finally{J(!1)}}};return c.jsxs("section",{children:[c.jsx("div",{className:"section-title",children:"Permissions"}),r&&c.jsxs("p",{className:"grant-help",children:["Revision ",r.revision,". Review source access, direct tools, and delegated work independently."]}),r&&c.jsx(Ay,{clientId:f,revision:r.revision}),!!(r!=null&&r.repairReasons.length)&&c.jsxs("p",{role:"status",style:{color:"var(--warning)"},children:["Delegation needs repair: ",r.repairReasons.join(", "),". Review and explicitly grant the missing bindings below."]}),_&&G&&c.jsx(qd,{draft:_,catalog:G,sources:E,existing:!0,setDraft:Z=>{H(Z),C(void 0),jl(!1)}}),M&&c.jsxs("p",{role:"alert",style:{color:"var(--error)"},children:[M," ",c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>void ul().catch(Z=>N(Z.message)),children:"Reload current grant"})]}),h&&c.jsx(Yd,{preview:h}),il&&c.jsx("p",{role:"status",children:"Permissions saved. Credentials are unchanged."}),c.jsx("button",{type:"button",className:"btn btn-primary",disabled:w||!_||!G,onClick:()=>void k(),children:w?"Checking…":h?"Apply reviewed changes":"Preview changes"})]})}function Ay({clientId:f,revision:E}){const[T,r]=Y.useState(),[D,_]=Y.useState(!1);return Y.useEffect(()=>{let H=!0;const G=()=>void xl.agentsSpend().then(h=>{H&&(r(h.find(C=>C.client_id===f)),_(!1))}).catch(()=>{H&&_(!0)});G();const O=setInterval(G,2e4);return()=>{H=!1,clearInterval(O)}},[f,E]),D?c.jsx("p",{role:"status",children:"Delegated spend is unavailable. Reload to check before starting more work."}):T?c.jsxs("div",{style:{border:"1px solid var(--border)",padding:12,marginBottom:14},children:[c.jsx("strong",{children:"Delegated work"}),c.jsxs("p",{children:[T.inflight_count," unfinished jobs · Daily cap: ",T.cap_usd_per_day===null?"Unlimited":`$${T.cap_usd_per_day.toFixed(2)}`]}),c.jsxs("p",{className:"grant-help",children:["Recorded today: $",(T.spent_cents_today/100).toFixed(2),". Known outstanding reservations: $",(T.pending_cents/100).toFixed(2),", including overdue calls from earlier days."]}),T.unknown_count>0&&c.jsxs("p",{role:"status",style:{color:"var(--warning)"},children:[T.unknown_count," unresolved calls have an unknown cost. The known amounts above do not bound total liability; a finite cap refuses further calls until reconciliation."]})]}):null}function Ey({serverUrl:f,clientId:E,credentialFile:T=!0}){const[r,D]=Y.useState();return Y.useEffect(()=>{xl.grantCatalog().then(D).catch(()=>{})},[]),c.jsxs("section",{children:[c.jsx("div",{className:"section-title",children:"Connect this agent"}),c.jsx("p",{children:"Follow your harness guide for the supported connection and reload steps. Grok Bot and Muse can use GBrain inside their own computer when its prerequisites pass."}),c.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:12},children:r==null?void 0:r.harnesses.map(_=>c.jsx("a",{href:_.documentation,target:"_blank",rel:"noreferrer",children:_.label},_.id))}),T?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"grant-help",children:"Use the credential file saved at registration in the target environment. Restrict its file permissions to the owner before connecting."}),c.jsx("div",{className:"code-block",children:c.jsx("pre",{style:{whiteSpace:"pre-wrap"},children:`gbrain connect ${f}/mcp --credentials-file /absolute/private/credentials.json --harness YOUR_HARNESS --install`})})]}):c.jsx("p",{className:"grant-help",children:"Follow your harness guide for this credential type. The thin CLI used by Grok Bot and Muse requires a renewable OAuth client with client_credentials; register one above to use that connection."}),c.jsxs("p",{className:"grant-help",children:["Client ID: ",E,". Installing on the server host does not configure a different agent's computer."]})]})}function _y(f){const E=Math.floor((Date.now()-f.getTime())/1e3);return E<60?"just now":E<3600?`${Math.floor(E/60)}m ago`:E<86400?`${Math.floor(E/3600)}h ago`:`${Math.floor(E/86400)}d ago`}function Oy(){const[f,E]=Y.useState([]),[T,r]=Y.useState([]),[D,_]=Y.useState(!0),[H,G]=Y.useState(!1),[O,h]=Y.useState(null),[C,M]=Y.useState(!1),[N,w]=Y.useState(null),[J,il]=Y.useState(null);Y.useEffect(()=>{jl(),xl.sources().then(r).catch(()=>{})},[]);const jl=()=>{xl.agents().then(E).catch(()=>{})};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[c.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Agents"}),c.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[c.jsxs("label",{style:{fontSize:13,color:"var(--text-secondary)",display:"flex",alignItems:"center",gap:6,cursor:"pointer"},children:[c.jsx("input",{type:"checkbox",checked:D,onChange:ul=>_(ul.target.checked)})," Hide revoked"]}),c.jsx("button",{className:"btn btn-secondary",onClick:()=>M(!0),children:"+ API Key"}),c.jsx("button",{className:"btn btn-primary",onClick:()=>G(!0),children:"+ OAuth Client"})]})]}),(()=>{const ul=f.filter(k=>!D||k.status!=="revoked");return f.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No agents registered. Register your first agent to get started."}):ul.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:'All agents are revoked. Uncheck "Hide revoked" to view them.'}):c.jsxs(c.Fragment,{children:[c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Name"}),c.jsx("th",{children:"Type"}),c.jsx("th",{children:"Scopes"}),c.jsx("th",{children:"Sources"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Requests"}),c.jsx("th",{children:"Last Used"})]})}),c.jsx("tbody",{children:ul.map(k=>c.jsxs("tr",{onClick:()=>il(k),style:{cursor:"pointer"},children:[c.jsx("td",{style:{fontWeight:500},children:k.name||k.client_name}),c.jsx("td",{children:c.jsx("span",{className:`badge ${k.auth_type==="oauth"?"badge-read":"badge-write"}`,style:{fontSize:11},children:k.auth_type==="oauth"?"OAuth":"API Key"})}),c.jsx("td",{children:(k.scope||"").split(" ").filter(Boolean).map(Z=>c.jsx("span",{className:`badge badge-${Z}`,style:{marginRight:4},children:Z},Z))}),c.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12},children:k.auth_type==="oauth"?`${k.source_id||"none"} · ${(k.federated_read||[]).length} readable`:"Unscoped"}),c.jsx("td",{children:c.jsx("span",{className:`badge ${k.status==="active"?"badge-success":"badge-danger"}`,children:k.status})}),c.jsxs("td",{children:[c.jsx("span",{style:{fontWeight:500},children:k.requests_today||0}),c.jsxs("span",{style:{color:"var(--text-muted)",fontSize:12},children:[" / ",k.total_requests||0]})]}),c.jsx("td",{style:{color:"var(--text-secondary)"},children:k.last_used_at?_y(new Date(k.last_used_at)):"Never"})]},k.id))})]}),c.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginTop:12},children:[f.filter(k=>k.status==="active").length," active / ",f.length," total"]})]})})(),H&&c.jsx(My,{sources:T,onClose:()=>G(!1),onRegistered:ul=>{G(!1),h(ul),jl()}}),O&&c.jsx(Cy,{credentials:O,onClose:()=>h(null)}),J&&c.jsx(Uy,{agent:J,sources:T,onClose:()=>il(null),onRevoked:jl,onRecovered:ul=>{il(null),h(ul)},onRescoped:({sourceId:ul,federatedRead:k})=>{il(Z=>Z&&{...Z,source_id:ul,federated_read:k}),jl()}},J.id),C&&c.jsx(Ny,{onClose:()=>M(!1),onCreated:ul=>{M(!1),w(ul),jl()}}),N&&c.jsx(Dy,{token:N,onClose:()=>w(null)})]})}function Ny({onClose:f,onCreated:E}){const[T,r]=Y.useState(""),[D,_]=Y.useState(!1),[H,G]=Y.useState(""),O=async h=>{if(h.preventDefault(),!T.trim()){G("Name required");return}_(!0);try{const C=await xl.createApiKey(T.trim());E({name:C.name,token:C.token})}catch(C){G(C instanceof Error?C.message:"Failed")}finally{_(!1)}};return c.jsx("div",{className:"modal-overlay",onClick:f,children:c.jsxs("form",{className:"modal",onClick:h=>h.stopPropagation(),onSubmit:O,children:[c.jsx("div",{className:"modal-title",children:"Create API Key"}),c.jsx("p",{style:{color:"var(--text-secondary)",fontSize:13,marginBottom:16},children:"API keys use simple bearer token auth. They grant full read+write+admin access. For scoped access, use OAuth clients instead."}),c.jsxs("div",{style:{marginBottom:16},children:[c.jsx("label",{children:"Key Name"}),c.jsx("input",{placeholder:"e.g. claude-code-local",value:T,onChange:h=>r(h.target.value),autoFocus:!0})]}),H&&c.jsx("div",{style:{color:"var(--error)",fontSize:13,marginBottom:12},children:H}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end"},children:[c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:f,children:"Cancel"}),c.jsx("button",{type:"submit",className:"btn btn-primary",disabled:D,children:D?"Creating...":"Create Key"})]})]})})}function Dy({token:f,onClose:E}){const T=r=>navigator.clipboard.writeText(r);return c.jsx("div",{className:"modal-overlay",children:c.jsxs("div",{className:"modal",style:{maxWidth:560},children:[c.jsxs("div",{style:{textAlign:"center",marginBottom:16},children:[c.jsx("div",{style:{fontSize:36,color:"var(--success)",marginBottom:8},children:"✓"}),c.jsx("div",{style:{fontSize:20,fontWeight:600},children:"API Key Created"})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Name"}),c.jsx("div",{className:"code-block",children:c.jsx("span",{children:f.name})})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Bearer Token"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:f.token}),c.jsx("button",{className:"copy-btn",onClick:()=>T(f.token),children:"Copy"})]})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Usage"}),c.jsxs("div",{className:"code-block",children:[c.jsx("pre",{style:{whiteSpace:"pre-wrap",margin:0,fontSize:12},children:`Authorization: Bearer ${f.token}`}),c.jsx("button",{className:"copy-btn",onClick:()=>T(`Authorization: Bearer ${f.token}`),children:"Copy"})]})]}),c.jsx("div",{className:"warning-bar",children:"Save this token now. It will not be shown again."}),c.jsx("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:c.jsx("button",{className:"btn btn-primary",onClick:E,children:"Done"})})]})})}function My({sources:f,onClose:E,onRegistered:T}){const[r,D]=Y.useState(""),[_,H]=Y.useState(()=>yf()),[G,O]=Y.useState(),[h,C]=Y.useState(),[M,N]=Y.useState(!1),[w,J]=Y.useState(""),[il,jl]=Y.useState();Y.useEffect(()=>{xl.grantCatalog().then(O).catch(Z=>J(Z.message))},[]);const ul=async Z=>{if(Z.preventDefault(),!r.trim()){J("Name required");return}N(!0),J("");try{const Tl=await xl.registerClient({...h?Bd(h.after):Hd(_),name:r.trim(),dryRun:!h});h?T({clientId:Tl.clientId,clientSecret:Tl.clientSecret,name:r.trim(),credentials:Tl.credentials}):C(Tl)}catch(Tl){if(C(void 0),J(Tl instanceof Error?Tl.message:"Registration failed"),h)try{const wl=(await xl.agents()).filter(Hl=>Hl.auth_type==="oauth"&&Hl.status==="active"&&(Hl.name||Hl.client_name)===r.trim());wl.length===1&&jl({clientId:wl[0].id||wl[0].client_id,name:r.trim()})}catch{}}finally{N(!1)}},k=async()=>{if(il){N(!0),J("");try{T(await xl.recoverClient(il.clientId))}catch(Z){J(Z instanceof Error?Z.message:"Credential recovery failed")}finally{N(!1)}}};return c.jsx("div",{className:"modal-overlay",onClick:E,children:c.jsxs("form",{className:"modal",style:{maxWidth:700,width:"90vw",minWidth:0,maxHeight:"90vh",overflowY:"auto"},onClick:Z=>Z.stopPropagation(),onSubmit:ul,children:[c.jsx("div",{className:"modal-title",children:"Register agent"}),c.jsxs("fieldset",{disabled:M||!!il,style:{border:0,padding:0,margin:0},children:[c.jsxs("div",{style:{marginBottom:16},children:[c.jsx("label",{htmlFor:"agent-name",children:"Agent name"}),c.jsx("input",{id:"agent-name",placeholder:"muse-personal-example",value:r,onChange:Z=>{D(Z.target.value),C(void 0)},autoFocus:!0})]}),G&&c.jsx(qd,{draft:_,setDraft:Z=>{H(Z),C(void 0)},catalog:G,sources:f})]}),h&&c.jsx(Yd,{preview:h}),w&&c.jsx("p",{role:"alert",style:{color:"var(--error)"},children:w}),il&&c.jsxs("div",{role:"status",children:[c.jsxs("p",{children:["A registered client named ",il.name," exists. Recover its saved credential delivery before retrying registration. This preserves its permissions and secret."]}),c.jsx("button",{type:"button",className:"btn btn-secondary",disabled:M,onClick:()=>void k(),children:"Recover credentials"})]}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end"},children:[c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:E,children:"Cancel"}),c.jsx("button",{type:"submit",className:"btn btn-primary",disabled:M||!G||!!il,children:M?"Checking…":h?"Register with reviewed permissions":"Preview permissions"})]})]})})}function Cy({credentials:f,onClose:E}){const T=D=>navigator.clipboard.writeText(D),r=()=>{const D=f.credentials??{version:1,mcp_url:`${window.location.origin}/mcp`,issuer_url:window.location.origin,client_id:f.clientId,client_secret:f.clientSecret},_=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}),H=URL.createObjectURL(_),G=document.createElement("a");G.href=H,G.download=`${f.name}-credentials.json`,G.click(),URL.revokeObjectURL(H)};return c.jsx("div",{className:"modal-overlay",children:c.jsxs("div",{className:"modal",style:{maxWidth:560},children:[c.jsxs("div",{style:{textAlign:"center",marginBottom:16},children:[c.jsx("div",{style:{fontSize:36,color:"var(--success)",marginBottom:8},children:"✓"}),c.jsx("div",{style:{fontSize:20,fontWeight:600},children:"Agent Registered"})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Client ID"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:f.clientId}),c.jsx("button",{className:"copy-btn",onClick:()=>T(f.clientId),children:"Copy"})]})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Client Secret"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:f.clientSecret}),c.jsx("button",{className:"copy-btn",onClick:()=>T(f.clientSecret),children:"Copy"})]})]}),c.jsx("div",{className:"warning-bar",children:"Download the credential file now. Keep it private, set its permissions to 0600 on the target computer, and use it with gbrain connect. If delivery is lost, use Recover credentials in this client's Agents entry."}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:[c.jsx("button",{className:"btn btn-secondary",onClick:r,children:"Download as JSON"}),c.jsx("button",{className:"btn btn-primary",onClick:E,children:"Done"})]})]})})}function Uy({agent:f,sources:E,onClose:T,onRevoked:r,onRescoped:D,onRecovered:_}){const H=window.location.origin,G=f.id||f.client_id||"",O=f.auth_type==="oauth",[h,C]=Y.useState(!1),[M,N]=Y.useState(""),w=async()=>{C(!0),N("");try{_(await xl.recoverClient(G))}catch(J){N(J instanceof Error?J.message:"Credential recovery failed")}finally{C(!1)}};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"drawer-overlay",onClick:T}),c.jsxs("div",{className:"drawer",children:[c.jsx("button",{className:"drawer-close",onClick:T,children:"✕"}),c.jsx("div",{style:{fontSize:18,fontWeight:600,marginBottom:4},children:f.name||f.client_name}),c.jsx("span",{className:`badge ${f.status==="active"?"badge-success":"badge-danger"}`,children:f.status}),c.jsx("div",{className:"section-title",children:"Details"}),c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Client ID"}),c.jsxs("span",{className:"mono",children:[(f.id||f.id||f.client_id||"").substring(0,24),"..."]}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Scopes"}),c.jsx("span",{children:(f.scope||"").split(" ").filter(Boolean).map(J=>c.jsx("span",{className:`badge badge-${J}`,style:{marginRight:4},children:J},J))}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Registered"}),c.jsx("span",{children:new Date(f.created_at).toLocaleDateString()}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Token TTL"}),c.jsx("span",{children:f.token_ttl?f.token_ttl>=86400?`${Math.floor(f.token_ttl/86400)}d`:f.token_ttl>=3600?`${Math.floor(f.token_ttl/3600)}h`:`${f.token_ttl}s`:"1h (default)"})]}),O&&c.jsx(Ty,{clientId:G,sources:E,onRescoped:D}),c.jsx(Ey,{serverUrl:H,clientId:G,credentialFile:O&&f.grant_types.includes("client_credentials")}),O&&f.status==="active"&&f.grant_types.includes("client_credentials")&&c.jsxs("div",{children:[c.jsx("p",{className:"grant-help",children:"If registration finished but its download was lost, recover the saved credential delivery. Existing permissions and credentials stay unchanged."}),c.jsx("button",{type:"button",className:"btn btn-secondary",disabled:h,onClick:()=>void w(),children:h?"Recovering…":"Recover credentials"}),M&&c.jsx("p",{role:"alert",style:{color:"var(--error)"},children:M})]}),c.jsxs("div",{style:{marginTop:32},children:[f.status==="active"&&c.jsx("button",{className:"btn btn-danger",onClick:async()=>{if(confirm(`Revoke ${f.name||f.client_name}? All active tokens will be invalidated.`))try{f.auth_type==="oauth"?await xl.revokeClient(f.id||f.client_id||""):await xl.revokeApiKey(f.name||""),r(),T()}catch(J){alert("Revoke failed: "+(J instanceof Error?J.message:"unknown error"))}},children:"Revoke Agent"}),f.status==="revoked"&&c.jsx("span",{style:{color:"var(--text-muted)",fontSize:13},children:"This agent has been revoked."})]})]})]})}function Ry(){const[f,E]=Y.useState({rows:[],total:0,page:1,pages:1}),[T,r]=Y.useState(1),[D,_]=Y.useState("all"),[H,G]=Y.useState(null);Y.useEffect(()=>{O(T)},[T,D]);const O=N=>{const w=D!=="all"?`&agent=${encodeURIComponent(D)}`:"";xl.requests(N,w).then(E).catch(()=>{})},h=N=>{const w=Date.now()-new Date(N).getTime();return w<6e4?`${Math.floor(w/1e3)}s ago`:w<36e5?`${Math.floor(w/6e4)} min ago`:w<864e5?`${Math.floor(w/36e5)}h ago`:new Date(N).toLocaleDateString()},C=N=>{if(!N)return null;const{query:w,slug:J,partial:il,limit:jl,...ul}=N,k=[];return w&&k.push(`"${w}"`),J&&k.push(J),il&&k.push(`~${il}`),jl&&k.push(`limit=${jl}`),Object.keys(ul).length>0&&k.push(`+${Object.keys(ul).length} params`),k.join(" ")},M=new Map;return f.rows.forEach(N=>{N.token_name&&M.set(N.token_name,N.agent_name||N.token_name)}),c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[c.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Request Log"}),c.jsxs("select",{value:D,onChange:N=>{_(N.target.value),r(1)},style:{background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)",borderRadius:6,padding:"4px 8px",fontSize:13},children:[c.jsx("option",{value:"all",children:"All agents"}),[...M.entries()].map(([N,w])=>c.jsx("option",{value:N,children:w},N))]})]}),f.rows.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No requests yet."}):c.jsxs(c.Fragment,{children:[c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Time"}),c.jsx("th",{children:"Agent"}),c.jsx("th",{children:"Operation"}),c.jsx("th",{children:"Params"}),c.jsx("th",{children:"Latency"}),c.jsx("th",{children:"Status"})]})}),c.jsx("tbody",{children:f.rows.map(N=>c.jsxs(Ud.Fragment,{children:[c.jsxs("tr",{onClick:()=>G(H===N.id?null:N.id),style:{cursor:"pointer"},children:[c.jsx("td",{style:{color:"var(--text-secondary)",whiteSpace:"nowrap"},children:h(N.created_at)}),c.jsx("td",{children:c.jsx("a",{style:{color:"var(--text-link, #88aaff)",cursor:"pointer",textDecoration:"none",fontWeight:500},onClick:w=>{w.stopPropagation(),_(N.token_name),r(1)},children:N.agent_name||N.token_name})}),c.jsx("td",{className:"mono",children:N.operation}),c.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C(N.params)}),c.jsxs("td",{className:"mono",children:[N.latency_ms,"ms"]}),c.jsx("td",{children:c.jsx("span",{className:`badge badge-${N.status}`,children:N.status})})]}),H===N.id&&c.jsx("tr",{children:c.jsx("td",{colSpan:6,style:{background:"var(--bg-secondary, #0f0f1a)",padding:16},children:c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[c.jsx("span",{style:{color:"var(--text-muted)"},children:"Time"}),c.jsx("span",{children:new Date(N.created_at).toLocaleString()}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Agent"}),c.jsx("span",{className:"mono",children:N.token_name}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Operation"}),c.jsx("span",{className:"mono",children:N.operation}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Latency"}),c.jsxs("span",{children:[N.latency_ms,"ms"]}),N.params&&c.jsxs(c.Fragment,{children:[c.jsx("span",{style:{color:"var(--text-muted)"},children:"Params"}),c.jsx("pre",{className:"mono",style:{margin:0,whiteSpace:"pre-wrap",fontSize:12},children:JSON.stringify(N.params,null,2)})]}),N.error_message&&c.jsxs(c.Fragment,{children:[c.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:"Error"}),c.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:N.error_message})]})]})})})]},N.id))})]}),c.jsxs("div",{className:"pagination",children:[c.jsxs("span",{children:["Page ",f.page," of ",f.pages," (",f.total," total)"]}),c.jsxs("div",{style:{display:"flex",gap:8},children:[c.jsx("button",{disabled:f.page<=1,onClick:()=>r(N=>N-1),children:"Previous"}),c.jsx("button",{disabled:f.page>=f.pages,onClick:()=>r(N=>N+1),children:"Next"})]})]})]})]})}function Hy({markup:f}){return c.jsx("div",{style:{width:"100%",overflow:"auto"},dangerouslySetInnerHTML:{__html:f}})}function Lu({type:f,ariaLabel:E}){const[T,r]=Y.useState(""),[D,_]=Y.useState("");return Y.useEffect(()=>{let H=!1;return xl.calibrationChart(f).then(G=>{H||r(G)}).catch(G=>{H||_(G.message??"fetch failed")}),()=>{H=!0}},[f]),D?c.jsxs("div",{style:{padding:16,color:"var(--error)"},role:"alert",children:[E,": ",D]}):T?c.jsx(Hy,{markup:T}):c.jsxs("div",{style:{padding:16,color:"var(--text-muted)"},children:[E," loading..."]})}function By(){const[f,E]=Y.useState(null),[T,r]=Y.useState(!0),[D,_]=Y.useState("");if(Y.useEffect(()=>{xl.calibrationProfile().then(O=>{E(O),r(!1)}).catch(O=>{_(O.message??"fetch failed"),r(!1)})},[]),T)return c.jsx("div",{style:{padding:24,color:"var(--text-secondary)"},children:"Loading calibration profile…"});if(D)return c.jsxs("div",{style:{padding:24,color:"var(--error)"},role:"alert",children:["Could not load calibration profile: ",D]});if(!f)return c.jsxs("div",{style:{padding:24,maxWidth:700},children:[c.jsx("h1",{style:{marginBottom:16},children:"Calibration"}),c.jsx("p",{style:{color:"var(--text-secondary)"},children:"No calibration profile yet. Builds after 5+ resolved takes."}),c.jsx("pre",{style:{background:"var(--bg-secondary)",padding:12,borderRadius:4,color:"var(--text-primary)",marginTop:12,fontFamily:"var(--font-mono)"},children:"gbrain dream --phase calibration_profile"})]});const H=new Date(f.generated_at),G=Math.floor((Date.now()-H.getTime())/(1e3*60*60*24));return c.jsxs("div",{style:{padding:32,maxWidth:720},children:[c.jsx("h1",{style:{marginBottom:8},children:"Calibration"}),c.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginBottom:24},children:["Holder: ",f.holder," · ","Updated ",G===0?"today":`${G}d ago`,f.published&&" · published",f.grade_completion<.9&&` · ~${Math.round(f.grade_completion*100)}% graded`,!f.voice_gate_passed&&" · voice gate fell back to template"]}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Lu,{type:"brier-trend",ariaLabel:"Brier trend"})}),c.jsxs("section",{style:{marginBottom:32},children:[c.jsx("h2",{style:{fontSize:14,color:"var(--text-secondary)",marginBottom:12,fontWeight:400},children:"Pattern statements"}),c.jsx(Lu,{type:"pattern-statements",ariaLabel:"Pattern statements"})]}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Lu,{type:"domain-bars",ariaLabel:"Per-domain accuracy"})}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Lu,{type:"abandoned-threads",ariaLabel:"Abandoned threads"})}),f.active_bias_tags.length>0&&c.jsxs("section",{style:{marginBottom:32,color:"var(--text-muted)",fontSize:13},children:["Active bias tags: ",f.active_bias_tags.join(", ")]})]})}function qy(f){return f===0?"var(--accent-success, #2ea043)":f>=100?"var(--accent-danger, #f85149)":"var(--accent-warn, #d29922)"}function Dd(f){return`$${(f/100).toFixed(2)}`}function Yy(){const[f,E]=Y.useState(null),[T,r]=Y.useState(null);if(Y.useEffect(()=>{let _=!0,H=null;const G=async()=>{try{const O=await xl.jobsWatch();_&&(E(O),r(null))}catch(O){_&&r(O instanceof Error?O.message:String(O))}_&&(H=setTimeout(G,1e3))};return G(),()=>{_=!1,H&&clearTimeout(H)}},[]),T)return c.jsxs("div",{style:{padding:24,color:"var(--accent-danger, #f85149)"},children:[c.jsx("h2",{children:"Jobs Watch — error"}),c.jsx("pre",{style:{whiteSpace:"pre-wrap"},children:T})]});if(!f)return c.jsx("div",{style:{padding:24,color:"var(--text-muted, #777)"},children:"Loading jobs watch…"});const D=new Date(f.ts_ms).toLocaleTimeString();return c.jsxs("div",{style:{padding:24,fontFamily:'var(--font-mono, "JetBrains Mono", monospace)'},children:[c.jsxs("h1",{style:{fontSize:18,marginBottom:4},children:["Jobs Watch",c.jsxs("span",{style:{marginLeft:12,color:"var(--text-muted, #777)",fontSize:12,fontWeight:"normal"},children:["updated ",D]})]}),c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Queue"}),c.jsxs("div",{children:["waiting=",c.jsx("b",{children:f.queue_health.waiting})," ","active=",c.jsx("b",{children:f.queue_health.active})," ","stalled=",c.jsx("b",{style:{color:f.queue_health.stalled>0?"var(--accent-warn, #d29922)":void 0},children:f.queue_health.stalled})]})]}),f.by_type.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"By type (24h)"}),c.jsxs("table",{style:{borderCollapse:"collapse"},children:[c.jsx("thead",{children:c.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[c.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"name"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"total"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"done"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"fail"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"dead"})]})}),c.jsx("tbody",{children:f.by_type.slice(0,6).map(_=>c.jsxs("tr",{children:[c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.name}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.total}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.completed}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.failed}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.dead})]},_.name))})]})]}),c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Lease pressure (1h)"}),c.jsxs("div",{style:{color:qy(f.lease_pressure_1h)},children:[f.lease_pressure_1h," bounce",f.lease_pressure_1h===1?"":"s"]})]}),f.top_errors.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Top errors (24h)"}),c.jsx("table",{style:{borderCollapse:"collapse"},children:c.jsx("tbody",{children:f.top_errors.slice(0,5).map(_=>c.jsxs("tr",{children:[c.jsxs("td",{style:{textAlign:"right",padding:"4px 12px 4px 0",color:"var(--text-muted, #777)"},children:[_.count,"×"]}),c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.cluster})]},_.cluster))})})]}),f.budget_owners.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Budget owners"}),c.jsxs("table",{style:{borderCollapse:"collapse"},children:[c.jsx("thead",{children:c.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[c.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"owner"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"spent"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"remaining"})]})}),c.jsx("tbody",{children:f.budget_owners.slice(0,5).map(_=>c.jsxs("tr",{children:[c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.owner_id}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Dd(_.total_spent_cents)}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Dd(_.remaining_cents)})]},_.owner_id))})]})]})]})}function Md(){const f=window.location.hash.replace("#","")||"dashboard";return["login","dashboard","agents","log","calibration","jobs"].includes(f)?f:"dashboard"}function Gy(){const[f,E]=Y.useState(Md);Y.useEffect(()=>{const D=()=>E(Md());return window.addEventListener("hashchange",D),()=>window.removeEventListener("hashchange",D)},[]);const T=D=>{window.location.hash=D,E(D)};if(f==="login")return c.jsx(Sy,{onLogin:()=>T("dashboard")});const r=async()=>{if(confirm("Sign out every active admin session, including other browsers and tabs? Each one will need to re-authenticate via a fresh magic link.")){try{await xl.signOutEverywhere()}catch{}T("login")}};return c.jsxs("div",{className:"app",children:[c.jsxs("nav",{className:"sidebar",children:[c.jsx("div",{className:"sidebar-logo",children:"GBrain"}),c.jsxs("div",{className:"sidebar-nav",children:[c.jsx("a",{className:`nav-item ${f==="dashboard"?"active":""}`,onClick:()=>T("dashboard"),children:"Dashboard"}),c.jsx("a",{className:`nav-item ${f==="agents"?"active":""}`,onClick:()=>T("agents"),children:"Agents"}),c.jsx("a",{className:`nav-item ${f==="log"?"active":""}`,onClick:()=>T("log"),children:"Request Log"}),c.jsx("a",{className:`nav-item ${f==="calibration"?"active":""}`,onClick:()=>T("calibration"),children:"Calibration"}),c.jsx("a",{className:`nav-item ${f==="jobs"?"active":""}`,onClick:()=>T("jobs"),children:"Jobs Watch"})]}),c.jsx("div",{style:{marginTop:"auto",padding:"16px 12px",borderTop:"1px solid var(--border)"},children:c.jsx("button",{onClick:r,style:{background:"transparent",border:"1px solid var(--border)",color:"var(--text-secondary)",padding:"6px 10px",borderRadius:6,fontSize:12,cursor:"pointer",width:"100%"},title:"Revoke every active admin session — every browser, every tab",children:"Sign out everywhere"})})]}),c.jsxs("main",{className:"main",children:[f==="dashboard"&&c.jsx(xy,{}),f==="agents"&&c.jsx(Oy,{}),f==="log"&&c.jsx(Ry,{}),f==="calibration"&&c.jsx(By,{}),f==="jobs"&&c.jsx(Yy,{})]})]})}py.createRoot(document.getElementById("root")).render(c.jsx(Ud.StrictMode,{children:c.jsx(Gy,{})})); diff --git a/admin/dist/assets/index-CLnyXRh0.css b/admin/dist/assets/index-CLnyXRh0.css new file mode 100644 index 00000000..a270151c --- /dev/null +++ b/admin/dist/assets/index-CLnyXRh0.css @@ -0,0 +1 @@ +:root{--bg-primary: #0a0a0f;--bg-secondary: #14141f;--bg-tertiary: #1e1e2e;--text-primary: #e0e0e0;--text-secondary: #888;--text-muted: #777;--accent: #3b82f6;--success: #22c55e;--warning: #f59e0b;--error: #ef4444;--font-mono: "JetBrains Mono", monospace;--font-sans: "Inter", system-ui, sans-serif}*{margin:0;padding:0;box-sizing:border-box}body{font-family:var(--font-sans);background:var(--bg-primary);color:var(--text-primary);font-size:14px;line-height:1.5}.app{display:flex;min-height:100vh}.sidebar{width:200px;background:var(--bg-secondary);border-right:1px solid #1e1e2e;padding:16px 0;flex-shrink:0;display:flex;flex-direction:column}.sidebar-logo{font-size:18px;font-weight:600;padding:0 16px 24px;color:var(--text-primary)}.sidebar-nav{display:flex;flex-direction:column;gap:2px}.nav-item{display:flex;align-items:center;gap:8px;padding:8px 16px;color:var(--text-secondary);text-decoration:none;font-size:13px;cursor:pointer;border-left:3px solid transparent;transition:all .15s}.nav-item:hover{background:var(--bg-tertiary);color:var(--text-primary)}.nav-item.active{border-left-color:var(--accent);background:var(--bg-tertiary);color:var(--text-primary)}.main{flex:1;padding:24px 32px;overflow-y:auto}.page-title{font-size:24px;font-weight:600;margin-bottom:24px}.metrics{display:flex;gap:16px;margin-bottom:24px}.metric{background:var(--bg-secondary);padding:16px 20px;border-radius:6px;min-width:140px}.metric-value{font-family:var(--font-mono);font-size:28px;font-weight:500}.metric-label{font-size:12px;color:var(--text-secondary);margin-top:4px}table{width:100%;border-collapse:collapse}th{text-align:left;font-size:11px;text-transform:uppercase;color:var(--text-muted);padding:8px 12px;font-weight:500;letter-spacing:.5px}td{padding:10px 12px;font-size:13px;border-top:1px solid #1a1a2a}tr:hover td{background:var(--bg-tertiary)}.badge{display:inline-block;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:500}.badge-read{background:#3b82f626;color:var(--accent)}.badge-write{background:#f59e0b26;color:var(--warning)}.badge-admin{background:#ef444426;color:var(--error)}.badge-success{background:#22c55e26;color:var(--success)}.badge-error{background:#ef444426;color:var(--error)}.status-dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px}.status-active{background:var(--success)}.status-warning{background:var(--warning)}.status-inactive{background:var(--text-muted)}.btn{padding:8px 16px;border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;border:none;transition:all .15s}.btn-primary{background:var(--accent);color:#fff}.btn-primary:hover{background:#2563eb}.btn-secondary{background:transparent;color:var(--text-secondary);border:1px solid #333}.btn-secondary:hover{border-color:var(--text-secondary);color:var(--text-primary)}.btn-danger{background:transparent;color:var(--error);border:1px solid var(--error)}.btn-danger:hover{background:#ef44441a}input,select,textarea{background:var(--bg-primary);border:1px solid #333;color:var(--text-primary);padding:8px 12px;border-radius:6px;font-size:13px;font-family:var(--font-sans);width:100%}input:focus,select:focus,textarea:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 2px #3b82f633}input::placeholder{color:var(--text-muted)}label{display:block;font-size:13px;font-weight:500;margin-bottom:6px}.grant-help{color:var(--text-secondary);font-size:12px;line-height:1.5;margin:6px 0 12px}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#000000b3;display:flex;align-items:center;justify-content:center;z-index:100}.modal{background:var(--bg-secondary);border-radius:8px;padding:24px;min-width:420px;max-width:520px}.modal-title{font-size:18px;font-weight:600;margin-bottom:20px}.drawer-overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#00000080;z-index:90}.drawer{position:fixed;right:0;top:0;bottom:0;width:420px;background:var(--bg-secondary);border-left:1px solid var(--accent);padding:24px;z-index:91;overflow-y:auto}.drawer-close{position:absolute;top:16px;right:16px;background:none;border:none;color:var(--text-muted);font-size:18px;cursor:pointer}.section-title{font-size:11px;text-transform:uppercase;color:var(--text-muted);letter-spacing:.5px;margin:20px 0 12px;font-weight:500}.health-panel{background:var(--bg-secondary);border-radius:6px;padding:16px}.health-row{display:flex;justify-content:space-between;padding:6px 0;font-size:13px}.code-block{background:var(--bg-primary);border-radius:6px;padding:12px;font-family:var(--font-mono);font-size:12px;overflow-x:auto;position:relative}.code-block .copy-btn{position:absolute;top:8px;right:8px;background:var(--accent);color:#fff;border:none;padding:4px 10px;border-radius:4px;font-size:11px;cursor:pointer}.feed{max-height:400px;overflow-y:auto}.feed-empty{color:var(--text-muted);text-align:center;padding:32px;font-size:13px}.sparkline{display:inline-block;vertical-align:middle}.filter-bar{display:flex;gap:12px;margin-bottom:16px;align-items:center}.filter-bar select{width:auto;min-width:140px}.pagination{display:flex;justify-content:space-between;align-items:center;padding:12px 0;font-size:13px;color:var(--text-secondary)}.pagination button{background:var(--bg-secondary);border:1px solid #333;color:var(--text-primary);padding:6px 12px;border-radius:4px;cursor:pointer;font-size:12px}.pagination button:disabled{opacity:.3;cursor:default}.warning-bar{background:#f59e0b26;border:1px solid var(--warning);color:var(--warning);padding:10px 16px;border-radius:6px;font-size:13px;margin:12px 0}.checkbox-group{display:flex;gap:16px;flex-wrap:wrap}.checkbox-label{display:flex;align-items:center;gap:6px;font-size:13px;cursor:pointer}.checkbox-label input[type=checkbox]{width:auto;flex-shrink:0}.tabs{display:flex;gap:0;margin-bottom:12px}.tab{padding:6px 12px;font-size:13px;color:var(--text-secondary);cursor:pointer;border-bottom:2px solid transparent}.tab.active{color:var(--accent);border-bottom-color:var(--accent)}.login-page{display:flex;align-items:center;justify-content:center;min-height:100vh;background:var(--bg-primary)}.login-box{text-align:left;width:340px}.login-logo{font-size:32px;font-weight:600;margin-bottom:32px}.login-hint{color:var(--text-muted);font-size:12px;margin-top:12px}.login-error{color:var(--error);font-size:13px;margin-top:8px}.mono{font-family:var(--font-mono);font-size:12px}@media(max-width:768px){.sidebar{display:none}.main{padding:16px}.metrics{flex-wrap:wrap}.drawer{width:100%}} diff --git a/admin/dist/assets/index-CviJXT-1.js b/admin/dist/assets/index-CviJXT-1.js deleted file mode 100644 index 674e9279..00000000 --- a/admin/dist/assets/index-CviJXT-1.js +++ /dev/null @@ -1,56 +0,0 @@ -(function(){const M=document.createElement("link").relList;if(M&&M.supports&&M.supports("modulepreload"))return;for(const N of document.querySelectorAll('link[rel="modulepreload"]'))h(N);new MutationObserver(N=>{for(const _ of N)if(_.type==="childList")for(const R of _.addedNodes)R.tagName==="LINK"&&R.rel==="modulepreload"&&h(R)}).observe(document,{childList:!0,subtree:!0});function E(N){const _={};return N.integrity&&(_.integrity=N.integrity),N.referrerPolicy&&(_.referrerPolicy=N.referrerPolicy),N.crossOrigin==="use-credentials"?_.credentials="include":N.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function h(N){if(N.ep)return;N.ep=!0;const _=E(N);fetch(N.href,_)}})();function Md(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var ff={exports:{}},jn={};/** - * @license React - * react-jsx-runtime.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var gd;function ey(){if(gd)return jn;gd=1;var o=Symbol.for("react.transitional.element"),M=Symbol.for("react.fragment");function E(h,N,_){var R=null;if(_!==void 0&&(R=""+_),N.key!==void 0&&(R=""+N.key),"key"in N){_={};for(var K in N)K!=="key"&&(_[K]=N[K])}else _=N;return N=_.ref,{$$typeof:o,type:h,key:R,ref:N!==void 0?N:null,props:_}}return jn.Fragment=M,jn.jsx=E,jn.jsxs=E,jn}var Sd;function ay(){return Sd||(Sd=1,ff.exports=ey()),ff.exports}var c=ay(),sf={exports:{}},k={};/** - * @license React - * react.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var pd;function ny(){if(pd)return k;pd=1;var o=Symbol.for("react.transitional.element"),M=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),h=Symbol.for("react.strict_mode"),N=Symbol.for("react.profiler"),_=Symbol.for("react.consumer"),R=Symbol.for("react.context"),K=Symbol.for("react.forward_ref"),A=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),B=Symbol.for("react.lazy"),D=Symbol.for("react.activity"),O=Symbol.iterator;function Q(d){return d===null||typeof d!="object"?null:(d=O&&d[O]||d["@@iterator"],typeof d=="function"?d:null)}var V={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},it=Object.assign,gt={};function ut(d,z,U){this.props=d,this.context=z,this.refs=gt,this.updater=U||V}ut.prototype.isReactComponent={},ut.prototype.setState=function(d,z){if(typeof d!="object"&&typeof d!="function"&&d!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,d,z,"setState")},ut.prototype.forceUpdate=function(d){this.updater.enqueueForceUpdate(this,d,"forceUpdate")};function w(){}w.prototype=ut.prototype;function X(d,z,U){this.props=d,this.context=z,this.refs=gt,this.updater=U||V}var Xt=X.prototype=new w;Xt.constructor=X,it(Xt,ut.prototype),Xt.isPureReactComponent=!0;var Vt=Array.isArray;function Qt(){}var at={H:null,A:null,T:null,S:null},kt=Object.prototype.hasOwnProperty;function El(d,z,U){var q=U.ref;return{$$typeof:o,type:d,key:z,ref:q!==void 0?q:null,props:U}}function Le(d,z){return El(d.type,z,d.props)}function Ol(d){return typeof d=="object"&&d!==null&&d.$$typeof===o}function $t(d){var z={"=":"=0",":":"=2"};return"$"+d.replace(/[=:]/g,function(U){return z[U]})}var Te=/\/+/g;function Ul(d,z){return typeof d=="object"&&d!==null&&d.key!=null?$t(""+d.key):z.toString(36)}function Tl(d){switch(d.status){case"fulfilled":return d.value;case"rejected":throw d.reason;default:switch(typeof d.status=="string"?d.then(Qt,Qt):(d.status="pending",d.then(function(z){d.status==="pending"&&(d.status="fulfilled",d.value=z)},function(z){d.status==="pending"&&(d.status="rejected",d.reason=z)})),d.status){case"fulfilled":return d.value;case"rejected":throw d.reason}}throw d}function x(d,z,U,q,$){var I=typeof d;(I==="undefined"||I==="boolean")&&(d=null);var ot=!1;if(d===null)ot=!0;else switch(I){case"bigint":case"string":case"number":ot=!0;break;case"object":switch(d.$$typeof){case o:case M:ot=!0;break;case B:return ot=d._init,x(ot(d._payload),z,U,q,$)}}if(ot)return $=$(d),ot=q===""?"."+Ul(d,0):q,Vt($)?(U="",ot!=null&&(U=ot.replace(Te,"$&/")+"/"),x($,z,U,"",function(Oa){return Oa})):$!=null&&(Ol($)&&($=Le($,U+($.key==null||d&&d.key===$.key?"":(""+$.key).replace(Te,"$&/")+"/")+ot)),z.push($)),1;ot=0;var Kt=q===""?".":q+":";if(Vt(d))for(var At=0;At>>1,St=x[ht];if(0>>1;htN(U,J))qN($,U)?(x[ht]=$,x[q]=J,ht=q):(x[ht]=U,x[z]=J,ht=z);else if(qN($,J))x[ht]=$,x[q]=J,ht=q;else break t}}return C}function N(x,C){var J=x.sortIndex-C.sortIndex;return J!==0?J:x.id-C.id}if(o.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var _=performance;o.unstable_now=function(){return _.now()}}else{var R=Date,K=R.now();o.unstable_now=function(){return R.now()-K}}var A=[],p=[],B=1,D=null,O=3,Q=!1,V=!1,it=!1,gt=!1,ut=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,X=typeof setImmediate<"u"?setImmediate:null;function Xt(x){for(var C=E(p);C!==null;){if(C.callback===null)h(p);else if(C.startTime<=x)h(p),C.sortIndex=C.expirationTime,M(A,C);else break;C=E(p)}}function Vt(x){if(it=!1,Xt(x),!V)if(E(A)!==null)V=!0,Qt||(Qt=!0,$t());else{var C=E(p);C!==null&&Tl(Vt,C.startTime-x)}}var Qt=!1,at=-1,kt=5,El=-1;function Le(){return gt?!0:!(o.unstable_now()-Elx&&Le());){var ht=D.callback;if(typeof ht=="function"){D.callback=null,O=D.priorityLevel;var St=ht(D.expirationTime<=x);if(x=o.unstable_now(),typeof St=="function"){D.callback=St,Xt(x),C=!0;break l}D===E(A)&&h(A),Xt(x)}else h(A);D=E(A)}if(D!==null)C=!0;else{var d=E(p);d!==null&&Tl(Vt,d.startTime-x),C=!1}}break t}finally{D=null,O=J,Q=!1}C=void 0}}finally{C?$t():Qt=!1}}}var $t;if(typeof X=="function")$t=function(){X(Ol)};else if(typeof MessageChannel<"u"){var Te=new MessageChannel,Ul=Te.port2;Te.port1.onmessage=Ol,$t=function(){Ul.postMessage(null)}}else $t=function(){ut(Ol,0)};function Tl(x,C){at=ut(function(){x(o.unstable_now())},C)}o.unstable_IdlePriority=5,o.unstable_ImmediatePriority=1,o.unstable_LowPriority=4,o.unstable_NormalPriority=3,o.unstable_Profiling=null,o.unstable_UserBlockingPriority=2,o.unstable_cancelCallback=function(x){x.callback=null},o.unstable_forceFrameRate=function(x){0>x||125ht?(x.sortIndex=J,M(p,x),E(A)===null&&x===E(p)&&(it?(w(at),at=-1):it=!0,Tl(Vt,J-ht))):(x.sortIndex=St,M(A,x),V||Q||(V=!0,Qt||(Qt=!0,$t()))),x},o.unstable_shouldYield=Le,o.unstable_wrapCallback=function(x){var C=O;return function(){var J=O;O=C;try{return x.apply(this,arguments)}finally{O=J}}}})(df)),df}var jd;function iy(){return jd||(jd=1,rf.exports=uy()),rf.exports}var hf={exports:{}},Zt={};/** - * @license React - * react-dom.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Td;function cy(){if(Td)return Zt;Td=1;var o=mf();function M(A){var p="https://react.dev/errors/"+A;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(M){console.error(M)}}return o(),hf.exports=cy(),hf.exports}/** - * @license React - * react-dom-client.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Ad;function sy(){if(Ad)return Tn;Ad=1;var o=iy(),M=mf(),E=fy();function h(t){var l="https://react.dev/errors/"+t;if(1St||(t.current=ht[St],ht[St]=null,St--)}function U(t,l){St++,ht[St]=t.current,t.current=l}var q=d(null),$=d(null),I=d(null),ot=d(null);function Kt(t,l){switch(U(I,l),U($,t),U(q,null),l.nodeType){case 9:case 11:t=(t=l.documentElement)&&(t=t.namespaceURI)?Xr(t):0;break;default:if(t=l.tagName,l=l.namespaceURI)l=Xr(l),t=Qr(l,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}z(q),U(q,t)}function At(){z(q),z($),z(I)}function Oa(t){t.memoizedState!==null&&U(ot,t);var l=q.current,e=Qr(l,t.type);l!==e&&(U($,t),U(q,e))}function zn(t){$.current===t&&(z(q),z($)),ot.current===t&&(z(ot),Sn._currentValue=J)}var Lu,yf;function ze(t){if(Lu===void 0)try{throw Error()}catch(e){var l=e.stack.trim().match(/\n( *(at )?)/);Lu=l&&l[1]||"",yf=-1)":-1n||s[a]!==v[n]){var b=` -`+s[a].replace(" at new "," at ");return t.displayName&&b.includes("")&&(b=b.replace("",t.displayName)),b}while(1<=a&&0<=n);break}}}finally{Vu=!1,Error.prepareStackTrace=e}return(e=t?t.displayName||t.name:"")?ze(e):""}function Ud(t,l){switch(t.tag){case 26:case 27:case 5:return ze(t.type);case 16:return ze("Lazy");case 13:return t.child!==l&&l!==null?ze("Suspense Fallback"):ze("Suspense");case 19:return ze("SuspenseList");case 0:case 15:return Ku(t.type,!1);case 11:return Ku(t.type.render,!1);case 1:return Ku(t.type,!0);case 31:return ze("Activity");default:return""}}function vf(t){try{var l="",e=null;do l+=Ud(t,e),e=t,t=t.return;while(t);return l}catch(a){return` -Error generating stack: `+a.message+` -`+a.stack}}var Ju=Object.prototype.hasOwnProperty,wu=o.unstable_scheduleCallback,ku=o.unstable_cancelCallback,Rd=o.unstable_shouldYield,Bd=o.unstable_requestPaint,al=o.unstable_now,Hd=o.unstable_getCurrentPriorityLevel,gf=o.unstable_ImmediatePriority,Sf=o.unstable_UserBlockingPriority,An=o.unstable_NormalPriority,qd=o.unstable_LowPriority,pf=o.unstable_IdlePriority,Yd=o.log,Gd=o.unstable_setDisableYieldValue,Na=null,nl=null;function Il(t){if(typeof Yd=="function"&&Gd(t),nl&&typeof nl.setStrictMode=="function")try{nl.setStrictMode(Na,t)}catch{}}var ul=Math.clz32?Math.clz32:Zd,Xd=Math.log,Qd=Math.LN2;function Zd(t){return t>>>=0,t===0?32:31-(Xd(t)/Qd|0)|0}var _n=256,En=262144,On=4194304;function Ae(t){var l=t&42;if(l!==0)return l;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Nn(t,l,e){var a=t.pendingLanes;if(a===0)return 0;var n=0,u=t.suspendedLanes,i=t.pingedLanes;t=t.warmLanes;var f=a&134217727;return f!==0?(a=f&~u,a!==0?n=Ae(a):(i&=f,i!==0?n=Ae(i):e||(e=f&~t,e!==0&&(n=Ae(e))))):(f=a&~u,f!==0?n=Ae(f):i!==0?n=Ae(i):e||(e=a&~t,e!==0&&(n=Ae(e)))),n===0?0:l!==0&&l!==n&&(l&u)===0&&(u=n&-n,e=l&-l,u>=e||u===32&&(e&4194048)!==0)?l:n}function Ma(t,l){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&l)===0}function Ld(t,l){switch(t){case 1:case 2:case 4:case 8:case 64:return l+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function bf(){var t=On;return On<<=1,(On&62914560)===0&&(On=4194304),t}function $u(t){for(var l=[],e=0;31>e;e++)l.push(t);return l}function Da(t,l){t.pendingLanes|=l,l!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Vd(t,l,e,a,n,u){var i=t.pendingLanes;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=e,t.entangledLanes&=e,t.errorRecoveryDisabledLanes&=e,t.shellSuspendCounter=0;var f=t.entanglements,s=t.expirationTimes,v=t.hiddenUpdates;for(e=i&~e;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Wd=/[\n"\\]/g;function ml(t){return t.replace(Wd,function(l){return"\\"+l.charCodeAt(0).toString(16)+" "})}function li(t,l,e,a,n,u,i,f){t.name="",i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"?t.type=i:t.removeAttribute("type"),l!=null?i==="number"?(l===0&&t.value===""||t.value!=l)&&(t.value=""+hl(l)):t.value!==""+hl(l)&&(t.value=""+hl(l)):i!=="submit"&&i!=="reset"||t.removeAttribute("value"),l!=null?ei(t,i,hl(l)):e!=null?ei(t,i,hl(e)):a!=null&&t.removeAttribute("value"),n==null&&u!=null&&(t.defaultChecked=!!u),n!=null&&(t.checked=n&&typeof n!="function"&&typeof n!="symbol"),f!=null&&typeof f!="function"&&typeof f!="symbol"&&typeof f!="boolean"?t.name=""+hl(f):t.removeAttribute("name")}function Uf(t,l,e,a,n,u,i,f){if(u!=null&&typeof u!="function"&&typeof u!="symbol"&&typeof u!="boolean"&&(t.type=u),l!=null||e!=null){if(!(u!=="submit"&&u!=="reset"||l!=null)){ti(t);return}e=e!=null?""+hl(e):"",l=l!=null?""+hl(l):e,f||l===t.value||(t.value=l),t.defaultValue=l}a=a??n,a=typeof a!="function"&&typeof a!="symbol"&&!!a,t.checked=f?t.checked:!!a,t.defaultChecked=!!a,i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(t.name=i),ti(t)}function ei(t,l,e){l==="number"&&Cn(t.ownerDocument)===t||t.defaultValue===""+e||(t.defaultValue=""+e)}function $e(t,l,e,a){if(t=t.options,l){l={};for(var n=0;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ci=!1;if(Hl)try{var Ba={};Object.defineProperty(Ba,"passive",{get:function(){ci=!0}}),window.addEventListener("test",Ba,Ba),window.removeEventListener("test",Ba,Ba)}catch{ci=!1}var te=null,fi=null,Rn=null;function Xf(){if(Rn)return Rn;var t,l=fi,e=l.length,a,n="value"in te?te.value:te.textContent,u=n.length;for(t=0;t=Ya),Jf=" ",wf=!1;function kf(t,l){switch(t){case"keyup":return zh.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function $f(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Pe=!1;function _h(t,l){switch(t){case"compositionend":return $f(l);case"keypress":return l.which!==32?null:(wf=!0,Jf);case"textInput":return t=l.data,t===Jf&&wf?null:t;default:return null}}function Eh(t,l){if(Pe)return t==="compositionend"||!hi&&kf(t,l)?(t=Xf(),Rn=fi=te=null,Pe=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(l.ctrlKey||l.altKey||l.metaKey)||l.ctrlKey&&l.altKey){if(l.char&&1=l)return{node:e,offset:l-t};t=a}t:{for(;e;){if(e.nextSibling){e=e.nextSibling;break t}e=e.parentNode}e=void 0}e=as(e)}}function us(t,l){return t&&l?t===l?!0:t&&t.nodeType===3?!1:l&&l.nodeType===3?us(t,l.parentNode):"contains"in t?t.contains(l):t.compareDocumentPosition?!!(t.compareDocumentPosition(l)&16):!1:!1}function is(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var l=Cn(t.document);l instanceof t.HTMLIFrameElement;){try{var e=typeof l.contentWindow.location.href=="string"}catch{e=!1}if(e)t=l.contentWindow;else break;l=Cn(t.document)}return l}function vi(t){var l=t&&t.nodeName&&t.nodeName.toLowerCase();return l&&(l==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||l==="textarea"||t.contentEditable==="true")}var Bh=Hl&&"documentMode"in document&&11>=document.documentMode,ta=null,gi=null,Za=null,Si=!1;function cs(t,l,e){var a=e.window===e?e.document:e.nodeType===9?e:e.ownerDocument;Si||ta==null||ta!==Cn(a)||(a=ta,"selectionStart"in a&&vi(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),Za&&Qa(Za,a)||(Za=a,a=Eu(gi,"onSelect"),0>=i,n-=i,Nl=1<<32-ul(l)+n|e<F?(et=Y,Y=null):et=Y.sibling;var ft=g(m,Y,y[F],j);if(ft===null){Y===null&&(Y=et);break}t&&Y&&ft.alternate===null&&l(m,Y),r=u(ft,r,F),ct===null?G=ft:ct.sibling=ft,ct=ft,Y=et}if(F===y.length)return e(m,Y),nt&&Yl(m,F),G;if(Y===null){for(;FF?(et=Y,Y=null):et=Y.sibling;var je=g(m,Y,ft.value,j);if(je===null){Y===null&&(Y=et);break}t&&Y&&je.alternate===null&&l(m,Y),r=u(je,r,F),ct===null?G=je:ct.sibling=je,ct=je,Y=et}if(ft.done)return e(m,Y),nt&&Yl(m,F),G;if(Y===null){for(;!ft.done;F++,ft=y.next())ft=T(m,ft.value,j),ft!==null&&(r=u(ft,r,F),ct===null?G=ft:ct.sibling=ft,ct=ft);return nt&&Yl(m,F),G}for(Y=a(Y);!ft.done;F++,ft=y.next())ft=S(Y,m,F,ft.value,j),ft!==null&&(t&&ft.alternate!==null&&Y.delete(ft.key===null?F:ft.key),r=u(ft,r,F),ct===null?G=ft:ct.sibling=ft,ct=ft);return t&&Y.forEach(function(ly){return l(m,ly)}),nt&&Yl(m,F),G}function vt(m,r,y,j){if(typeof y=="object"&&y!==null&&y.type===it&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case Q:t:{for(var G=y.key;r!==null;){if(r.key===G){if(G=y.type,G===it){if(r.tag===7){e(m,r.sibling),j=n(r,y.props.children),j.return=m,m=j;break t}}else if(r.elementType===G||typeof G=="object"&&G!==null&&G.$$typeof===kt&&He(G)===r.type){e(m,r.sibling),j=n(r,y.props),ka(j,y),j.return=m,m=j;break t}e(m,r);break}else l(m,r);r=r.sibling}y.type===it?(j=De(y.props.children,m.mode,j,y.key),j.return=m,m=j):(j=Vn(y.type,y.key,y.props,null,m.mode,j),ka(j,y),j.return=m,m=j)}return i(m);case V:t:{for(G=y.key;r!==null;){if(r.key===G)if(r.tag===4&&r.stateNode.containerInfo===y.containerInfo&&r.stateNode.implementation===y.implementation){e(m,r.sibling),j=n(r,y.children||[]),j.return=m,m=j;break t}else{e(m,r);break}else l(m,r);r=r.sibling}j=Ai(y,m.mode,j),j.return=m,m=j}return i(m);case kt:return y=He(y),vt(m,r,y,j)}if(Tl(y))return H(m,r,y,j);if($t(y)){if(G=$t(y),typeof G!="function")throw Error(h(150));return y=G.call(y),Z(m,r,y,j)}if(typeof y.then=="function")return vt(m,r,Fn(y),j);if(y.$$typeof===X)return vt(m,r,wn(m,y),j);In(m,y)}return typeof y=="string"&&y!==""||typeof y=="number"||typeof y=="bigint"?(y=""+y,r!==null&&r.tag===6?(e(m,r.sibling),j=n(r,y),j.return=m,m=j):(e(m,r),j=zi(y,m.mode,j),j.return=m,m=j),i(m)):e(m,r)}return function(m,r,y,j){try{wa=0;var G=vt(m,r,y,j);return ra=null,G}catch(Y){if(Y===oa||Y===$n)throw Y;var ct=cl(29,Y,null,m.mode);return ct.lanes=j,ct.return=m,ct}finally{}}}var Ye=Ms(!0),Ds=Ms(!1),ue=!1;function qi(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Yi(t,l){t=t.updateQueue,l.updateQueue===t&&(l.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function ie(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function ce(t,l,e){var a=t.updateQueue;if(a===null)return null;if(a=a.shared,(st&2)!==0){var n=a.pending;return n===null?l.next=l:(l.next=n.next,n.next=l),a.pending=l,l=Ln(t),ms(t,null,e),l}return Zn(t,a,l,e),Ln(t)}function $a(t,l,e){if(l=l.updateQueue,l!==null&&(l=l.shared,(e&4194048)!==0)){var a=l.lanes;a&=t.pendingLanes,e|=a,l.lanes=e,jf(t,e)}}function Gi(t,l){var e=t.updateQueue,a=t.alternate;if(a!==null&&(a=a.updateQueue,e===a)){var n=null,u=null;if(e=e.firstBaseUpdate,e!==null){do{var i={lane:e.lane,tag:e.tag,payload:e.payload,callback:null,next:null};u===null?n=u=i:u=u.next=i,e=e.next}while(e!==null);u===null?n=u=l:u=u.next=l}else n=u=l;e={baseState:a.baseState,firstBaseUpdate:n,lastBaseUpdate:u,shared:a.shared,callbacks:a.callbacks},t.updateQueue=e;return}t=e.lastBaseUpdate,t===null?e.firstBaseUpdate=l:t.next=l,e.lastBaseUpdate=l}var Xi=!1;function Wa(){if(Xi){var t=sa;if(t!==null)throw t}}function Fa(t,l,e,a){Xi=!1;var n=t.updateQueue;ue=!1;var u=n.firstBaseUpdate,i=n.lastBaseUpdate,f=n.shared.pending;if(f!==null){n.shared.pending=null;var s=f,v=s.next;s.next=null,i===null?u=v:i.next=v,i=s;var b=t.alternate;b!==null&&(b=b.updateQueue,f=b.lastBaseUpdate,f!==i&&(f===null?b.firstBaseUpdate=v:f.next=v,b.lastBaseUpdate=s))}if(u!==null){var T=n.baseState;i=0,b=v=s=null,f=u;do{var g=f.lane&-536870913,S=g!==f.lane;if(S?(lt&g)===g:(a&g)===g){g!==0&&g===fa&&(Xi=!0),b!==null&&(b=b.next={lane:0,tag:f.tag,payload:f.payload,callback:null,next:null});t:{var H=t,Z=f;g=l;var vt=e;switch(Z.tag){case 1:if(H=Z.payload,typeof H=="function"){T=H.call(vt,T,g);break t}T=H;break t;case 3:H.flags=H.flags&-65537|128;case 0:if(H=Z.payload,g=typeof H=="function"?H.call(vt,T,g):H,g==null)break t;T=D({},T,g);break t;case 2:ue=!0}}g=f.callback,g!==null&&(t.flags|=64,S&&(t.flags|=8192),S=n.callbacks,S===null?n.callbacks=[g]:S.push(g))}else S={lane:g,tag:f.tag,payload:f.payload,callback:f.callback,next:null},b===null?(v=b=S,s=T):b=b.next=S,i|=g;if(f=f.next,f===null){if(f=n.shared.pending,f===null)break;S=f,f=S.next,S.next=null,n.lastBaseUpdate=S,n.shared.pending=null}}while(!0);b===null&&(s=T),n.baseState=s,n.firstBaseUpdate=v,n.lastBaseUpdate=b,u===null&&(n.shared.lanes=0),de|=i,t.lanes=i,t.memoizedState=T}}function Cs(t,l){if(typeof t!="function")throw Error(h(191,t));t.call(l)}function Us(t,l){var e=t.callbacks;if(e!==null)for(t.callbacks=null,t=0;tu?u:8;var i=x.T,f={};x.T=f,uc(t,!1,l,e);try{var s=n(),v=x.S;if(v!==null&&v(f,s),s!==null&&typeof s=="object"&&typeof s.then=="function"){var b=Vh(s,a);tn(t,l,b,dl(t))}else tn(t,l,a,dl(t))}catch(T){tn(t,l,{then:function(){},status:"rejected",reason:T},dl())}finally{C.p=u,i!==null&&f.types!==null&&(i.types=f.types),x.T=i}}function Wh(){}function ac(t,l,e,a){if(t.tag!==5)throw Error(h(476));var n=ro(t).queue;oo(t,n,l,J,e===null?Wh:function(){return ho(t),e(a)})}function ro(t){var l=t.memoizedState;if(l!==null)return l;l={memoizedState:J,baseState:J,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Zl,lastRenderedState:J},next:null};var e={};return l.next={memoizedState:e,baseState:e,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Zl,lastRenderedState:e},next:null},t.memoizedState=l,t=t.alternate,t!==null&&(t.memoizedState=l),l}function ho(t){var l=ro(t);l.next===null&&(l=t.alternate.memoizedState),tn(t,l.next.queue,{},dl())}function nc(){return qt(Sn)}function mo(){return Et().memoizedState}function yo(){return Et().memoizedState}function Fh(t){for(var l=t.return;l!==null;){switch(l.tag){case 24:case 3:var e=dl();t=ie(e);var a=ce(l,t,e);a!==null&&(el(a,l,e),$a(a,l,e)),l={cache:Ui()},t.payload=l;return}l=l.return}}function Ih(t,l,e){var a=dl();e={lane:a,revertLane:0,gesture:null,action:e,hasEagerState:!1,eagerState:null,next:null},fu(t)?go(l,e):(e=ji(t,l,e,a),e!==null&&(el(e,t,a),So(e,l,a)))}function vo(t,l,e){var a=dl();tn(t,l,e,a)}function tn(t,l,e,a){var n={lane:a,revertLane:0,gesture:null,action:e,hasEagerState:!1,eagerState:null,next:null};if(fu(t))go(l,n);else{var u=t.alternate;if(t.lanes===0&&(u===null||u.lanes===0)&&(u=l.lastRenderedReducer,u!==null))try{var i=l.lastRenderedState,f=u(i,e);if(n.hasEagerState=!0,n.eagerState=f,il(f,i))return Zn(t,l,n,0),pt===null&&Qn(),!1}catch{}finally{}if(e=ji(t,l,n,a),e!==null)return el(e,t,a),So(e,l,a),!0}return!1}function uc(t,l,e,a){if(a={lane:2,revertLane:qc(),gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},fu(t)){if(l)throw Error(h(479))}else l=ji(t,e,a,2),l!==null&&el(l,t,2)}function fu(t){var l=t.alternate;return t===W||l!==null&&l===W}function go(t,l){ha=lu=!0;var e=t.pending;e===null?l.next=l:(l.next=e.next,e.next=l),t.pending=l}function So(t,l,e){if((e&4194048)!==0){var a=l.lanes;a&=t.pendingLanes,e|=a,l.lanes=e,jf(t,e)}}var ln={readContext:qt,use:nu,useCallback:Tt,useContext:Tt,useEffect:Tt,useImperativeHandle:Tt,useLayoutEffect:Tt,useInsertionEffect:Tt,useMemo:Tt,useReducer:Tt,useRef:Tt,useState:Tt,useDebugValue:Tt,useDeferredValue:Tt,useTransition:Tt,useSyncExternalStore:Tt,useId:Tt,useHostTransitionStatus:Tt,useFormState:Tt,useActionState:Tt,useOptimistic:Tt,useMemoCache:Tt,useCacheRefresh:Tt};ln.useEffectEvent=Tt;var po={readContext:qt,use:nu,useCallback:function(t,l){return Jt().memoizedState=[t,l===void 0?null:l],t},useContext:qt,useEffect:lo,useImperativeHandle:function(t,l,e){e=e!=null?e.concat([t]):null,iu(4194308,4,uo.bind(null,l,t),e)},useLayoutEffect:function(t,l){return iu(4194308,4,t,l)},useInsertionEffect:function(t,l){iu(4,2,t,l)},useMemo:function(t,l){var e=Jt();l=l===void 0?null:l;var a=t();if(Ge){Il(!0);try{t()}finally{Il(!1)}}return e.memoizedState=[a,l],a},useReducer:function(t,l,e){var a=Jt();if(e!==void 0){var n=e(l);if(Ge){Il(!0);try{e(l)}finally{Il(!1)}}}else n=l;return a.memoizedState=a.baseState=n,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:n},a.queue=t,t=t.dispatch=Ih.bind(null,W,t),[a.memoizedState,t]},useRef:function(t){var l=Jt();return t={current:t},l.memoizedState=t},useState:function(t){t=Ii(t);var l=t.queue,e=vo.bind(null,W,l);return l.dispatch=e,[t.memoizedState,e]},useDebugValue:lc,useDeferredValue:function(t,l){var e=Jt();return ec(e,t,l)},useTransition:function(){var t=Ii(!1);return t=oo.bind(null,W,t.queue,!0,!1),Jt().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,l,e){var a=W,n=Jt();if(nt){if(e===void 0)throw Error(h(407));e=e()}else{if(e=l(),pt===null)throw Error(h(349));(lt&127)!==0||Gs(a,l,e)}n.memoizedState=e;var u={value:e,getSnapshot:l};return n.queue=u,lo(Qs.bind(null,a,u,t),[t]),a.flags|=2048,ya(9,{destroy:void 0},Xs.bind(null,a,u,e,l),null),e},useId:function(){var t=Jt(),l=pt.identifierPrefix;if(nt){var e=Ml,a=Nl;e=(a&~(1<<32-ul(a)-1)).toString(32)+e,l="_"+l+"R_"+e,e=eu++,0<\/script>",u=u.removeChild(u.firstChild);break;case"select":u=typeof a.is=="string"?i.createElement("select",{is:a.is}):i.createElement("select"),a.multiple?u.multiple=!0:a.size&&(u.size=a.size);break;default:u=typeof a.is=="string"?i.createElement(n,{is:a.is}):i.createElement(n)}}u[Bt]=l,u[Wt]=a;t:for(i=l.child;i!==null;){if(i.tag===5||i.tag===6)u.appendChild(i.stateNode);else if(i.tag!==4&&i.tag!==27&&i.child!==null){i.child.return=i,i=i.child;continue}if(i===l)break t;for(;i.sibling===null;){if(i.return===null||i.return===l)break t;i=i.return}i.sibling.return=i.return,i=i.sibling}l.stateNode=u;t:switch(Gt(u,n,a),n){case"button":case"input":case"select":case"textarea":a=!!a.autoFocus;break t;case"img":a=!0;break t;default:a=!1}a&&Vl(l)}}return xt(l),pc(l,l.type,t===null?null:t.memoizedProps,l.pendingProps,e),null;case 6:if(t&&l.stateNode!=null)t.memoizedProps!==a&&Vl(l);else{if(typeof a!="string"&&l.stateNode===null)throw Error(h(166));if(t=I.current,ia(l)){if(t=l.stateNode,e=l.memoizedProps,a=null,n=Ht,n!==null)switch(n.tag){case 27:case 5:a=n.memoizedProps}t[Bt]=l,t=!!(t.nodeValue===e||a!==null&&a.suppressHydrationWarning===!0||Yr(t.nodeValue,e)),t||ae(l,!0)}else t=Ou(t).createTextNode(a),t[Bt]=l,l.stateNode=t}return xt(l),null;case 31:if(e=l.memoizedState,t===null||t.memoizedState!==null){if(a=ia(l),e!==null){if(t===null){if(!a)throw Error(h(318));if(t=l.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(h(557));t[Bt]=l}else Ce(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;xt(l),t=!1}else e=Ni(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=e),t=!0;if(!t)return l.flags&256?(sl(l),l):(sl(l),null);if((l.flags&128)!==0)throw Error(h(558))}return xt(l),null;case 13:if(a=l.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(n=ia(l),a!==null&&a.dehydrated!==null){if(t===null){if(!n)throw Error(h(318));if(n=l.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(h(317));n[Bt]=l}else Ce(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;xt(l),n=!1}else n=Ni(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=n),n=!0;if(!n)return l.flags&256?(sl(l),l):(sl(l),null)}return sl(l),(l.flags&128)!==0?(l.lanes=e,l):(e=a!==null,t=t!==null&&t.memoizedState!==null,e&&(a=l.child,n=null,a.alternate!==null&&a.alternate.memoizedState!==null&&a.alternate.memoizedState.cachePool!==null&&(n=a.alternate.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==n&&(a.flags|=2048)),e!==t&&e&&(l.child.flags|=8192),hu(l,l.updateQueue),xt(l),null);case 4:return At(),t===null&&Qc(l.stateNode.containerInfo),xt(l),null;case 10:return Xl(l.type),xt(l),null;case 19:if(z(_t),a=l.memoizedState,a===null)return xt(l),null;if(n=(l.flags&128)!==0,u=a.rendering,u===null)if(n)an(a,!1);else{if(zt!==0||t!==null&&(t.flags&128)!==0)for(t=l.child;t!==null;){if(u=tu(t),u!==null){for(l.flags|=128,an(a,!1),t=u.updateQueue,l.updateQueue=t,hu(l,t),l.subtreeFlags=0,t=e,e=l.child;e!==null;)ys(e,t),e=e.sibling;return U(_t,_t.current&1|2),nt&&Yl(l,a.treeForkCount),l.child}t=t.sibling}a.tail!==null&&al()>Su&&(l.flags|=128,n=!0,an(a,!1),l.lanes=4194304)}else{if(!n)if(t=tu(u),t!==null){if(l.flags|=128,n=!0,t=t.updateQueue,l.updateQueue=t,hu(l,t),an(a,!0),a.tail===null&&a.tailMode==="hidden"&&!u.alternate&&!nt)return xt(l),null}else 2*al()-a.renderingStartTime>Su&&e!==536870912&&(l.flags|=128,n=!0,an(a,!1),l.lanes=4194304);a.isBackwards?(u.sibling=l.child,l.child=u):(t=a.last,t!==null?t.sibling=u:l.child=u,a.last=u)}return a.tail!==null?(t=a.tail,a.rendering=t,a.tail=t.sibling,a.renderingStartTime=al(),t.sibling=null,e=_t.current,U(_t,n?e&1|2:e&1),nt&&Yl(l,a.treeForkCount),t):(xt(l),null);case 22:case 23:return sl(l),Zi(),a=l.memoizedState!==null,t!==null?t.memoizedState!==null!==a&&(l.flags|=8192):a&&(l.flags|=8192),a?(e&536870912)!==0&&(l.flags&128)===0&&(xt(l),l.subtreeFlags&6&&(l.flags|=8192)):xt(l),e=l.updateQueue,e!==null&&hu(l,e.retryQueue),e=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(e=t.memoizedState.cachePool.pool),a=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(a=l.memoizedState.cachePool.pool),a!==e&&(l.flags|=2048),t!==null&&z(Be),null;case 24:return e=null,t!==null&&(e=t.memoizedState.cache),l.memoizedState.cache!==e&&(l.flags|=2048),Xl(Ot),xt(l),null;case 25:return null;case 30:return null}throw Error(h(156,l.tag))}function am(t,l){switch(Ei(l),l.tag){case 1:return t=l.flags,t&65536?(l.flags=t&-65537|128,l):null;case 3:return Xl(Ot),At(),t=l.flags,(t&65536)!==0&&(t&128)===0?(l.flags=t&-65537|128,l):null;case 26:case 27:case 5:return zn(l),null;case 31:if(l.memoizedState!==null){if(sl(l),l.alternate===null)throw Error(h(340));Ce()}return t=l.flags,t&65536?(l.flags=t&-65537|128,l):null;case 13:if(sl(l),t=l.memoizedState,t!==null&&t.dehydrated!==null){if(l.alternate===null)throw Error(h(340));Ce()}return t=l.flags,t&65536?(l.flags=t&-65537|128,l):null;case 19:return z(_t),null;case 4:return At(),null;case 10:return Xl(l.type),null;case 22:case 23:return sl(l),Zi(),t!==null&&z(Be),t=l.flags,t&65536?(l.flags=t&-65537|128,l):null;case 24:return Xl(Ot),null;case 25:return null;default:return null}}function Lo(t,l){switch(Ei(l),l.tag){case 3:Xl(Ot),At();break;case 26:case 27:case 5:zn(l);break;case 4:At();break;case 31:l.memoizedState!==null&&sl(l);break;case 13:sl(l);break;case 19:z(_t);break;case 10:Xl(l.type);break;case 22:case 23:sl(l),Zi(),t!==null&&z(Be);break;case 24:Xl(Ot)}}function nn(t,l){try{var e=l.updateQueue,a=e!==null?e.lastEffect:null;if(a!==null){var n=a.next;e=n;do{if((e.tag&t)===t){a=void 0;var u=e.create,i=e.inst;a=u(),i.destroy=a}e=e.next}while(e!==n)}}catch(f){dt(l,l.return,f)}}function oe(t,l,e){try{var a=l.updateQueue,n=a!==null?a.lastEffect:null;if(n!==null){var u=n.next;a=u;do{if((a.tag&t)===t){var i=a.inst,f=i.destroy;if(f!==void 0){i.destroy=void 0,n=l;var s=e,v=f;try{v()}catch(b){dt(n,s,b)}}}a=a.next}while(a!==u)}}catch(b){dt(l,l.return,b)}}function Vo(t){var l=t.updateQueue;if(l!==null){var e=t.stateNode;try{Us(l,e)}catch(a){dt(t,t.return,a)}}}function Ko(t,l,e){e.props=Xe(t.type,t.memoizedProps),e.state=t.memoizedState;try{e.componentWillUnmount()}catch(a){dt(t,l,a)}}function un(t,l){try{var e=t.ref;if(e!==null){switch(t.tag){case 26:case 27:case 5:var a=t.stateNode;break;case 30:a=t.stateNode;break;default:a=t.stateNode}typeof e=="function"?t.refCleanup=e(a):e.current=a}}catch(n){dt(t,l,n)}}function Dl(t,l){var e=t.ref,a=t.refCleanup;if(e!==null)if(typeof a=="function")try{a()}catch(n){dt(t,l,n)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof e=="function")try{e(null)}catch(n){dt(t,l,n)}else e.current=null}function Jo(t){var l=t.type,e=t.memoizedProps,a=t.stateNode;try{t:switch(l){case"button":case"input":case"select":case"textarea":e.autoFocus&&a.focus();break t;case"img":e.src?a.src=e.src:e.srcSet&&(a.srcset=e.srcSet)}}catch(n){dt(t,t.return,n)}}function bc(t,l,e){try{var a=t.stateNode;Am(a,t.type,e,l),a[Wt]=l}catch(n){dt(t,t.return,n)}}function wo(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&ge(t.type)||t.tag===4}function xc(t){t:for(;;){for(;t.sibling===null;){if(t.return===null||wo(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&ge(t.type)||t.flags&2||t.child===null||t.tag===4)continue t;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function jc(t,l,e){var a=t.tag;if(a===5||a===6)t=t.stateNode,l?(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e).insertBefore(t,l):(l=e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,l.appendChild(t),e=e._reactRootContainer,e!=null||l.onclick!==null||(l.onclick=Bl));else if(a!==4&&(a===27&&ge(t.type)&&(e=t.stateNode,l=null),t=t.child,t!==null))for(jc(t,l,e),t=t.sibling;t!==null;)jc(t,l,e),t=t.sibling}function mu(t,l,e){var a=t.tag;if(a===5||a===6)t=t.stateNode,l?e.insertBefore(t,l):e.appendChild(t);else if(a!==4&&(a===27&&ge(t.type)&&(e=t.stateNode),t=t.child,t!==null))for(mu(t,l,e),t=t.sibling;t!==null;)mu(t,l,e),t=t.sibling}function ko(t){var l=t.stateNode,e=t.memoizedProps;try{for(var a=t.type,n=l.attributes;n.length;)l.removeAttributeNode(n[0]);Gt(l,a,e),l[Bt]=t,l[Wt]=e}catch(u){dt(t,t.return,u)}}var Kl=!1,Dt=!1,Tc=!1,$o=typeof WeakSet=="function"?WeakSet:Set,Rt=null;function nm(t,l){if(t=t.containerInfo,Vc=Bu,t=is(t),vi(t)){if("selectionStart"in t)var e={start:t.selectionStart,end:t.selectionEnd};else t:{e=(e=t.ownerDocument)&&e.defaultView||window;var a=e.getSelection&&e.getSelection();if(a&&a.rangeCount!==0){e=a.anchorNode;var n=a.anchorOffset,u=a.focusNode;a=a.focusOffset;try{e.nodeType,u.nodeType}catch{e=null;break t}var i=0,f=-1,s=-1,v=0,b=0,T=t,g=null;l:for(;;){for(var S;T!==e||n!==0&&T.nodeType!==3||(f=i+n),T!==u||a!==0&&T.nodeType!==3||(s=i+a),T.nodeType===3&&(i+=T.nodeValue.length),(S=T.firstChild)!==null;)g=T,T=S;for(;;){if(T===t)break l;if(g===e&&++v===n&&(f=i),g===u&&++b===a&&(s=i),(S=T.nextSibling)!==null)break;T=g,g=T.parentNode}T=S}e=f===-1||s===-1?null:{start:f,end:s}}else e=null}e=e||{start:0,end:0}}else e=null;for(Kc={focusedElem:t,selectionRange:e},Bu=!1,Rt=l;Rt!==null;)if(l=Rt,t=l.child,(l.subtreeFlags&1028)!==0&&t!==null)t.return=l,Rt=t;else for(;Rt!==null;){switch(l=Rt,u=l.alternate,t=l.flags,l.tag){case 0:if((t&4)!==0&&(t=l.updateQueue,t=t!==null?t.events:null,t!==null))for(e=0;e title"))),Gt(u,a,e),u[Bt]=t,Ut(u),a=u;break t;case"link":var i=ld("link","href",n).get(a+(e.href||""));if(i){for(var f=0;fvt&&(i=vt,vt=Z,Z=i);var m=ns(f,Z),r=ns(f,vt);if(m&&r&&(S.rangeCount!==1||S.anchorNode!==m.node||S.anchorOffset!==m.offset||S.focusNode!==r.node||S.focusOffset!==r.offset)){var y=T.createRange();y.setStart(m.node,m.offset),S.removeAllRanges(),Z>vt?(S.addRange(y),S.extend(r.node,r.offset)):(y.setEnd(r.node,r.offset),S.addRange(y))}}}}for(T=[],S=f;S=S.parentNode;)S.nodeType===1&&T.push({element:S,left:S.scrollLeft,top:S.scrollTop});for(typeof f.focus=="function"&&f.focus(),f=0;fe?32:e,x.T=null,e=Mc,Mc=null;var u=me,i=Wl;if(Ct=0,ba=me=null,Wl=0,(st&6)!==0)throw Error(h(331));var f=st;if(st|=4,ir(u.current),ar(u,u.current,i,e),st=f,dn(0,!1),nl&&typeof nl.onPostCommitFiberRoot=="function")try{nl.onPostCommitFiberRoot(Na,u)}catch{}return!0}finally{C.p=n,x.T=a,zr(t,l)}}function _r(t,l,e){l=vl(e,l),l=sc(t.stateNode,l,2),t=ce(t,l,2),t!==null&&(Da(t,2),Cl(t))}function dt(t,l,e){if(t.tag===3)_r(t,t,e);else for(;l!==null;){if(l.tag===3){_r(l,t,e);break}else if(l.tag===1){var a=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof a.componentDidCatch=="function"&&(he===null||!he.has(a))){t=vl(e,t),e=Eo(2),a=ce(l,e,2),a!==null&&(Oo(e,a,l,t),Da(a,2),Cl(a));break}}l=l.return}}function Rc(t,l,e){var a=t.pingCache;if(a===null){a=t.pingCache=new cm;var n=new Set;a.set(l,n)}else n=a.get(l),n===void 0&&(n=new Set,a.set(l,n));n.has(e)||(_c=!0,n.add(e),t=dm.bind(null,t,l,e),l.then(t,t))}function dm(t,l,e){var a=t.pingCache;a!==null&&a.delete(l),t.pingedLanes|=t.suspendedLanes&e,t.warmLanes&=~e,pt===t&&(lt&e)===e&&(zt===4||zt===3&&(lt&62914560)===lt&&300>al()-gu?(st&2)===0&&xa(t,0):Ec|=e,pa===lt&&(pa=0)),Cl(t)}function Er(t,l){l===0&&(l=bf()),t=Me(t,l),t!==null&&(Da(t,l),Cl(t))}function hm(t){var l=t.memoizedState,e=0;l!==null&&(e=l.retryLane),Er(t,e)}function mm(t,l){var e=0;switch(t.tag){case 31:case 13:var a=t.stateNode,n=t.memoizedState;n!==null&&(e=n.retryLane);break;case 19:a=t.stateNode;break;case 22:a=t.stateNode._retryCache;break;default:throw Error(h(314))}a!==null&&a.delete(l),Er(t,e)}function ym(t,l){return wu(t,l)}var zu=null,Ta=null,Bc=!1,Au=!1,Hc=!1,ve=0;function Cl(t){t!==Ta&&t.next===null&&(Ta===null?zu=Ta=t:Ta=Ta.next=t),Au=!0,Bc||(Bc=!0,gm())}function dn(t,l){if(!Hc&&Au){Hc=!0;do for(var e=!1,a=zu;a!==null;){if(t!==0){var n=a.pendingLanes;if(n===0)var u=0;else{var i=a.suspendedLanes,f=a.pingedLanes;u=(1<<31-ul(42|t)+1)-1,u&=n&~(i&~f),u=u&201326741?u&201326741|1:u?u|2:0}u!==0&&(e=!0,Dr(a,u))}else u=lt,u=Nn(a,a===pt?u:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),(u&3)===0||Ma(a,u)||(e=!0,Dr(a,u));a=a.next}while(e);Hc=!1}}function vm(){Or()}function Or(){Au=Bc=!1;var t=0;ve!==0&&Em()&&(t=ve);for(var l=al(),e=null,a=zu;a!==null;){var n=a.next,u=Nr(a,l);u===0?(a.next=null,e===null?zu=n:e.next=n,n===null&&(Ta=e)):(e=a,(t!==0||(u&3)!==0)&&(Au=!0)),a=n}Ct!==0&&Ct!==5||dn(t),ve!==0&&(ve=0)}function Nr(t,l){for(var e=t.suspendedLanes,a=t.pingedLanes,n=t.expirationTimes,u=t.pendingLanes&-62914561;0f)break;var b=s.transferSize,T=s.initiatorType;b&&Gr(T)&&(s=s.responseEnd,i+=b*(s"u"?null:document;function Fr(t,l,e){var a=za;if(a&&typeof l=="string"&&l){var n=ml(l);n='link[rel="'+t+'"][href="'+n+'"]',typeof e=="string"&&(n+='[crossorigin="'+e+'"]'),Wr.has(n)||(Wr.add(n),t={rel:t,crossOrigin:e,href:l},a.querySelector(n)===null&&(l=a.createElement("link"),Gt(l,"link",t),Ut(l),a.head.appendChild(l)))}}function Hm(t){Fl.D(t),Fr("dns-prefetch",t,null)}function qm(t,l){Fl.C(t,l),Fr("preconnect",t,l)}function Ym(t,l,e){Fl.L(t,l,e);var a=za;if(a&&t&&l){var n='link[rel="preload"][as="'+ml(l)+'"]';l==="image"&&e&&e.imageSrcSet?(n+='[imagesrcset="'+ml(e.imageSrcSet)+'"]',typeof e.imageSizes=="string"&&(n+='[imagesizes="'+ml(e.imageSizes)+'"]')):n+='[href="'+ml(t)+'"]';var u=n;switch(l){case"style":u=Aa(t);break;case"script":u=_a(t)}jl.has(u)||(t=D({rel:"preload",href:l==="image"&&e&&e.imageSrcSet?void 0:t,as:l},e),jl.set(u,t),a.querySelector(n)!==null||l==="style"&&a.querySelector(vn(u))||l==="script"&&a.querySelector(gn(u))||(l=a.createElement("link"),Gt(l,"link",t),Ut(l),a.head.appendChild(l)))}}function Gm(t,l){Fl.m(t,l);var e=za;if(e&&t){var a=l&&typeof l.as=="string"?l.as:"script",n='link[rel="modulepreload"][as="'+ml(a)+'"][href="'+ml(t)+'"]',u=n;switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":u=_a(t)}if(!jl.has(u)&&(t=D({rel:"modulepreload",href:t},l),jl.set(u,t),e.querySelector(n)===null)){switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(e.querySelector(gn(u)))return}a=e.createElement("link"),Gt(a,"link",t),Ut(a),e.head.appendChild(a)}}}function Xm(t,l,e){Fl.S(t,l,e);var a=za;if(a&&t){var n=we(a).hoistableStyles,u=Aa(t);l=l||"default";var i=n.get(u);if(!i){var f={loading:0,preload:null};if(i=a.querySelector(vn(u)))f.loading=5;else{t=D({rel:"stylesheet",href:t,"data-precedence":l},e),(e=jl.get(u))&&Ic(t,e);var s=i=a.createElement("link");Ut(s),Gt(s,"link",t),s._p=new Promise(function(v,b){s.onload=v,s.onerror=b}),s.addEventListener("load",function(){f.loading|=1}),s.addEventListener("error",function(){f.loading|=2}),f.loading|=4,Mu(i,l,a)}i={type:"stylesheet",instance:i,count:1,state:f},n.set(u,i)}}}function Qm(t,l){Fl.X(t,l);var e=za;if(e&&t){var a=we(e).hoistableScripts,n=_a(t),u=a.get(n);u||(u=e.querySelector(gn(n)),u||(t=D({src:t,async:!0},l),(l=jl.get(n))&&Pc(t,l),u=e.createElement("script"),Ut(u),Gt(u,"link",t),e.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},a.set(n,u))}}function Zm(t,l){Fl.M(t,l);var e=za;if(e&&t){var a=we(e).hoistableScripts,n=_a(t),u=a.get(n);u||(u=e.querySelector(gn(n)),u||(t=D({src:t,async:!0,type:"module"},l),(l=jl.get(n))&&Pc(t,l),u=e.createElement("script"),Ut(u),Gt(u,"link",t),e.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},a.set(n,u))}}function Ir(t,l,e,a){var n=(n=I.current)?Nu(n):null;if(!n)throw Error(h(446));switch(t){case"meta":case"title":return null;case"style":return typeof e.precedence=="string"&&typeof e.href=="string"?(l=Aa(e.href),e=we(n).hoistableStyles,a=e.get(l),a||(a={type:"style",instance:null,count:0,state:null},e.set(l,a)),a):{type:"void",instance:null,count:0,state:null};case"link":if(e.rel==="stylesheet"&&typeof e.href=="string"&&typeof e.precedence=="string"){t=Aa(e.href);var u=we(n).hoistableStyles,i=u.get(t);if(i||(n=n.ownerDocument||n,i={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},u.set(t,i),(u=n.querySelector(vn(t)))&&!u._p&&(i.instance=u,i.state.loading=5),jl.has(t)||(e={rel:"preload",as:"style",href:e.href,crossOrigin:e.crossOrigin,integrity:e.integrity,media:e.media,hrefLang:e.hrefLang,referrerPolicy:e.referrerPolicy},jl.set(t,e),u||Lm(n,t,e,i.state))),l&&a===null)throw Error(h(528,""));return i}if(l&&a!==null)throw Error(h(529,""));return null;case"script":return l=e.async,e=e.src,typeof e=="string"&&l&&typeof l!="function"&&typeof l!="symbol"?(l=_a(e),e=we(n).hoistableScripts,a=e.get(l),a||(a={type:"script",instance:null,count:0,state:null},e.set(l,a)),a):{type:"void",instance:null,count:0,state:null};default:throw Error(h(444,t))}}function Aa(t){return'href="'+ml(t)+'"'}function vn(t){return'link[rel="stylesheet"]['+t+"]"}function Pr(t){return D({},t,{"data-precedence":t.precedence,precedence:null})}function Lm(t,l,e,a){t.querySelector('link[rel="preload"][as="style"]['+l+"]")?a.loading=1:(l=t.createElement("link"),a.preload=l,l.addEventListener("load",function(){return a.loading|=1}),l.addEventListener("error",function(){return a.loading|=2}),Gt(l,"link",e),Ut(l),t.head.appendChild(l))}function _a(t){return'[src="'+ml(t)+'"]'}function gn(t){return"script[async]"+t}function td(t,l,e){if(l.count++,l.instance===null)switch(l.type){case"style":var a=t.querySelector('style[data-href~="'+ml(e.href)+'"]');if(a)return l.instance=a,Ut(a),a;var n=D({},e,{"data-href":e.href,"data-precedence":e.precedence,href:null,precedence:null});return a=(t.ownerDocument||t).createElement("style"),Ut(a),Gt(a,"style",n),Mu(a,e.precedence,t),l.instance=a;case"stylesheet":n=Aa(e.href);var u=t.querySelector(vn(n));if(u)return l.state.loading|=4,l.instance=u,Ut(u),u;a=Pr(e),(n=jl.get(n))&&Ic(a,n),u=(t.ownerDocument||t).createElement("link"),Ut(u);var i=u;return i._p=new Promise(function(f,s){i.onload=f,i.onerror=s}),Gt(u,"link",a),l.state.loading|=4,Mu(u,e.precedence,t),l.instance=u;case"script":return u=_a(e.src),(n=t.querySelector(gn(u)))?(l.instance=n,Ut(n),n):(a=e,(n=jl.get(u))&&(a=D({},e),Pc(a,n)),t=t.ownerDocument||t,n=t.createElement("script"),Ut(n),Gt(n,"link",a),t.head.appendChild(n),l.instance=n);case"void":return null;default:throw Error(h(443,l.type))}else l.type==="stylesheet"&&(l.state.loading&4)===0&&(a=l.instance,l.state.loading|=4,Mu(a,e.precedence,t));return l.instance}function Mu(t,l,e){for(var a=e.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),n=a.length?a[a.length-1]:null,u=n,i=0;i title"):null)}function Vm(t,l,e){if(e===1||l.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof l.precedence!="string"||typeof l.href!="string"||l.href==="")break;return!0;case"link":if(typeof l.rel!="string"||typeof l.href!="string"||l.href===""||l.onLoad||l.onError)break;switch(l.rel){case"stylesheet":return t=l.disabled,typeof l.precedence=="string"&&t==null;default:return!0}case"script":if(l.async&&typeof l.async!="function"&&typeof l.async!="symbol"&&!l.onLoad&&!l.onError&&l.src&&typeof l.src=="string")return!0}return!1}function ad(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function Km(t,l,e,a){if(e.type==="stylesheet"&&(typeof a.media!="string"||matchMedia(a.media).matches!==!1)&&(e.state.loading&4)===0){if(e.instance===null){var n=Aa(a.href),u=l.querySelector(vn(n));if(u){l=u._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(t.count++,t=Cu.bind(t),l.then(t,t)),e.state.loading|=4,e.instance=u,Ut(u);return}u=l.ownerDocument||l,a=Pr(a),(n=jl.get(n))&&Ic(a,n),u=u.createElement("link"),Ut(u);var i=u;i._p=new Promise(function(f,s){i.onload=f,i.onerror=s}),Gt(u,"link",a),e.instance=u}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(e,l),(l=e.state.preload)&&(e.state.loading&3)===0&&(t.count++,e=Cu.bind(t),l.addEventListener("load",e),l.addEventListener("error",e))}}var tf=0;function Jm(t,l){return t.stylesheets&&t.count===0&&Ru(t,t.stylesheets),0tf?50:800)+l);return t.unsuspend=e,function(){t.unsuspend=null,clearTimeout(a),clearTimeout(n)}}:null}function Cu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Ru(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Uu=null;function Ru(t,l){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Uu=new Map,l.forEach(wm,t),Uu=null,Cu.call(t))}function wm(t,l){if(!(l.state.loading&4)){var e=Uu.get(t);if(e)var a=e.get(null);else{e=new Map,Uu.set(t,e);for(var n=t.querySelectorAll("link[data-precedence],style[data-precedence]"),u=0;u"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(M){console.error(M)}}return o(),of.exports=sy(),of.exports}var ry=oy();const dy=Md(ry),Cd="";async function wt(o,M){const E=await fetch(`${Cd}${o}`,{...M,credentials:"same-origin",headers:{"Content-Type":"application/json",...M==null?void 0:M.headers}});if(E.status===401)throw window.location.hash="#login",new Error("Unauthorized");if(!E.ok){const h=await E.json().catch(()=>({}));throw new Error(h.error||`HTTP ${E.status}`)}return E.json()}async function hy(o){const M=await fetch(`${Cd}${o}`,{credentials:"same-origin"});if(M.status===401)throw window.location.hash="#login",new Error("Unauthorized");if(!M.ok)throw new Error(`HTTP ${M.status}`);return M.text()}const Lt={login:o=>wt("/admin/login",{method:"POST",body:JSON.stringify({token:o})}),signOutEverywhere:()=>wt("/admin/api/sign-out-everywhere",{method:"POST"}),stats:()=>wt("/admin/api/stats"),health:()=>wt("/admin/api/health-indicators"),agents:()=>wt("/admin/api/agents"),sources:()=>wt("/admin/api/sources"),requests:(o=1,M="")=>wt(`/admin/api/requests?page=${o}${M}`),apiKeys:()=>wt("/admin/api/api-keys"),createApiKey(o){return wt("/admin/api/api-keys",{method:"POST",body:JSON.stringify({name:o})})},revokeApiKey(o){return wt("/admin/api/api-keys/revoke",{method:"POST",body:JSON.stringify({name:o})})},updateClientTtl:(o,M)=>wt("/admin/api/update-client-ttl",{method:"POST",body:JSON.stringify({clientId:o,tokenTtl:M})}),rescopeClient:(o,M,E)=>wt("/admin/api/rescope-client",{method:"POST",body:JSON.stringify({clientId:o,sourceId:M,federatedRead:E})}),revokeClient:o=>wt("/admin/api/revoke-client",{method:"POST",body:JSON.stringify({clientId:o})}),calibrationProfile:o=>wt(`/admin/api/calibration/profile${o?`?holder=${encodeURIComponent(o)}`:""}`),calibrationChart:(o,M)=>hy(`/admin/api/calibration/charts/${encodeURIComponent(o)}${M?`?holder=${encodeURIComponent(M)}`:""}`),jobsWatch:()=>wt("/admin/api/jobs/watch")};function my({onLogin:o}){const[M,E]=L.useState(""),[h,N]=L.useState(""),[_,R]=L.useState(!1),K=async A=>{A.preventDefault(),N(""),R(!0);try{await Lt.login(M),E(""),o()}catch{N("Invalid token.")}finally{R(!1)}};return c.jsx("div",{className:"login-page",children:c.jsxs("div",{className:"login-box",children:[c.jsx("div",{className:"login-logo",children:"GBrain"}),c.jsxs("div",{style:{background:"rgba(136, 170, 255, 0.08)",border:"1px solid rgba(136, 170, 255, 0.2)",borderRadius:8,padding:"14px 16px",marginBottom:20,fontSize:13,lineHeight:1.5,color:"var(--text-secondary)"},children:[c.jsx("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:6},children:"🔒 This is a protected dashboard"}),"Ask your AI agent for the admin login link:",c.jsx("div",{style:{background:"rgba(0,0,0,0.3)",borderRadius:6,padding:"8px 12px",marginTop:8,fontFamily:"var(--font-mono)",fontSize:12,color:"#88aaff",wordBreak:"break-all"},children:'"Give me the GBrain admin login link"'}),c.jsx("div",{style:{marginTop:8,fontSize:12,color:"var(--text-muted)"},children:"Each link is single-use. Your agent generates a fresh one each time."})]}),c.jsxs("details",{style:{marginBottom:16},children:[c.jsx("summary",{style:{cursor:"pointer",fontSize:13,color:"var(--text-muted)"},children:"Or paste bootstrap token manually"}),c.jsxs("form",{onSubmit:K,style:{marginTop:12},children:[c.jsx("div",{style:{marginBottom:12},children:c.jsx("input",{type:"password",placeholder:"Admin Token",value:M,onChange:A=>E(A.target.value)})}),c.jsx("button",{className:"btn btn-primary",style:{width:"100%"},disabled:_,children:_?"Authenticating...":"Submit"}),h&&c.jsx("div",{className:"login-error",children:h})]})]})]})})}function yy(){const[o,M]=L.useState({connected_agents:0,requests_today:0,active_tokens:0}),[E,h]=L.useState({expiring_soon:0,error_rate:"0%"}),[N,_]=L.useState([]),[R,K]=L.useState("connecting"),A=L.useRef(null);L.useEffect(()=>{Lt.stats().then(M).catch(()=>{}),Lt.health().then(h).catch(()=>{});const B=new EventSource("/admin/events",{withCredentials:!0});A.current=B,B.onopen=()=>K("connected"),B.onmessage=O=>{try{const Q=JSON.parse(O.data);_(V=>[Q,...V].slice(0,50))}catch{}},B.onerror=()=>{K("disconnected"),setTimeout(()=>{K("connecting"),B.close()},3e3)};const D=setInterval(()=>{Lt.stats().then(M).catch(()=>{}),Lt.health().then(h).catch(()=>{})},3e4);return()=>{B.close(),clearInterval(D)}},[]);const p=B=>{const D=Date.now()-new Date(B).getTime();return D<6e4?`${Math.floor(D/1e3)}s ago`:D<36e5?`${Math.floor(D/6e4)} min ago`:`${Math.floor(D/36e5)}h ago`};return c.jsxs(c.Fragment,{children:[c.jsx("h1",{className:"page-title",children:"Dashboard"}),c.jsxs("div",{style:{display:"flex",gap:24},children:[c.jsxs("div",{style:{flex:1},children:[c.jsxs("div",{className:"metrics",children:[c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:o.connected_agents}),c.jsx("div",{className:"metric-label",children:"Connected Agents"})]}),c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:o.requests_today}),c.jsx("div",{className:"metric-label",children:"Requests Today"})]}),c.jsxs("div",{className:"metric",children:[c.jsx("div",{className:"metric-value",children:o.active_tokens}),c.jsx("div",{className:"metric-label",children:"Active Tokens"})]})]}),c.jsxs("h2",{className:"section-title",children:["Live Activity",c.jsx("span",{style:{marginLeft:8,fontSize:10,color:R==="connected"?"var(--success)":R==="connecting"?"var(--warning)":"var(--error)"},children:R==="connected"?"● connected":R==="connecting"?"● connecting...":"● disconnected"})]}),c.jsx("div",{className:"feed",children:N.length===0?c.jsx("div",{className:"feed-empty",children:R==="connected"?"No requests yet. Agents will appear when they connect.":"Connecting..."}):c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Agent"}),c.jsx("th",{children:"Operation"}),c.jsx("th",{children:"Scopes"}),c.jsx("th",{children:"Latency"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Time"})]})}),c.jsx("tbody",{children:N.map((B,D)=>c.jsxs("tr",{children:[c.jsx("td",{className:"mono",children:B.agent}),c.jsx("td",{className:"mono",children:B.operation}),c.jsx("td",{children:B.scopes.split(",").map(O=>c.jsx("span",{className:`badge badge-${O.trim()}`,style:{marginRight:4},children:O.trim()},O))}),c.jsxs("td",{className:"mono",children:[B.latency_ms," ms"]}),c.jsx("td",{children:c.jsx("span",{className:`badge badge-${B.status}`,children:B.status})}),c.jsx("td",{style:{color:"var(--text-secondary)"},children:p(B.timestamp)})]},D))})]})})]}),c.jsxs("div",{style:{width:220},children:[c.jsx("h2",{className:"section-title",children:"Token Health"}),c.jsxs("div",{className:"health-panel",children:[c.jsxs("div",{className:"health-row",children:[c.jsx("span",{style:{color:"var(--warning)"},children:"Expiring Soon"}),c.jsx("span",{className:"mono",children:E.expiring_soon})]}),c.jsxs("div",{className:"health-row",children:[c.jsx("span",{style:{color:"var(--error)"},children:"Error Rate"}),c.jsx("span",{className:"mono",children:E.error_rate})]})]})]})]})]})}const Ed=["admin","agent","read","sources_admin","users_admin","write"];function vy(o){const M=Math.floor((Date.now()-o.getTime())/1e3);return M<60?"just now":M<3600?`${Math.floor(M/60)}m ago`:M<86400?`${Math.floor(M/3600)}h ago`:`${Math.floor(M/86400)}d ago`}function gy(){const[o,M]=L.useState([]),[E,h]=L.useState([]),[N,_]=L.useState(!0),[R,K]=L.useState(!1),[A,p]=L.useState(null),[B,D]=L.useState(!1),[O,Q]=L.useState(null),[V,it]=L.useState(null);L.useEffect(()=>{gt(),Lt.sources().then(h).catch(()=>{})},[]);const gt=()=>{Lt.agents().then(M).catch(()=>{})};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[c.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Agents"}),c.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[c.jsxs("label",{style:{fontSize:13,color:"var(--text-secondary)",display:"flex",alignItems:"center",gap:6,cursor:"pointer"},children:[c.jsx("input",{type:"checkbox",checked:N,onChange:ut=>_(ut.target.checked)})," Hide revoked"]}),c.jsx("button",{className:"btn btn-secondary",onClick:()=>D(!0),children:"+ API Key"}),c.jsx("button",{className:"btn btn-primary",onClick:()=>K(!0),children:"+ OAuth Client"})]})]}),(()=>{const ut=o.filter(w=>!N||w.status!=="revoked");return o.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No agents registered. Register your first agent to get started."}):ut.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:'All agents are revoked. Uncheck "Hide revoked" to view them.'}):c.jsxs(c.Fragment,{children:[c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Name"}),c.jsx("th",{children:"Type"}),c.jsx("th",{children:"Scopes"}),c.jsx("th",{children:"Sources"}),c.jsx("th",{children:"Status"}),c.jsx("th",{children:"Requests"}),c.jsx("th",{children:"Last Used"})]})}),c.jsx("tbody",{children:ut.map(w=>c.jsxs("tr",{onClick:()=>it(w),style:{cursor:"pointer"},children:[c.jsx("td",{style:{fontWeight:500},children:w.name||w.client_name}),c.jsx("td",{children:c.jsx("span",{className:`badge ${w.auth_type==="oauth"?"badge-read":"badge-write"}`,style:{fontSize:11},children:w.auth_type==="oauth"?"OAuth":"API Key"})}),c.jsx("td",{children:(w.scope||"").split(" ").filter(Boolean).map(X=>c.jsx("span",{className:`badge badge-${X}`,style:{marginRight:4},children:X},X))}),c.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12},children:w.auth_type==="oauth"?`${w.source_id||"none"} · ${(w.federated_read||[]).length} readable`:"Unscoped"}),c.jsx("td",{children:c.jsx("span",{className:`badge ${w.status==="active"?"badge-success":"badge-danger"}`,children:w.status})}),c.jsxs("td",{children:[c.jsx("span",{style:{fontWeight:500},children:w.requests_today||0}),c.jsxs("span",{style:{color:"var(--text-muted)",fontSize:12},children:[" / ",w.total_requests||0]})]}),c.jsx("td",{style:{color:"var(--text-secondary)"},children:w.last_used_at?vy(new Date(w.last_used_at)):"Never"})]},w.id))})]}),c.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginTop:12},children:[o.filter(w=>w.status==="active").length," active / ",o.length," total"]})]})})(),R&&c.jsx(by,{onClose:()=>K(!1),onRegistered:ut=>{K(!1),p(ut),gt()}}),A&&c.jsx(xy,{credentials:A,onClose:()=>p(null)}),V&&c.jsx(Ty,{agent:V,sources:E,onClose:()=>it(null),onRevoked:gt,onRescoped:({sourceId:ut,federatedRead:w})=>{it(X=>X&&{...X,source_id:ut,federated_read:w}),gt()}},V.id),B&&c.jsx(Sy,{onClose:()=>D(!1),onCreated:ut=>{D(!1),Q(ut),gt()}}),O&&c.jsx(py,{token:O,onClose:()=>Q(null)})]})}function Sy({onClose:o,onCreated:M}){const[E,h]=L.useState(""),[N,_]=L.useState(!1),[R,K]=L.useState(""),A=async p=>{if(p.preventDefault(),!E.trim()){K("Name required");return}_(!0);try{const B=await Lt.createApiKey(E.trim());M({name:B.name,token:B.token})}catch(B){K(B instanceof Error?B.message:"Failed")}finally{_(!1)}};return c.jsx("div",{className:"modal-overlay",onClick:o,children:c.jsxs("form",{className:"modal",onClick:p=>p.stopPropagation(),onSubmit:A,children:[c.jsx("div",{className:"modal-title",children:"Create API Key"}),c.jsx("p",{style:{color:"var(--text-secondary)",fontSize:13,marginBottom:16},children:"API keys use simple bearer token auth. They grant full read+write+admin access. For scoped access, use OAuth clients instead."}),c.jsxs("div",{style:{marginBottom:16},children:[c.jsx("label",{children:"Key Name"}),c.jsx("input",{placeholder:"e.g. claude-code-local",value:E,onChange:p=>h(p.target.value),autoFocus:!0})]}),R&&c.jsx("div",{style:{color:"var(--error)",fontSize:13,marginBottom:12},children:R}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end"},children:[c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:o,children:"Cancel"}),c.jsx("button",{type:"submit",className:"btn btn-primary",disabled:N,children:N?"Creating...":"Create Key"})]})]})})}function py({token:o,onClose:M}){const E=h=>navigator.clipboard.writeText(h);return c.jsx("div",{className:"modal-overlay",children:c.jsxs("div",{className:"modal",style:{maxWidth:560},children:[c.jsxs("div",{style:{textAlign:"center",marginBottom:16},children:[c.jsx("div",{style:{fontSize:36,color:"var(--success)",marginBottom:8},children:"✓"}),c.jsx("div",{style:{fontSize:20,fontWeight:600},children:"API Key Created"})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Name"}),c.jsx("div",{className:"code-block",children:c.jsx("span",{children:o.name})})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Bearer Token"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:o.token}),c.jsx("button",{className:"copy-btn",onClick:()=>E(o.token),children:"Copy"})]})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Usage"}),c.jsxs("div",{className:"code-block",children:[c.jsx("pre",{style:{whiteSpace:"pre-wrap",margin:0,fontSize:12},children:`Authorization: Bearer ${o.token}`}),c.jsx("button",{className:"copy-btn",onClick:()=>E(`Authorization: Bearer ${o.token}`),children:"Copy"})]})]}),c.jsx("div",{className:"warning-bar",children:"Save this token now. It will not be shown again."}),c.jsx("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:c.jsx("button",{className:"btn btn-primary",onClick:M,children:"Done"})})]})})}function by({onClose:o,onRegistered:M}){const[E,h]=L.useState(""),[N,_]=L.useState(()=>Object.fromEntries(Ed.map(V=>[V,V==="read"]))),[R,K]=L.useState("86400"),[A,p]=L.useState(!1),[B,D]=L.useState(""),O=[{label:"1 hour",value:"3600"},{label:"24 hours",value:"86400"},{label:"7 days",value:"604800"},{label:"30 days",value:"2592000"},{label:"1 year",value:"31536000"},{label:"No expiry",value:"0"}],Q=async V=>{if(V.preventDefault(),!E.trim()){D("Name required");return}p(!0),D("");try{const it=Object.entries(N).filter(([,w])=>w).map(([w])=>w).join(" "),gt=await fetch("/admin/api/register-client",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:E.trim(),scopes:it,tokenTtl:R==="0"?31536e4:Number(R)})});if(!gt.ok)throw new Error("Registration failed");const ut=await gt.json();M({clientId:ut.clientId,clientSecret:ut.clientSecret,name:E.trim()})}catch(it){D(it instanceof Error?it.message:"Registration failed")}finally{p(!1)}};return c.jsx("div",{className:"modal-overlay",onClick:o,children:c.jsxs("form",{className:"modal",onClick:V=>V.stopPropagation(),onSubmit:Q,children:[c.jsx("div",{className:"modal-title",children:"Register Agent"}),c.jsxs("div",{style:{marginBottom:16},children:[c.jsx("label",{children:"Agent Name"}),c.jsx("input",{placeholder:"e.g. perplexity-production",value:E,onChange:V=>h(V.target.value),autoFocus:!0})]}),c.jsxs("div",{style:{marginBottom:16},children:[c.jsx("label",{children:"Scopes"}),c.jsx("div",{className:"checkbox-group",children:Ed.map(V=>c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:N[V],onChange:it=>_(gt=>({...gt,[V]:it.target.checked}))}),V]},V))})]}),c.jsxs("div",{style:{marginBottom:20},children:[c.jsx("label",{children:"Token Lifetime"}),c.jsx("select",{value:R,onChange:V=>K(V.target.value),style:{width:"100%",background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)",borderRadius:6,padding:"6px 10px",fontSize:14},children:O.map(V=>c.jsx("option",{value:V.value,children:V.label},V.value))})]}),B&&c.jsx("div",{style:{color:"var(--error)",fontSize:13,marginBottom:12},children:B}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end"},children:[c.jsx("button",{type:"button",className:"btn btn-secondary",onClick:o,children:"Cancel"}),c.jsx("button",{type:"submit",className:"btn btn-primary",disabled:A,children:A?"Registering...":"Register"})]})]})})}function xy({credentials:o,onClose:M}){const E=N=>navigator.clipboard.writeText(N),h=()=>{const N=new Blob([JSON.stringify(o,null,2)],{type:"application/json"}),_=URL.createObjectURL(N),R=document.createElement("a");R.href=_,R.download=`${o.name}-credentials.json`,R.click(),URL.revokeObjectURL(_)};return c.jsx("div",{className:"modal-overlay",children:c.jsxs("div",{className:"modal",style:{maxWidth:560},children:[c.jsxs("div",{style:{textAlign:"center",marginBottom:16},children:[c.jsx("div",{style:{fontSize:36,color:"var(--success)",marginBottom:8},children:"✓"}),c.jsx("div",{style:{fontSize:20,fontWeight:600},children:"Agent Registered"})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Client ID"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:o.clientId}),c.jsx("button",{className:"copy-btn",onClick:()=>E(o.clientId),children:"Copy"})]})]}),c.jsxs("div",{style:{marginBottom:12},children:[c.jsx("label",{style:{fontSize:12},children:"Client Secret"}),c.jsxs("div",{className:"code-block",children:[c.jsx("span",{children:o.clientSecret}),c.jsx("button",{className:"copy-btn",onClick:()=>E(o.clientSecret),children:"Copy"})]})]}),c.jsx("div",{className:"warning-bar",children:"Save this secret now. It will not be shown again."}),c.jsxs("div",{style:{display:"flex",gap:12,justifyContent:"flex-end",marginTop:20},children:[c.jsx("button",{className:"btn btn-secondary",onClick:h,children:"Download as JSON"}),c.jsx("button",{className:"btn btn-primary",onClick:M,children:"Done"})]})]})})}function jy({clientId:o,agent:M,sources:E,onRescoped:h}){const[N,_]=L.useState(M.source_id||"default"),[R,K]=L.useState(M.federated_read||[]),[A,p]=L.useState(!1),[B,D]=L.useState(""),[O,Q]=L.useState(!1),V=new Set(R),it=new Set(E.map(X=>X.id)),gt=R.filter(X=>!it.has(X)),ut=!it.has(N),w=async()=>{if(R.length===0){D("Select at least one readable source.");return}p(!0),D(""),Q(!1);try{const X=await Lt.rescopeClient(o,N,R);_(X.sourceId),K(X.federatedRead),Q(!0),h(X)}catch(X){D(X instanceof Error?X.message:"Failed to save source access")}finally{p(!1)}};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"section-title",children:"Source Access"}),c.jsx("div",{style:{color:"var(--text-secondary)",fontSize:12,lineHeight:1.5,marginBottom:12},children:"The primary source is the write destination. Read access is an explicit allowlist and does not widen automatically."}),c.jsxs("div",{style:{marginBottom:14},children:[c.jsx("label",{htmlFor:"agent-write-source",children:"Primary / write source"}),c.jsxs("select",{id:"agent-write-source",value:N,onChange:X=>{_(X.target.value),Q(!1)},style:{width:"100%",background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)",borderRadius:6,padding:"6px 10px",fontSize:14},children:[ut&&c.jsxs("option",{value:N,disabled:!0,children:[N," · unavailable"]}),E.map(X=>c.jsxs("option",{value:X.id,children:[X.name," (",X.id,")"]},X.id))]})]}),c.jsxs("fieldset",{style:{border:0,padding:0,margin:"0 0 14px"},children:[c.jsx("legend",{children:"Readable sources"}),c.jsxs("div",{className:"checkbox-group",style:{marginTop:6},children:[E.map(X=>c.jsxs("label",{className:"checkbox-label",children:[c.jsx("input",{type:"checkbox",checked:V.has(X.id),onChange:Xt=>{Q(!1),K(Vt=>Xt.target.checked?[...Vt,X.id]:Vt.filter(Qt=>Qt!==X.id))}}),X.name," (",X.id,")",X.federated?" · federated":" · private"]},X.id)),gt.map(X=>c.jsxs("label",{className:"checkbox-label",style:{color:"var(--warning)"},children:[c.jsx("input",{type:"checkbox",checked:!0,onChange:()=>{Q(!1),K(Xt=>Xt.filter(Vt=>Vt!==X))}}),X," · unavailable (clear to remove grant)"]},X))]})]}),(ut||gt.length>0)&&c.jsx("div",{style:{color:"var(--warning)",fontSize:13,marginBottom:10},children:"This client references unavailable or archived sources. Choose an active primary source and clear unavailable read grants before saving."}),B&&c.jsx("div",{style:{color:"var(--error)",fontSize:13,marginBottom:10},children:B}),O&&c.jsx("div",{style:{color:"var(--success)",fontSize:13,marginBottom:10},children:"Source access saved."}),c.jsx("button",{type:"button",className:"btn btn-primary",disabled:A||R.length===0||E.length===0||ut||gt.length>0,onClick:w,children:A?"Saving...":"Save Source Access"})]})}function Ty({agent:o,sources:M,onClose:E,onRevoked:h,onRescoped:N}){const[_,R]=L.useState("claude-code"),K=Q=>navigator.clipboard.writeText(Q),A=window.location.origin,p=o.id||o.client_id||"",B=o.auth_type==="oauth",D=o.name||o.client_name||"unknown",O={"claude-code":B?["The user wants to connect GBrain MCP to your context. Here's how.","","# Step 1 — read the client secret from the operator without putting it in shell history.","# read -s suppresses the echo; export keeps it scoped to this shell session.",'read -rs -p "Client Secret: " GBRAIN_CS && echo',"","# Step 2 — mint a token and register GBrain in one go.",`claude mcp add --transport http gbrain ${A}/mcp \\`,` --header "Authorization: Bearer $(curl -s -X POST ${A}/token \\`," -d 'grant_type=client_credentials' \\",` -d 'client_id=${p}' \\`,' --data-urlencode "client_secret=$GBRAIN_CS" \\',` -d 'scope=${o.scope||"read write"}' | jq -r .access_token)"`,"","# Step 3 — clear the secret from this shell.","unset GBRAIN_CS","",`The token will last ${o.token_ttl?o.token_ttl>=86400?Math.floor(o.token_ttl/86400)+" days":Math.floor(o.token_ttl/3600)+" hours":"1 hour (default)"}.`,"","─── Fallback: 2-step curl + paste ───","","If your shell doesn't support read -s, mint the token first, then paste:","",`curl -s -X POST ${A}/token \\`," -d 'grant_type=client_credentials' \\",` -d 'client_id=${p}' \\`," -d 'client_secret=PASTE_YOUR_CLIENT_SECRET_HERE' \\",` -d 'scope=${o.scope||"read write"}' | jq -r .access_token`,"",`claude mcp add --transport http gbrain ${A}/mcp \\`,' --header "Authorization: Bearer PASTE_TOKEN_FROM_ABOVE"',"","# Then run: history -d $((HISTCMD-1)) # zsh: print -s -- '' && fc -p"].join(` -`):["The user wants to connect GBrain MCP to your context. Here's how.","","Run this command in terminal to register GBrain:","",`claude mcp add --transport http gbrain ${A}/mcp \\`,' --header "Authorization: Bearer PASTE_YOUR_API_KEY_HERE"',"",`Replace PASTE_YOUR_API_KEY_HERE with the API key shown when "${D}" was created.`,"API keys never expire."].join(` -`),chatgpt:["The user wants to connect GBrain MCP to ChatGPT.","","1. Open ChatGPT > Settings > Tools & Integrations > Add MCP Server","2. Enter this URL — ChatGPT will auto-discover the OAuth configuration:","",` ${A}/.well-known/oauth-authorization-server`,"","3. When prompted for credentials:",` Client ID: ${p}`," Client Secret: (the secret from agent registration)"," Grant Type: client_credentials",` Scope: ${o.scope||"read write"}`].join(` -`),"claude-cowork":["The user wants to connect GBrain MCP to Claude.ai.","","1. Open claude.ai > Settings > Connected Apps > Add MCP Server",`2. Server URL: ${A}/mcp`,"3. When prompted for auth:",` Token endpoint: ${A}/token`,` Client ID: ${p}`," Client Secret: (the secret from agent registration)",` Scope: ${o.scope||"read write"}`,"",`Discovery URL: ${A}/.well-known/oauth-authorization-server`].join(` -`),cursor:B?["The user wants to connect GBrain MCP to Cursor.","","Cursor supports OAuth for remote MCP. Add to .cursor/mcp.json:","","{",' "mcpServers": {',' "gbrain": {',` "url": "${A}/mcp",`,' "transport": "sse"'," }"," }","}","","Cursor will auto-discover OAuth via:",`${A}/.well-known/oauth-authorization-server`,"",`When prompted: Client ID ${p}, use the secret from registration.`].join(` -`):["The user wants to connect GBrain MCP to Cursor.","","Add to .cursor/mcp.json:","","{",' "mcpServers": {',' "gbrain": {',` "url": "${A}/mcp",`,' "transport": "sse",',' "headers": {',' "Authorization": "Bearer PASTE_YOUR_API_KEY_HERE"'," }"," }"," }","}","",`Replace PASTE_YOUR_API_KEY_HERE with the API key shown when "${D}" was created.`].join(` -`),perplexity:["The user wants to connect GBrain MCP to Perplexity.","","1. Go to Settings > Connectors > Add MCP",`2. Server URL: ${A}/mcp`,`3. Client ID: ${p}`,"4. Client Secret: (the secret from agent registration)"].join(` -`),json:JSON.stringify({server_url:A+"/mcp",token_url:A+"/token",discovery_url:A+"/.well-known/oauth-authorization-server",client_id:p,client_name:D,auth_type:o.auth_type,scope:o.scope},null,2)};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"drawer-overlay",onClick:E}),c.jsxs("div",{className:"drawer",children:[c.jsx("button",{className:"drawer-close",onClick:E,children:"✕"}),c.jsx("div",{style:{fontSize:18,fontWeight:600,marginBottom:4},children:o.name||o.client_name}),c.jsx("span",{className:`badge ${o.status==="active"?"badge-success":"badge-danger"}`,children:o.status}),c.jsx("div",{className:"section-title",children:"Details"}),c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Client ID"}),c.jsxs("span",{className:"mono",children:[(o.id||o.id||o.client_id||"").substring(0,24),"..."]}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Scopes"}),c.jsx("span",{children:(o.scope||"").split(" ").filter(Boolean).map(Q=>c.jsx("span",{className:`badge badge-${Q}`,style:{marginRight:4},children:Q},Q))}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Registered"}),c.jsx("span",{children:new Date(o.created_at).toLocaleDateString()}),c.jsx("span",{style:{color:"var(--text-secondary)"},children:"Token TTL"}),c.jsx("span",{children:o.token_ttl?o.token_ttl>=31536e3?"No expiry":o.token_ttl>=86400?`${Math.floor(o.token_ttl/86400)}d`:o.token_ttl>=3600?`${Math.floor(o.token_ttl/3600)}h`:`${o.token_ttl}s`:"1h (default)"})]}),B&&c.jsx(jy,{clientId:p,agent:o,sources:M,onRescoped:N}),c.jsx("div",{className:"section-title",children:"Config Export"}),c.jsxs("div",{className:"tabs",style:{flexWrap:"wrap"},children:[c.jsx("div",{className:`tab ${_==="claude-code"?"active":""}`,onClick:()=>R("claude-code"),children:"Claude Code"}),c.jsx("div",{className:`tab ${_==="chatgpt"?"active":""}`,onClick:()=>R("chatgpt"),children:"ChatGPT"}),c.jsx("div",{className:`tab ${_==="claude-cowork"?"active":""}`,onClick:()=>R("claude-cowork"),children:"Claude.ai"}),c.jsx("div",{className:`tab ${_==="cursor"?"active":""}`,onClick:()=>R("cursor"),children:"Cursor"}),c.jsx("div",{className:`tab ${_==="perplexity"?"active":""}`,onClick:()=>R("perplexity"),children:"Perplexity"}),c.jsx("div",{className:`tab ${_==="json"?"active":""}`,onClick:()=>R("json"),children:"JSON"})]}),(()=>{if(!B&&new Set(["chatgpt","claude-cowork","perplexity"]).has(_)){const V=_==="chatgpt"?"ChatGPT":_==="claude-cowork"?"Claude.ai":"Perplexity";return c.jsxs("div",{style:{background:"rgba(255, 200, 100, 0.08)",border:"1px solid rgba(255, 200, 100, 0.2)",borderRadius:8,padding:"14px 16px",marginTop:12,fontSize:13,lineHeight:1.6,color:"var(--text-secondary)"},children:[c.jsxs("div",{style:{fontWeight:600,color:"var(--text-primary)",marginBottom:6},children:[V," requires an OAuth client"]}),V," only supports OAuth 2.0 (client_credentials). API keys use raw bearer tokens, which ",V," does not accept. Register a separate OAuth client and use that to connect this AI."]})}return c.jsxs("div",{className:"code-block",children:[c.jsx("pre",{style:{whiteSpace:"pre-wrap",margin:0},children:O[_]}),c.jsx("button",{className:"copy-btn",onClick:()=>K(O[_]),children:"Copy"})]})})(),c.jsxs("div",{style:{marginTop:32},children:[o.status==="active"&&c.jsx("button",{className:"btn btn-danger",onClick:async()=>{if(confirm(`Revoke ${o.name||o.client_name}? All active tokens will be invalidated.`))try{o.auth_type==="oauth"?await Lt.revokeClient(o.id||o.client_id||""):await Lt.revokeApiKey(o.name||""),h(),E()}catch(Q){alert("Revoke failed: "+(Q instanceof Error?Q.message:"unknown error"))}},children:"Revoke Agent"}),o.status==="revoked"&&c.jsx("span",{style:{color:"var(--text-muted)",fontSize:13},children:"This agent has been revoked."})]})]})]})}function zy(){const[o,M]=L.useState({rows:[],total:0,page:1,pages:1}),[E,h]=L.useState(1),[N,_]=L.useState("all"),[R,K]=L.useState(null);L.useEffect(()=>{A(E)},[E,N]);const A=O=>{const Q=N!=="all"?`&agent=${encodeURIComponent(N)}`:"";Lt.requests(O,Q).then(M).catch(()=>{})},p=O=>{const Q=Date.now()-new Date(O).getTime();return Q<6e4?`${Math.floor(Q/1e3)}s ago`:Q<36e5?`${Math.floor(Q/6e4)} min ago`:Q<864e5?`${Math.floor(Q/36e5)}h ago`:new Date(O).toLocaleDateString()},B=O=>{if(!O)return null;const{query:Q,slug:V,partial:it,limit:gt,...ut}=O,w=[];return Q&&w.push(`"${Q}"`),V&&w.push(V),it&&w.push(`~${it}`),gt&&w.push(`limit=${gt}`),Object.keys(ut).length>0&&w.push(`+${Object.keys(ut).length} params`),w.join(" ")},D=new Map;return o.rows.forEach(O=>{O.token_name&&D.set(O.token_name,O.agent_name||O.token_name)}),c.jsxs(c.Fragment,{children:[c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[c.jsx("h1",{className:"page-title",style:{marginBottom:0},children:"Request Log"}),c.jsxs("select",{value:N,onChange:O=>{_(O.target.value),h(1)},style:{background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)",borderRadius:6,padding:"4px 8px",fontSize:13},children:[c.jsx("option",{value:"all",children:"All agents"}),[...D.entries()].map(([O,Q])=>c.jsx("option",{value:O,children:Q},O))]})]}),o.rows.length===0?c.jsx("div",{style:{textAlign:"center",padding:48,color:"var(--text-muted)"},children:"No requests yet."}):c.jsxs(c.Fragment,{children:[c.jsxs("table",{children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Time"}),c.jsx("th",{children:"Agent"}),c.jsx("th",{children:"Operation"}),c.jsx("th",{children:"Params"}),c.jsx("th",{children:"Latency"}),c.jsx("th",{children:"Status"})]})}),c.jsx("tbody",{children:o.rows.map(O=>c.jsxs(Dd.Fragment,{children:[c.jsxs("tr",{onClick:()=>K(R===O.id?null:O.id),style:{cursor:"pointer"},children:[c.jsx("td",{style:{color:"var(--text-secondary)",whiteSpace:"nowrap"},children:p(O.created_at)}),c.jsx("td",{children:c.jsx("a",{style:{color:"var(--text-link, #88aaff)",cursor:"pointer",textDecoration:"none",fontWeight:500},onClick:Q=>{Q.stopPropagation(),_(O.token_name),h(1)},children:O.agent_name||O.token_name})}),c.jsx("td",{className:"mono",children:O.operation}),c.jsx("td",{style:{color:"var(--text-secondary)",fontSize:12,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:B(O.params)}),c.jsxs("td",{className:"mono",children:[O.latency_ms,"ms"]}),c.jsx("td",{children:c.jsx("span",{className:`badge badge-${O.status}`,children:O.status})})]}),R===O.id&&c.jsx("tr",{children:c.jsx("td",{colSpan:6,style:{background:"var(--bg-secondary, #0f0f1a)",padding:16},children:c.jsxs("div",{style:{display:"grid",gridTemplateColumns:"100px 1fr",gap:"6px 12px",fontSize:13},children:[c.jsx("span",{style:{color:"var(--text-muted)"},children:"Time"}),c.jsx("span",{children:new Date(O.created_at).toLocaleString()}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Agent"}),c.jsx("span",{className:"mono",children:O.token_name}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Operation"}),c.jsx("span",{className:"mono",children:O.operation}),c.jsx("span",{style:{color:"var(--text-muted)"},children:"Latency"}),c.jsxs("span",{children:[O.latency_ms,"ms"]}),O.params&&c.jsxs(c.Fragment,{children:[c.jsx("span",{style:{color:"var(--text-muted)"},children:"Params"}),c.jsx("pre",{className:"mono",style:{margin:0,whiteSpace:"pre-wrap",fontSize:12},children:JSON.stringify(O.params,null,2)})]}),O.error_message&&c.jsxs(c.Fragment,{children:[c.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:"Error"}),c.jsx("span",{style:{color:"var(--error, #ff6b6b)"},children:O.error_message})]})]})})})]},O.id))})]}),c.jsxs("div",{className:"pagination",children:[c.jsxs("span",{children:["Page ",o.page," of ",o.pages," (",o.total," total)"]}),c.jsxs("div",{style:{display:"flex",gap:8},children:[c.jsx("button",{disabled:o.page<=1,onClick:()=>h(O=>O-1),children:"Previous"}),c.jsx("button",{disabled:o.page>=o.pages,onClick:()=>h(O=>O+1),children:"Next"})]})]})]})]})}function Ay({markup:o}){return c.jsx("div",{style:{width:"100%",overflow:"auto"},dangerouslySetInnerHTML:{__html:o}})}function Zu({type:o,ariaLabel:M}){const[E,h]=L.useState(""),[N,_]=L.useState("");return L.useEffect(()=>{let R=!1;return Lt.calibrationChart(o).then(K=>{R||h(K)}).catch(K=>{R||_(K.message??"fetch failed")}),()=>{R=!0}},[o]),N?c.jsxs("div",{style:{padding:16,color:"var(--error)"},role:"alert",children:[M,": ",N]}):E?c.jsx(Ay,{markup:E}):c.jsxs("div",{style:{padding:16,color:"var(--text-muted)"},children:[M," loading..."]})}function _y(){const[o,M]=L.useState(null),[E,h]=L.useState(!0),[N,_]=L.useState("");if(L.useEffect(()=>{Lt.calibrationProfile().then(A=>{M(A),h(!1)}).catch(A=>{_(A.message??"fetch failed"),h(!1)})},[]),E)return c.jsx("div",{style:{padding:24,color:"var(--text-secondary)"},children:"Loading calibration profile…"});if(N)return c.jsxs("div",{style:{padding:24,color:"var(--error)"},role:"alert",children:["Could not load calibration profile: ",N]});if(!o)return c.jsxs("div",{style:{padding:24,maxWidth:700},children:[c.jsx("h1",{style:{marginBottom:16},children:"Calibration"}),c.jsx("p",{style:{color:"var(--text-secondary)"},children:"No calibration profile yet. Builds after 5+ resolved takes."}),c.jsx("pre",{style:{background:"var(--bg-secondary)",padding:12,borderRadius:4,color:"var(--text-primary)",marginTop:12,fontFamily:"var(--font-mono)"},children:"gbrain dream --phase calibration_profile"})]});const R=new Date(o.generated_at),K=Math.floor((Date.now()-R.getTime())/(1e3*60*60*24));return c.jsxs("div",{style:{padding:32,maxWidth:720},children:[c.jsx("h1",{style:{marginBottom:8},children:"Calibration"}),c.jsxs("div",{style:{color:"var(--text-muted)",fontSize:13,marginBottom:24},children:["Holder: ",o.holder," · ","Updated ",K===0?"today":`${K}d ago`,o.published&&" · published",o.grade_completion<.9&&` · ~${Math.round(o.grade_completion*100)}% graded`,!o.voice_gate_passed&&" · voice gate fell back to template"]}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Zu,{type:"brier-trend",ariaLabel:"Brier trend"})}),c.jsxs("section",{style:{marginBottom:32},children:[c.jsx("h2",{style:{fontSize:14,color:"var(--text-secondary)",marginBottom:12,fontWeight:400},children:"Pattern statements"}),c.jsx(Zu,{type:"pattern-statements",ariaLabel:"Pattern statements"})]}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Zu,{type:"domain-bars",ariaLabel:"Per-domain accuracy"})}),c.jsx("section",{style:{marginBottom:32},children:c.jsx(Zu,{type:"abandoned-threads",ariaLabel:"Abandoned threads"})}),o.active_bias_tags.length>0&&c.jsxs("section",{style:{marginBottom:32,color:"var(--text-muted)",fontSize:13},children:["Active bias tags: ",o.active_bias_tags.join(", ")]})]})}function Ey(o){return o===0?"var(--accent-success, #2ea043)":o>=100?"var(--accent-danger, #f85149)":"var(--accent-warn, #d29922)"}function Od(o){return`$${(o/100).toFixed(2)}`}function Oy(){const[o,M]=L.useState(null),[E,h]=L.useState(null);if(L.useEffect(()=>{let _=!0,R=null;const K=async()=>{try{const A=await Lt.jobsWatch();_&&(M(A),h(null))}catch(A){_&&h(A instanceof Error?A.message:String(A))}_&&(R=setTimeout(K,1e3))};return K(),()=>{_=!1,R&&clearTimeout(R)}},[]),E)return c.jsxs("div",{style:{padding:24,color:"var(--accent-danger, #f85149)"},children:[c.jsx("h2",{children:"Jobs Watch — error"}),c.jsx("pre",{style:{whiteSpace:"pre-wrap"},children:E})]});if(!o)return c.jsx("div",{style:{padding:24,color:"var(--text-muted, #777)"},children:"Loading jobs watch…"});const N=new Date(o.ts_ms).toLocaleTimeString();return c.jsxs("div",{style:{padding:24,fontFamily:'var(--font-mono, "JetBrains Mono", monospace)'},children:[c.jsxs("h1",{style:{fontSize:18,marginBottom:4},children:["Jobs Watch",c.jsxs("span",{style:{marginLeft:12,color:"var(--text-muted, #777)",fontSize:12,fontWeight:"normal"},children:["updated ",N]})]}),c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Queue"}),c.jsxs("div",{children:["waiting=",c.jsx("b",{children:o.queue_health.waiting})," ","active=",c.jsx("b",{children:o.queue_health.active})," ","stalled=",c.jsx("b",{style:{color:o.queue_health.stalled>0?"var(--accent-warn, #d29922)":void 0},children:o.queue_health.stalled})]})]}),o.by_type.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"By type (24h)"}),c.jsxs("table",{style:{borderCollapse:"collapse"},children:[c.jsx("thead",{children:c.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[c.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"name"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"total"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"done"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"fail"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"dead"})]})}),c.jsx("tbody",{children:o.by_type.slice(0,6).map(_=>c.jsxs("tr",{children:[c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.name}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.total}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.completed}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.failed}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:_.dead})]},_.name))})]})]}),c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Lease pressure (1h)"}),c.jsxs("div",{style:{color:Ey(o.lease_pressure_1h)},children:[o.lease_pressure_1h," bounce",o.lease_pressure_1h===1?"":"s"]})]}),o.top_errors.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Top errors (24h)"}),c.jsx("table",{style:{borderCollapse:"collapse"},children:c.jsx("tbody",{children:o.top_errors.slice(0,5).map(_=>c.jsxs("tr",{children:[c.jsxs("td",{style:{textAlign:"right",padding:"4px 12px 4px 0",color:"var(--text-muted, #777)"},children:[_.count,"×"]}),c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.cluster})]},_.cluster))})})]}),o.budget_owners.length>0&&c.jsxs("section",{style:{marginTop:24},children:[c.jsx("h2",{style:{fontSize:14,marginBottom:8},children:"Budget owners"}),c.jsxs("table",{style:{borderCollapse:"collapse"},children:[c.jsx("thead",{children:c.jsxs("tr",{style:{color:"var(--text-muted, #777)",fontSize:12},children:[c.jsx("th",{style:{textAlign:"left",padding:"4px 12px 4px 0"},children:"owner"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"spent"}),c.jsx("th",{style:{textAlign:"right",padding:"4px 12px"},children:"remaining"})]})}),c.jsx("tbody",{children:o.budget_owners.slice(0,5).map(_=>c.jsxs("tr",{children:[c.jsx("td",{style:{padding:"4px 12px 4px 0"},children:_.owner_id}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Od(_.total_spent_cents)}),c.jsx("td",{style:{textAlign:"right",padding:"4px 12px"},children:Od(_.remaining_cents)})]},_.owner_id))})]})]})]})}function Nd(){const o=window.location.hash.replace("#","")||"dashboard";return["login","dashboard","agents","log","calibration","jobs"].includes(o)?o:"dashboard"}function Ny(){const[o,M]=L.useState(Nd);L.useEffect(()=>{const N=()=>M(Nd());return window.addEventListener("hashchange",N),()=>window.removeEventListener("hashchange",N)},[]);const E=N=>{window.location.hash=N,M(N)};if(o==="login")return c.jsx(my,{onLogin:()=>E("dashboard")});const h=async()=>{if(confirm("Sign out every active admin session, including other browsers and tabs? Each one will need to re-authenticate via a fresh magic link.")){try{await Lt.signOutEverywhere()}catch{}E("login")}};return c.jsxs("div",{className:"app",children:[c.jsxs("nav",{className:"sidebar",children:[c.jsx("div",{className:"sidebar-logo",children:"GBrain"}),c.jsxs("div",{className:"sidebar-nav",children:[c.jsx("a",{className:`nav-item ${o==="dashboard"?"active":""}`,onClick:()=>E("dashboard"),children:"Dashboard"}),c.jsx("a",{className:`nav-item ${o==="agents"?"active":""}`,onClick:()=>E("agents"),children:"Agents"}),c.jsx("a",{className:`nav-item ${o==="log"?"active":""}`,onClick:()=>E("log"),children:"Request Log"}),c.jsx("a",{className:`nav-item ${o==="calibration"?"active":""}`,onClick:()=>E("calibration"),children:"Calibration"}),c.jsx("a",{className:`nav-item ${o==="jobs"?"active":""}`,onClick:()=>E("jobs"),children:"Jobs Watch"})]}),c.jsx("div",{style:{marginTop:"auto",padding:"16px 12px",borderTop:"1px solid var(--border)"},children:c.jsx("button",{onClick:h,style:{background:"transparent",border:"1px solid var(--border)",color:"var(--text-secondary)",padding:"6px 10px",borderRadius:6,fontSize:12,cursor:"pointer",width:"100%"},title:"Revoke every active admin session — every browser, every tab",children:"Sign out everywhere"})})]}),c.jsxs("main",{className:"main",children:[o==="dashboard"&&c.jsx(yy,{}),o==="agents"&&c.jsx(gy,{}),o==="log"&&c.jsx(zy,{}),o==="calibration"&&c.jsx(_y,{}),o==="jobs"&&c.jsx(Oy,{})]})]})}dy.createRoot(document.getElementById("root")).render(c.jsx(Dd.StrictMode,{children:c.jsx(Ny,{})})); diff --git a/admin/dist/assets/index-GxkWX7v3.css b/admin/dist/assets/index-GxkWX7v3.css deleted file mode 100644 index 32e5e375..00000000 --- a/admin/dist/assets/index-GxkWX7v3.css +++ /dev/null @@ -1 +0,0 @@ -:root{--bg-primary: #0a0a0f;--bg-secondary: #14141f;--bg-tertiary: #1e1e2e;--text-primary: #e0e0e0;--text-secondary: #888;--text-muted: #777;--accent: #3b82f6;--success: #22c55e;--warning: #f59e0b;--error: #ef4444;--font-mono: "JetBrains Mono", monospace;--font-sans: "Inter", system-ui, sans-serif}*{margin:0;padding:0;box-sizing:border-box}body{font-family:var(--font-sans);background:var(--bg-primary);color:var(--text-primary);font-size:14px;line-height:1.5}.app{display:flex;min-height:100vh}.sidebar{width:200px;background:var(--bg-secondary);border-right:1px solid #1e1e2e;padding:16px 0;flex-shrink:0;display:flex;flex-direction:column}.sidebar-logo{font-size:18px;font-weight:600;padding:0 16px 24px;color:var(--text-primary)}.sidebar-nav{display:flex;flex-direction:column;gap:2px}.nav-item{display:flex;align-items:center;gap:8px;padding:8px 16px;color:var(--text-secondary);text-decoration:none;font-size:13px;cursor:pointer;border-left:3px solid transparent;transition:all .15s}.nav-item:hover{background:var(--bg-tertiary);color:var(--text-primary)}.nav-item.active{border-left-color:var(--accent);background:var(--bg-tertiary);color:var(--text-primary)}.main{flex:1;padding:24px 32px;overflow-y:auto}.page-title{font-size:24px;font-weight:600;margin-bottom:24px}.metrics{display:flex;gap:16px;margin-bottom:24px}.metric{background:var(--bg-secondary);padding:16px 20px;border-radius:6px;min-width:140px}.metric-value{font-family:var(--font-mono);font-size:28px;font-weight:500}.metric-label{font-size:12px;color:var(--text-secondary);margin-top:4px}table{width:100%;border-collapse:collapse}th{text-align:left;font-size:11px;text-transform:uppercase;color:var(--text-muted);padding:8px 12px;font-weight:500;letter-spacing:.5px}td{padding:10px 12px;font-size:13px;border-top:1px solid #1a1a2a}tr:hover td{background:var(--bg-tertiary)}.badge{display:inline-block;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:500}.badge-read{background:#3b82f626;color:var(--accent)}.badge-write{background:#f59e0b26;color:var(--warning)}.badge-admin{background:#ef444426;color:var(--error)}.badge-success{background:#22c55e26;color:var(--success)}.badge-error{background:#ef444426;color:var(--error)}.status-dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px}.status-active{background:var(--success)}.status-warning{background:var(--warning)}.status-inactive{background:var(--text-muted)}.btn{padding:8px 16px;border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;border:none;transition:all .15s}.btn-primary{background:var(--accent);color:#fff}.btn-primary:hover{background:#2563eb}.btn-secondary{background:transparent;color:var(--text-secondary);border:1px solid #333}.btn-secondary:hover{border-color:var(--text-secondary);color:var(--text-primary)}.btn-danger{background:transparent;color:var(--error);border:1px solid var(--error)}.btn-danger:hover{background:#ef44441a}input,select{background:var(--bg-primary);border:1px solid #333;color:var(--text-primary);padding:8px 12px;border-radius:6px;font-size:13px;font-family:var(--font-sans);width:100%}input:focus,select:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 2px #3b82f633}input::placeholder{color:var(--text-muted)}label{display:block;font-size:13px;font-weight:500;margin-bottom:6px}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#000000b3;display:flex;align-items:center;justify-content:center;z-index:100}.modal{background:var(--bg-secondary);border-radius:8px;padding:24px;min-width:420px;max-width:520px}.modal-title{font-size:18px;font-weight:600;margin-bottom:20px}.drawer-overlay{position:fixed;top:0;right:0;bottom:0;left:0;background:#00000080;z-index:90}.drawer{position:fixed;right:0;top:0;bottom:0;width:420px;background:var(--bg-secondary);border-left:1px solid var(--accent);padding:24px;z-index:91;overflow-y:auto}.drawer-close{position:absolute;top:16px;right:16px;background:none;border:none;color:var(--text-muted);font-size:18px;cursor:pointer}.section-title{font-size:11px;text-transform:uppercase;color:var(--text-muted);letter-spacing:.5px;margin:20px 0 12px;font-weight:500}.health-panel{background:var(--bg-secondary);border-radius:6px;padding:16px}.health-row{display:flex;justify-content:space-between;padding:6px 0;font-size:13px}.code-block{background:var(--bg-primary);border-radius:6px;padding:12px;font-family:var(--font-mono);font-size:12px;overflow-x:auto;position:relative}.code-block .copy-btn{position:absolute;top:8px;right:8px;background:var(--accent);color:#fff;border:none;padding:4px 10px;border-radius:4px;font-size:11px;cursor:pointer}.feed{max-height:400px;overflow-y:auto}.feed-empty{color:var(--text-muted);text-align:center;padding:32px;font-size:13px}.sparkline{display:inline-block;vertical-align:middle}.filter-bar{display:flex;gap:12px;margin-bottom:16px;align-items:center}.filter-bar select{width:auto;min-width:140px}.pagination{display:flex;justify-content:space-between;align-items:center;padding:12px 0;font-size:13px;color:var(--text-secondary)}.pagination button{background:var(--bg-secondary);border:1px solid #333;color:var(--text-primary);padding:6px 12px;border-radius:4px;cursor:pointer;font-size:12px}.pagination button:disabled{opacity:.3;cursor:default}.warning-bar{background:#f59e0b26;border:1px solid var(--warning);color:var(--warning);padding:10px 16px;border-radius:6px;font-size:13px;margin:12px 0}.checkbox-group{display:flex;gap:16px;flex-wrap:wrap}.checkbox-label{display:flex;align-items:center;gap:6px;font-size:13px;cursor:pointer}.tabs{display:flex;gap:0;margin-bottom:12px}.tab{padding:6px 12px;font-size:13px;color:var(--text-secondary);cursor:pointer;border-bottom:2px solid transparent}.tab.active{color:var(--accent);border-bottom-color:var(--accent)}.login-page{display:flex;align-items:center;justify-content:center;min-height:100vh;background:var(--bg-primary)}.login-box{text-align:left;width:340px}.login-logo{font-size:32px;font-weight:600;margin-bottom:32px}.login-hint{color:var(--text-muted);font-size:12px;margin-top:12px}.login-error{color:var(--error);font-size:13px;margin-top:8px}.mono{font-family:var(--font-mono);font-size:12px}@media(max-width:768px){.sidebar{display:none}.main{padding:16px}.metrics{flex-wrap:wrap}.drawer{width:100%}} diff --git a/admin/dist/index.html b/admin/dist/index.html index b6fcad3e..8a8d946b 100644 --- a/admin/dist/index.html +++ b/admin/dist/index.html @@ -7,8 +7,8 @@ - - + +
diff --git a/admin/src/api.ts b/admin/src/api.ts index 3c15d585..4bec496b 100644 --- a/admin/src/api.ts +++ b/admin/src/api.ts @@ -17,7 +17,7 @@ async function apiFetch(path: string, options?: RequestInit) { } if (!res.ok) { const body = await res.json().catch(() => ({})); - throw new Error(body.error || `HTTP ${res.status}`); + throw new Error(body.message || body.error || `HTTP ${res.status}`); } return res.json(); } @@ -39,7 +39,13 @@ export const api = { stats: () => apiFetch('/admin/api/stats'), health: () => apiFetch('/admin/api/health-indicators'), agents: () => apiFetch('/admin/api/agents'), + agentsSpend: () => apiFetch('/admin/api/agents/spend'), sources: () => apiFetch('/admin/api/sources'), + grantCatalog: () => apiFetch('/admin/api/grant-catalog'), + clientGrant: (clientId: string) => apiFetch(`/admin/api/grants/${encodeURIComponent(clientId)}`), + registerClient: (body: Record) => apiFetch('/admin/api/register-client', { method: 'POST', body: JSON.stringify(body) }), + recoverClient: (clientId: string) => apiFetch('/admin/api/recover-client', { method: 'POST', body: JSON.stringify({ clientId }) }), + updateClientGrant: (clientId: string, body: Record) => apiFetch('/admin/api/rescope-client', { method: 'POST', body: JSON.stringify({ ...body, clientId }) }), requests: (page = 1, qs = '') => apiFetch(`/admin/api/requests?page=${page}${qs}`), apiKeys: () => apiFetch('/admin/api/api-keys'), createApiKey(keyName: string) { diff --git a/admin/src/components/ClientGrant.tsx b/admin/src/components/ClientGrant.tsx new file mode 100644 index 00000000..78b6a9fa --- /dev/null +++ b/admin/src/components/ClientGrant.tsx @@ -0,0 +1,192 @@ +import { useEffect, useState } from 'react'; +import { api } from '../api'; + +export interface Grant { + clientId: string; clientName: string; profile: string | null; revision: number; + scopes: string[]; sourceId: string; federatedRead: string[]; + boundSlugPrefixes: string[] | null; allowedOperations: string[] | null; + boundTools: string[] | null; boundSourceId: string | null; boundBrainId: string | null; + delegatedSlugPrefixes: string[] | null; delegatedNamespace: 'job' | 'prefixes'; + boundMaxConcurrent: number; budgetUsdPerDay: string | null; tokenTtlSeconds: number | null; + surface: string | null; repairReasons: string[]; +} +export interface GrantSource { id: string; name: string; federated: boolean } +export interface GrantCatalog { profiles: string[]; delegatedTools: string[]; operations: string[]; harnesses: { id: string; label: string; documentation: string }[] } +export interface GrantPreviewResult { before: Grant | null; after: Grant; revision: number; dryRun: boolean; tokenImplications: string } +export interface GrantDraft { + profile: string; applyProfile: boolean; source: string; reads: string[]; scopes: string; + directPrefixes: string; tools: string[]; namespace: 'job' | 'prefixes'; delegatedPrefixes: string; + concurrency: string; budget: string; ttl: string; surface: string; + operationSnapshot: string; editOperations: boolean; +} +const split = (text: string) => text.split(/[\s,]+/).filter(Boolean); +export function grantDraft(grant?: Grant): GrantDraft { + return { + profile: grant?.profile ?? 'memory-writer', applyProfile: !grant, source: grant?.sourceId ?? 'default', reads: grant?.federatedRead ?? ['default'], + scopes: grant?.scopes.join(' ') ?? '', directPrefixes: grant?.boundSlugPrefixes?.join('\n') ?? '', + tools: grant?.boundTools ?? [], namespace: grant?.delegatedNamespace ?? 'job', delegatedPrefixes: grant?.delegatedSlugPrefixes?.join('\n') ?? '', + concurrency: String(grant?.boundMaxConcurrent ?? 1), budget: grant?.budgetUsdPerDay ?? 'unlimited', + ttl: grant ? String(grant.tokenTtlSeconds ?? 0) : '3600', surface: grant?.surface ?? 'starter', + operationSnapshot: grant?.allowedOperations?.join('\n') ?? '', editOperations: false, + }; +} +export function grantRequest(draft: GrantDraft): Record { + const delegates = draft.scopes ? split(draft.scopes).includes('agent') : ['full', 'delegating-agent'].includes(draft.profile); + return { + ...(draft.applyProfile ? { profile: draft.profile } : {}), + sourceId: draft.source, federatedRead: draft.reads, boundSlugPrefixes: draft.directPrefixes.trim() ? split(draft.directPrefixes) : null, + ...(draft.scopes.trim() ? { scopes: split(draft.scopes) } : {}), + ...(draft.editOperations ? { allowedOperations: split(draft.operationSnapshot) } : {}), + ...(delegates ? { boundTools: draft.tools, boundSourceId: draft.source, delegatedNamespace: draft.namespace, + delegatedSlugPrefixes: draft.namespace === 'job' ? null : split(draft.delegatedPrefixes) } : {}), + boundMaxConcurrent: Number(draft.concurrency), budgetUsdPerDay: draft.budget === 'unlimited' ? null : draft.budget, + tokenTtl: draft.ttl === '0' ? null : Number(draft.ttl), surface: draft.surface === 'default' ? null : draft.surface, + }; +} +/** Commit the reviewed snapshot itself, so a server upgrade between preview + * and apply cannot silently add newly registered operations to a profile. */ +export function reviewedGrantRequest(grant: Grant): Record { + return { + ...(grant.profile ? { profile: grant.profile } : {}), scopes: grant.scopes, sourceId: grant.sourceId, federatedRead: grant.federatedRead, + boundSlugPrefixes: grant.boundSlugPrefixes, allowedOperations: grant.allowedOperations, boundTools: grant.boundTools, + boundSourceId: grant.boundSourceId, boundBrainId: grant.boundBrainId, delegatedNamespace: grant.delegatedNamespace, + delegatedSlugPrefixes: grant.delegatedSlugPrefixes, boundMaxConcurrent: grant.boundMaxConcurrent, + budgetUsdPerDay: grant.budgetUsdPerDay, tokenTtlSeconds: grant.tokenTtlSeconds, surface: grant.surface, + }; +} + +export function GrantFields({ draft, setDraft, sources, catalog, existing = false }: { + draft: GrantDraft; setDraft: (draft: GrantDraft) => void; sources: GrantSource[]; catalog: GrantCatalog; existing?: boolean; +}) { + const change = (key: K, value: GrantDraft[K]) => setDraft({ ...draft, [key]: value }); + const available = new Set(sources.map(s => s.id)); + const delegates = draft.scopes ? split(draft.scopes).includes('agent') : ['full', 'delegating-agent'].includes(draft.profile); + const field = { marginBottom: 14 }; + return <> +
+ +

Memory writer lets this agent recall, save, correct, and withdraw memory. Delegating profiles also allow selected server tools to run jobs.

+ {existing && } +
+
+
Readable sources + {[...sources, ...draft.reads.filter(id => !available.has(id)).map(id => ({ id, name: `${id} · unavailable` }))].map(source => )} +
+