diff --git a/.changeset/bharatcode-catalog-recovery.md b/.changeset/bharatcode-catalog-recovery.md new file mode 100644 index 00000000..459c0c7d --- /dev/null +++ b/.changeset/bharatcode-catalog-recovery.md @@ -0,0 +1,6 @@ +--- +"bharatcode-agent": patch +"@kilocode/cli": patch +--- + +Recover the BharatCode model catalog after temporary failures without restarting sessions. Keep the last working model list, explain catalog errors, and provide a catalog-only retry action. Isolate BharatCode Agent commands and views from other Kilo-derived extensions while preserving chats, sign-ins and existing settings. diff --git a/.changeset/bharatcode-vscode-publisher.md b/.changeset/bharatcode-vscode-publisher.md new file mode 100644 index 00000000..f3ac844e --- /dev/null +++ b/.changeset/bharatcode-vscode-publisher.md @@ -0,0 +1,5 @@ +--- +"bharatcode-agent": patch +--- + +Use the verified BharatCode publisher for the website sign-in extension, with matching runtime identity and package checks. diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index e74d4229..d619f9f8 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -42,12 +42,14 @@ jobs: check-kilo-generated-artifacts \ check-test-ci \ check-opencode-promise-facades \ - check-model-tool-network \ - check-opencode-annotations; do + check-model-tool-network; do echo "::group::$g" bun "script/$g.ts" echo "::endgroup::" done + # This organization fork imports Navya's bc/main, not upstream's main branch. + # Keep checking every change since that immutable import; do not silently skip the guard. + bun script/check-opencode-annotations.ts --base 1e97696076bafea5ff4010627108ca50a162d9eb echo "::group::extract-source-links" bun script/extract-source-links.ts --check echo "::endgroup::" @@ -90,6 +92,12 @@ jobs: # without it: "No usable Bubblewrap executable is available") - uses: ./.github/actions/setup-linux-sandbox + - name: OAuth identity and package regressions (blocking) + working-directory: packages/kilo-vscode + run: | + python3 -B -m unittest discover -s tests -p test_identity.py + bun --config=/dev/null test --preload ./tests/setup/vscode-mock.ts ./tests/unit/bharatcode-website-signin.test.ts ./tests/unit/extension-arch.test.ts ./tests/unit/extension-identity.test.ts ../opencode/test/plugin/bharatcode.test.ts + # 37 pre-existing failures = rebrand drift (tests assert upstream # strings like "Add to Kilo Code"; nothing ran these in this fork # before CI existed). Non-blocking so they stay visible without diff --git a/.github/workflows/oauth-candidate.yml b/.github/workflows/oauth-candidate.yml new file mode 100644 index 00000000..d5029854 --- /dev/null +++ b/.github/workflows/oauth-candidate.yml @@ -0,0 +1,113 @@ +# kilocode_change - new file +name: Website sign-in candidate + +on: + workflow_dispatch: + inputs: + reuse_verified_backends: + description: "Reuse only verified run 44186017306 backends; rebuild extension packages" + type: boolean + default: false + +permissions: + contents: read + actions: read + +concurrency: + group: oauth-candidate-${{ github.ref }} + cancel-in-progress: false + +jobs: + candidate: + runs-on: ubuntu-24.04 + timeout-minutes: 60 + env: + KILO_VERSION: 7.8.115 + KILO_CLI_TARGETS: win32-x64,win32-arm64,linux-x64,linux-arm64,linux-x64-musl,linux-arm64-musl,darwin-x64,darwin-arm64 + KILO_SKIP_BUNDLED_BWRAP: "1" + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + fetch-depth: 0 + - name: Download and verify fixed parent backends + if: inputs.reuse_verified_backends + env: + GH_TOKEN: ${{ github.token }} + run: | + gh api repos/BharatCode-ai/bharatcode-vscode/actions/artifacts/14373729058 > "$RUNNER_TEMP/parent-metadata.json" + gh api repos/BharatCode-ai/bharatcode-vscode/actions/artifacts/14373729058/zip > "$RUNNER_TEMP/parent.zip" + python3 -B packages/kilo-vscode/script/reuse-candidate.py prepare \ + --metadata "$RUNNER_TEMP/parent-metadata.json" --archive "$RUNNER_TEMP/parent.zip" \ + --root "$RUNNER_TEMP/verified-parent" + echo "CLI_DIST_DIR=$RUNNER_TEMP/verified-parent/dist" >> "$GITHUB_ENV" + - uses: ./.github/actions/setup-bun + with: + install-flags: ${{ inputs.reuse_verified_backends && '--os=linux --cpu=x64' || '--os=* --cpu=*' }} + - name: Verify source and release guards + run: | + bun script/check-workflows.ts + bun script/check-md-table-padding.ts + bun script/check-opencode-annotations.ts --base 1e97696076bafea5ff4010627108ca50a162d9eb + bun script/extract-source-links.ts --check + python3 -B -m unittest discover -s packages/kilo-vscode/tests -p 'test_*.py' + bunx prettier --check .github/workflows/oauth-candidate.yml .github/workflows/release.yml .github/workflows/checks.yml packages/kilo-vscode/package.json packages/kilo-vscode/src/constants.ts packages/kilo-vscode/src/extension.ts packages/kilo-vscode/tests/unit/extension-identity.test.ts packages/kilo-vscode/tests/unit/reuse-candidate-resources.test.ts packages/kilo-vscode/script/build.ts packages/kilo-vscode/script/publish.ts packages/kilo-vscode/webview-ui/src/components/chat/FeedbackDialog.tsx packages/kilo-vscode/webview-ui/src/components/marketplace/MarketplaceContribute.tsx packages/kilo-vscode/webview-ui/src/components/settings/AboutKiloCodeTab.tsx + - name: Verify website sign-in and command wiring + working-directory: packages/kilo-vscode + run: >- + bun --config=/dev/null test --preload ./tests/setup/vscode-mock.ts + ./tests/unit/bharatcode-website-signin.test.ts + ./tests/unit/extension-arch.test.ts + ./tests/unit/extension-identity.test.ts + ./tests/unit/namespace-migration.test.ts + ./tests/unit/configuration-lifecycle.test.ts + ./tests/unit/bharatcode-catalog-ui.test.ts + ./tests/unit/model-selector-lifecycle.test.ts + ./tests/unit/kilo-provider-provider-refresh.test.ts + ./tests/unit/kilo-provider-catalog.test.ts + ./tests/unit/provider-actions-save.test.ts + ./tests/unit/provider-context-catalog.test.ts + ./tests/unit/reuse-candidate-resources.test.ts + ../opencode/test/plugin/bharatcode.test.ts + - name: Verify catalog recovery without session disposal + working-directory: packages/opencode + run: >- + bun test + test/kilocode/provider/bharatcode-catalog.test.ts + test/kilocode/provider/bharatcode-catalog-cache.test.ts + test/kilocode/provider/catalog-refresh-route.test.ts + test/kilocode/catalog-recovery.test.ts + test/kilocode/model-cache-effect.test.ts + test/kilocode/model-cache-org.test.ts + --timeout 30000 + - name: Build bundled backends + if: ${{ !inputs.reuse_verified_backends }} + working-directory: packages/opencode + run: bun script/build.ts --skip-install + - name: Build and check extension packages + working-directory: packages/kilo-vscode + run: | + export PATH="$PWD/node_modules/.bin:$PATH" + bun run check-kilocode-change + bun run check-types:webview + bun script/build.ts + - name: Audit exact candidate packages + if: ${{ !inputs.reuse_verified_backends }} + run: >- + python3 packages/kilo-vscode/script/audit-vsix.py + --version "$KILO_VERSION" --receipt + - name: Audit derived packages and unchanged backend resources + if: inputs.reuse_verified_backends + run: >- + python3 -B packages/kilo-vscode/script/reuse-candidate.py verify + --root "$RUNNER_TEMP/verified-parent" + --out packages/kilo-vscode/out + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: vscode-oauth-${{ github.sha }} + path: | + packages/kilo-vscode/out/*.vsix + packages/kilo-vscode/out/candidate.json + packages/kilo-vscode/out/SHA256SUMS + if-no-files-found: error + retention-days: 3 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 54ee65c1..0832f42c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,8 +7,6 @@ name: Release on: - push: - branches: [bc/main] workflow_dispatch: permissions: @@ -145,45 +143,9 @@ jobs: - name: Audit vsixes + SHA256SUMS env: V: ${{ needs.cut.outputs.version }} - run: | - set -euo pipefail - python3 - <<'PY' - import json, os, zipfile, glob - V = os.environ["V"] - expected_binary = { - "win32-x64": "extension/bin/bharatcode.exe", - "win32-arm64": "extension/bin/bharatcode.exe", - } - files = sorted(glob.glob("packages/kilo-vscode/out/*.vsix")) - assert len(files) == 8, f"expected 8 vsixes, got {len(files)}" - for f in files: - base = os.path.basename(f) - prefix, suffix = "bharatcode-vscode-", f"-{V}.vsix" - assert base.startswith(prefix) and base.endswith(suffix), f"unexpected name {base}" - plat = base[len(prefix):-len(suffix)] - z = zipfile.ZipFile(f) - names = z.namelist() - maps = [n for n in names if n.endswith(".map")] - assert not maps, f"{plat}: {len(maps)} sourcemaps in zip" - want = expected_binary.get(plat, "extension/bin/bharatcode") - other = "extension/bin/bharatcode" if want.endswith(".exe") else "extension/bin/bharatcode.exe" - bins = [ - n for n in names - if n.startswith("extension/bin/") and n.count("/") == 2 - and not n.endswith((".wasm", ".js")) - and not any(t in n for t in ("tree-sitter", "console", "ffmpeg", "sandbox")) - ] - assert want in bins, f"{plat}: missing {want}, have {bins}" - assert other not in bins, f"{plat}: wrong-platform binary {other}" - lic = z.read("extension/LICENSE.txt").decode() - assert "BharatCode modifications" in lic and "Kilo Code" in lic, f"{plat}: license lines missing" - man = json.loads(z.read("extension/package.json")) - assert man["version"] == V, f"{plat}: version {man['version']} != {V}" - assert man["name"] == "bharatcode-vscode" and man["publisher"] == "thenabbu", f"{plat}: manifest identity" - print(f"{plat}: OK v{man['version']}") - PY - (cd packages/kilo-vscode/out && sha256sum *.vsix > SHA256SUMS) - cat packages/kilo-vscode/out/SHA256SUMS + run: >- + python3 packages/kilo-vscode/script/audit-vsix.py + --version "$V" --versioned --checksums - uses: actions/upload-artifact@v4 with: diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 0ec07fbd..0f8a2804 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -60,9 +60,9 @@ representative at an online or offline event. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement by opening an -issue at https://github.com/thenabbu/BharatCode-VSCode-Extension/issues +issue at https://github.com/BharatCode-ai/bharatcode-vscode/issues (confidential reports may instead be filed as a private security advisory at -https://github.com/thenabbu/BharatCode-VSCode-Extension/security/advisories/new). +https://github.com/BharatCode-ai/bharatcode-vscode/security/advisories/new). All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8dd2818e..3464e317 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,7 +12,7 @@ There are lots of ways to contribute to the project: - **Feature Requests:** Suggest new features or improvements - **Community Support:** Help other users in the community -Questions and discussion belong in [GitHub Issues](https://github.com/thenabbu/BharatCode-VSCode-Extension/issues). +Questions and discussion belong in [GitHub Issues](https://github.com/BharatCode-ai/bharatcode-vscode/issues). ## Prerequisites diff --git a/PRIVACY.md b/PRIVACY.md index 2a8218c2..362a7cca 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -25,7 +25,7 @@ No system is 100% secure. We take reasonable measures to protect what we do hand ## Contact -Questions about privacy: open an issue on [GitHub](https://github.com/thenabbu/BharatCode-VSCode-Extension/issues). +Questions about privacy: open an issue on [GitHub](https://github.com/BharatCode-ai/bharatcode-vscode/issues). --- diff --git a/README.md b/README.md index 1388ae4c..fe50953d 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@
-BharatCode for VS Code — the VS Code extension for bharatcode.ai +BharatCode Agent — the VS Code extension for bharatcode.ai
-Marketplace version -Latest release -CI status +Marketplace version +Latest release +CI status MIT licensed Provider: bharatcode.ai @@ -14,18 +14,18 @@ ### Your coding agent, ready in one click -**BharatCode for VS Code** installs the whole agent for you — runtime, provider, endpoint and models included. Sign in, and you are writing with it. +**BharatCode Agent** installs the whole agent for you — runtime, provider, endpoint and models included. Sign in, and you are writing with it.
--- -**[Install from the VS Code Marketplace »](https://marketplace.visualstudio.com/items?itemName=thenabbu.bharatcode-vscode)** +**[Install from the VS Code Marketplace »](https://marketplace.visualstudio.com/items?itemName=bharatcode.bharatcode-agent)** *Or press `Ctrl+P` / `⌘P` and paste:* ```bash -ext install thenabbu.bharatcode-vscode +ext install bharatcode.bharatcode-agent ``` VS Code **1.105.1** or newer. Chromebook, Linux, macOS and Windows all get their own build. @@ -38,17 +38,9 @@ VS Code **1.105.1** or newer. Chromebook, Linux, macOS and Windows all get their **2. Open a folder.** `File → Open Folder`. Your project is what the agent reads and edits. -**3. Sign in.** BharatCode greets you on first launch and offers both ways in: +**3. Select Sign in with BharatCode.** Your browser opens the BharatCode website. Sign in if needed, approve access, then return to VS Code. No API key or model request is needed for setup. -| | **Sign in with BharatCode** | **API key** | -|---|---|---| -| **Best for** | Nearly everyone | Scripts, shared machines, CI | -| **How** | A browser tab opens; click approve; done | Paste a key from your bharatcode.ai account | -| **Typing** | None | One paste | - -Both are first-class paths and both work on first run — pick either. Your credential is stored by the extension backend, **never** in `settings.json`, so it stays out of your repo and your dotfiles. - -Missed the prompt? `BharatCode: Connect Account` in the Command Palette brings it back. +You can also run `BharatCode: Sign In` from the Command Palette. Already connected? Your existing connection keeps working. That is the entire setup. No base URL, no provider JSON, no model list, no CLI. @@ -78,7 +70,7 @@ Your BharatCode account comes with two models, and the extension wires both up f | Model | Context | Best at | |---|---|---| -| `qwen-3.8-27b` | 262k | Everyday edits and fast iteration | +| `glm-5.3-flash` | 262k | Everyday edits and fast iteration | | `deepseek-v4.1-flash` | 1M | Whole-repo reasoning and long sessions | Both come from one OpenAI-compatible endpoint at `https://bharatcode.ai/api/model/v1`, and the list is read live from it. @@ -94,7 +86,7 @@ Both come from one OpenAI-compatible endpoint at `https://bharatcode.ai/api/mode
-Grab the file for your system from [Releases](https://github.com/thenabbu/BharatCode-VSCode-Extension/releases/latest), then run `Extensions: Install from VSIX...` from the Command Palette: +Grab the file for your system from [Releases](https://github.com/BharatCode-ai/bharatcode-vscode/releases/latest), then run `Extensions: Install from VSIX...` from the Command Palette: ```bash code --install-extension bharatcode-vscode-linux-x64-.vsix @@ -112,7 +104,7 @@ Eight platform builds ship per release, plus `SHA256SUMS`: Each carries its own runtime binary, which is why they are split per platform — you download yours, once. Verify with `sha256sum --check SHA256SUMS`. > **macOS first run:** builds are unsigned for now. If Gatekeeper blocks it: -> `xattr -dr com.apple.quarantine ~/.vscode/extensions/bharatcode.bharatcode-vscode-*` +> `xattr -dr com.apple.quarantine ~/.vscode/extensions/bharatcode.bharatcode-agent-*` @@ -136,14 +128,14 @@ Install the extension, sign in, and the agent is running — because the extensi
Where does this extension come from? -It is a fork of [Kilo Code](https://github.com/Kilo-Org/kilocode), itself a fork of [OpenCode](https://github.com/anomalyco/opencode). Those projects and their contributors built the agent this package runs, and the credit is theirs — MIT licensed, with attribution preserved in [LICENSE](LICENSE) and in the `kilocode_change` markers throughout the source. This fork brings that agent to the BharatCode provider, rebrands it, and reconfigures the provider layer so bharatcode.ai is wired in from the start. We build on their work; we do not claim it. +This organization repository continues [Navya’s BharatCode extension](https://github.com/thenabbu/BharatCode-VSCode-Extension). It is a fork of [Kilo Code](https://github.com/Kilo-Org/kilocode), itself a fork of [OpenCode](https://github.com/anomalyco/opencode). Those projects and their contributors built the agent this package runs, and the credit is theirs — MIT licensed, with attribution preserved in [LICENSE](LICENSE) and in the `kilocode_change` markers throughout the source. This fork brings that agent to the BharatCode provider, rebrands it, and reconfigures the provider layer so bharatcode.ai is wired in from the start. We build on their work; we do not claim it.
Do I need a key if I sign in with my browser? -One or the other is enough. Browser sign-in stores a session; a pasted key stores a key. Both land in the extension backend's auth store and both go only to the provider you connected. +No. Approve VS Code on the BharatCode website. The extension backend stores the session; you don’t need to create or paste a key.
@@ -191,5 +183,5 @@ MIT — use it, modify it, ship it commercially, keeping the attribution and lic

-bharatcode.ai · Marketplace · Releases · Issues +bharatcode.ai · Marketplace · Releases · Issues
diff --git a/RELEASING.md b/RELEASING.md index 9c51103d..a387c7b7 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,73 +1,91 @@ -# Releasing BharatCode +# Preparing a BharatCode VS Code release -One script, one command, from the lab host: +## Extension identity + +The approved website sign-in extension identity is **`bharatcode.bharatcode-agent`**: publisher `bharatcode`, package name `bharatcode-agent`, display name `BharatCode Agent`. The owner approved this identity and publication of all eight verified platform packages on 2026-11-18, after Marketplace rejected the reserved `bharatcode-vscode` name. The Marketplace publisher was verified on 2026-11-18. This is not the older CLI-launcher listing `bharatcode.bharatcode`; do not overwrite that listing or Navya's listing. + +The verified parent candidate remains `bharatcode.bharatcode-vscode`. Keep its receipt, hashes and reuse-helper identity pins unchanged. Existing `bharatcode-vscode-*.vsix` filenames are retained as a packaging convention; the manifest, compiled lookup and receipt identify the proposed extension independently of its archive filename. Repository URLs are unchanged. + +The former `thenabbu.bharatcode-vscode` identity belongs to the upstream BharatCode fork. Keep its attribution and license notices, but do not use it for this organization's packages, install links or runtime lookups. A publisher change is a different extension ID, not an automatic update or transfer of VS Code's extension-scoped state. Do not remove old installations or migrate profiles without a separate, explicit migration plan. + +Internal `kilo-code.*` commands/settings and the bundled CLI's data paths remain unchanged. Website sign-in still uses the loopback callback; changing the Marketplace publisher does not change the OAuth client, issuer or redirect URI. + +## Candidate-only workflow + +Use `.github/workflows/oauth-candidate.yml` on `website-signin`. It has read-only repository permissions and builds artifacts only: no tags, releases, registry uploads or production deployment. + +The candidate workflow is dispatch-only: pushing preparation changes does not start an additional native build. + +After the final identity changes are reviewed, committed and pushed with explicit authorization, one dispatch runs the consolidated checks and all eight platform builds: ```bash -ssh lab 'bash /data/ssd240/bharatcode-vscode-workspace/scripts/release.sh ' +gh workflow run oauth-candidate.yml --repo BharatCode-ai/bharatcode-vscode --ref website-signin ``` -It bumps the version (every package.json still at the old literal → new version), gates with production esbuild, builds **win32-x64 and linux-x64** (CLI and VSIX each), audits each zip (no sourcemaps, platform-exclusive `extension/bin/` binary, LICENSE, manifest id/version), writes SHA256SUMS for those two, tags, and pushes `bc/main` + the tag. It does **not** build the other six platforms — those come from the per-platform recipe below. +Do not dispatch until that branch contains the intended final commit. The command above does not push local edits. Publication is a separate decision. Do not substitute `release.yml` (which creates commits/tags/releases) or `script/publish.ts` (which uploads to registries). -The full matrix (8 platforms, ~8 min each on the lab box): +The candidate version is `7.8.113`, supplied by `KILO_VERSION` to both the CLI and extension builds. The source manifest remains at the base version until the build overrides it; do not bulk-bump unrelated workspace packages for an identity-only change. No new version has been published by this preparation. -| Platform | CLI target (`KILO_CLI_TARGETS`) | binary | -|---|---|---| -| win32-x64 | `win32-x64` | `bin/bharatcode.exe` | -| win32-arm64 | `win32-arm64` | `bin/bharatcode.exe` | -| linux-x64 | `linux-x64` | `bin/bharatcode` | -| linux-arm64 | `linux-arm64` | `bin/bharatcode` | -| alpine-x64 | `linux-x64-musl` | `bin/bharatcode` | -| alpine-arm64 | `linux-arm64-musl` | `bin/bharatcode` | -| darwin-x64 | `darwin-x64` | `bin/bharatcode` | -| darwin-arm64 | `darwin-arm64` | `bin/bharatcode` | +### Packaging-only reuse of the verified backends + +For an approved extension-only change, the same single Linux job can skip all native backend builds: -## Building the remaining six platforms +```bash +gh workflow run oauth-candidate.yml --repo BharatCode-ai/bharatcode-vscode --ref website-signin -f reuse_verified_backends=true +``` + +Do not run this until the final identity/source changes and dispatch are explicitly approved. This input does not rename the extension. It reuses only artifact `14373729058` from run `44186017306`, attempt `1`, source `09bcc0764e142829534f94475e90f863cd5a7f70`. An expired/missing artifact fails closed; do not substitute another candidate. + +The parent artifact was uploaded with a three-day retention period and may expire before dispatch. A separately retained local copy can remain valid if its pinned receipt and all eight VSIX hashes still verify, but this workflow has no local-copy fallback. Supporting one would require separate review and approval; do not silently rebuild backends or substitute artifacts after expiry. + +`script/reuse-candidate.py` (under `packages/kilo-vscode/`) pins the original `candidate.json` SHA-256, verifies every parent VSIX hash and target, and extracts only the CLI binaries and fixed companion-resource paths into `CLI_DIST_DIR`. The existing build copies Tree-sitter WASMs, sandbox workers, Linux/Alpine relay and seccomp helpers, and their license from beside each parent binary. It does not regenerate these resources from newer sources. SDK/extension-host/webview bundles are rebuilt once; `vsce` creates eight fresh packages normally, with no ZIP byte patching or backend execution. -Run per platform (`win32-arm64`, `linux-arm64`, `alpine-x64`, `alpine-arm64`, `darwin-x64`, `darwin-arm64`), with `PATH` including both packages' `node_modules/.bin`: +The final shared identity audit still checks all eight packages. A separate equality check requires every packaged `bin/` entry's bytes, path, size and permissions to match its parent. Only then are `candidate.json` (kind `derived-backend-reuse`) and `SHA256SUMS` written. The derived receipt records the new source/run, fixed parent artifact/receipt and VSIX hashes, and per-target binary/resource hashes and inventories. It is not the original candidate receipt, a new native build, or a claim that VSIX ZIP bytes are reproducible. Original receipts/artifacts remain unchanged. This Python helper is CI/release tooling only; ordinary `build.ts` still has no Python requirement. + +## Checks before rebuilding + +From the repository root: ```bash -# packages/opencode — build the CLI for the target key from the table -KILO_CLI_TARGETS= KILO_SKIP_BUNDLED_BWRAP=1 bun script/build.ts -# stage the built binary (dist/@kilocode/cli-/bin/bharatcode[.exe]) into packages/kilo-vscode/bin/ - -# packages/kilo-vscode — build the VSIX for the platform -KILO_VSIX_TARGETS= KILO_SKIP_HEAVY=1 KILO_SKIP_BUNDLED_BWRAP=1 bun script/build.ts -mv out/*.vsix /data/ssd240/vsix-out/bharatcode-vscode--.vsix -# run the zip audit (same rules as the script), then append the file's sha256 to SHA256SUMS +bun script/check-workflows.ts +bun script/check-md-table-padding.ts +bun script/check-opencode-annotations.ts --worktree +bun script/check-opencode-annotations.ts --base 1e97696076bafea5ff4010627108ca50a162d9eb +bun script/extract-source-links.ts +bun script/extract-source-links.ts --check +python3 -B -m unittest discover -s packages/kilo-vscode/tests -p 'test_*.py' ``` -Then upload from anywhere with `gh`: +From `packages/kilo-vscode`: ```bash -gh release upload -R thenabbu/BharatCode-VSCode-Extension --clobber \ - /data/ssd240/vsix-out/bharatcode-vscode--.vsix ... SHA256SUMS +bun --config=/dev/null test --preload ./tests/setup/vscode-mock.ts ./tests/unit/bharatcode-website-signin.test.ts ./tests/unit/extension-arch.test.ts ./tests/unit/extension-identity.test.ts ./tests/unit/reuse-candidate-resources.test.ts ../opencode/test/plugin/bharatcode.test.ts +bun run check-kilocode-change ``` -(or `gh release create ... --notes-file notes.md` for a fresh release; the repo flag `-R` is required.) +The candidate workflow also checks formatting, host and webview types, lint and production bundling. CI and the publishing script require Python 3 for the common VSIX audit; ordinary developer builds do not. The build script checks the source manifest against the runtime identity before packaging. Do not set `KILO_SKIP_HEAVY` in the candidate workflow. + +## Eight-platform evidence + +| VSIX target | CLI target | Bundled executable | +|---|---|---| +| win32-x64 | win32-x64 | bin/bharatcode.exe | +| win32-arm64 | win32-arm64 | bin/bharatcode.exe | +| linux-x64 | linux-x64 | bin/bharatcode | +| linux-arm64 | linux-arm64 | bin/bharatcode | +| alpine-x64 | linux-x64-musl | bin/bharatcode | +| alpine-arm64 | linux-arm64-musl | bin/bharatcode | +| darwin-x64 | darwin-x64 | bin/bharatcode | +| darwin-arm64 | darwin-arm64 | bin/bharatcode | -## Version scheme +`packages/kilo-vscode/script/audit-vsix.py` checks the exact target set, JSON and XML publisher/name/version/platform, compiled extension identity, website sign-in entry point, platform-exclusive binary, no sourcemaps, and BharatCode/Kilo license attribution. Candidate receipt, GitHub release audit and registry preflight all use this same audit. A source-level test also compiles the runtime identity constant in production mode. -- Fork of Kilo Code. BharatCode releases are **plain semver `X.Y.Z`** — necessarily so, see below. -- **Scheme:** upstream's `major.minor` is preserved and OUR release counter lives in the patch, offset by 100. First release of base 7.8 is `7.8.101`, then `7.8.102`, `7.8.103`… An upstream sync that moves the base to 7.9 restarts at `7.9.101`. -- **Why not `7.8.17-bc.3`:** the Marketplace *upload* validator rejects any prerelease suffix (`-bc.3`), with "must be one to four numbers separated by a period". -- **Why not `7.8.17.3`:** `vsce package` — which BUILDS the vsix — refuses a fourth component outright (`Invalid extension "version"`). Verified by direct test: `7.8.17-bc.3` and `7.8.101` both pass vsce; `7.8.17.3` fails. -- **The intersection is a 3-part numeric version.** The 100 offset keeps 1–99 free for real upstream patch releases of that minor, so a future upstream `7.8.20` sorts BELOW our `7.8.101` and can never collide. -- Tags use the same string (`7.8.101`). `release.yml` derives `major.minor` from the root `package.json` and takes the highest **pure 3-segment numeric** tag as the counter — legacy `-bc.N` and 4-part tags are filtered out, since they would corrupt the count. -- The Zed `extension.toml` is NOT version-synced: Zed validates strict semver against upstream's own release URLs, so it keeps upstream's version and stays upstream-maintained. -- ~36 `package.json` files share the version string; the bump replaces the old literal once per file. The embedded CLI inherits it via `KILO_VERSION` (`packages/opencode/script/build.ts`), so extension About and `bharatcode --version` stay in sync. -- Tag the exact final release commit — if you amend after tagging, re-point the tag (`git tag -d` + re-create) or the push ships the old tree. +Only after every VSIX passes does the candidate job write `candidate.json` and `SHA256SUMS`. The receipt records source SHA, run ID/attempt, version, publisher, package name, full extension ID, target, size and SHA-256 for each file. Download and verify all eight hashes before installation tests or a separate publication approval. Static audits do not prove native binary execution or a real VS Code sign-in round trip. -## What a release must prove (the script enforces) +The earlier candidate from source `9afaf1c9b4ac6e7b96c8dc773292473663935de8` used publisher `thenabbu`. Its eight verified VSIXes are historical evidence, not release-ready packages for the new identity. Preserve them; do not edit, relabel, re-zip or reuse their receipts. Fresh extension packages from the final source commit are required; the packaging-only path above uses the later, explicitly pinned parent, never this obsolete candidate. -- tree clean, branch synced with origin, tag not taken -- esbuild production gate RC=0 -- zip audit per platform: zero `*.map`, only the target platform's binary under `extension/bin/`, `extension/LICENSE.txt` with the BharatCode line, manifest `thenabbu.bharatcode-vscode` at the new version -- sha256 recorded before anything else touches `out/` +## Isolated installation validation -## Pitfalls that bit once +Only after separate approval, use disposable VS Code user-data and extensions directories for the final candidate. Confirm the extension is registered as `bharatcode.bharatcode-agent`, command activation and version lookup work, browser sign-in/cancel/retry work without a model request, and the correct bundled backend starts on each supported OS/architecture. Never use real profiles or credentials for automated fixtures. -- **Never `git add -A` while builds run** — `bin/` holds the 150-290MB CLI binary; committing it makes GitHub reject the push (100MB hard limit). `bin/bharatcode` and `bin/bharatcode.exe` stay untracked; only `bin/kilodev*` are tracked. If a large blob sneaks into a commit, `git rm --cached ` (one pathspec per call — a missing second pathspec fails the whole command), amend, re-point the tag, push. -- The factory emits unsuffixed names (`bharatcode-vscode-.vsix`); the script renames to `-` suffixes on move. -- Builds rewrite `bun.lock` and flip `bin/kilodev.cmd` mode — fold lockfile drift into the release commit, and `git checkout --` the mode bit. -- `vsce` must be on PATH for the factory (`packages/kilo-vscode/node_modules/.bin`). -- No publish CI: builds run where the toolchain lives. Marketplace publish config stays intact for the future listing. +Do not delete or merge existing users' extension state to make a candidate pass. Marketplace identity consolidation alone does not establish migration compatibility with either older listing. diff --git a/SECURITY.md b/SECURITY.md index 7636cd3e..1f7e9575 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -34,6 +34,6 @@ Server mode is opt-in only. When enabled, set `KILO_SERVER_PASSWORD` to require ## Reporting security issues -We value the contributions of the security research community and recognize the importance of a coordinated approach to vulnerability disclosure. If you have discovered a security vulnerability, please report it privately through [GitHub Security Advisories](https://github.com/thenabbu/BharatCode-VSCode-Extension/security/advisories/new) for this repository. +We value the contributions of the security research community and recognize the importance of a coordinated approach to vulnerability disclosure. If you have discovered a security vulnerability, please report it privately through [GitHub Security Advisories](https://github.com/BharatCode-ai/bharatcode-vscode/security/advisories/new) for this repository. We will acknowledge your report and work with you on a fix and coordinated disclosure. Please do not open a public issue for vulnerabilities. diff --git a/bun.lock b/bun.lock index b648bb64..6904be02 100644 --- a/bun.lock +++ b/bun.lock @@ -447,7 +447,7 @@ }, }, "packages/kilo-vscode": { - "name": "bharatcode-vscode", + "name": "bharatcode-agent", "version": "7.8.17-bc.1", "dependencies": { "@anthropic-ai/sdk": "^0.39.0", @@ -2938,7 +2938,7 @@ "better-path-resolve": ["better-path-resolve@1.0.0", "", { "dependencies": { "is-windows": "^1.0.0" } }, "sha512-pbnl5XzGBdrFU/wT4jqmJVPn2B6UHPBOhzMQkY/SPUPB6QtUXtmBHBIwCbXJol93mOpGMnQyP/+BB19q04xj7g=="], - "bharatcode-vscode": ["bharatcode-vscode@workspace:packages/kilo-vscode"], + "bharatcode-agent": ["bharatcode-agent@workspace:packages/kilo-vscode"], "bignumber.js": ["bignumber.js@9.3.1", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="], @@ -5296,13 +5296,13 @@ "babel-plugin-module-resolver/glob": ["glob@9.3.5", "", { "dependencies": { "fs.realpath": "^1.0.0", "minimatch": "^8.0.2", "minipass": "^4.2.4", "path-scurry": "^1.6.1" } }, "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q=="], - "bharatcode-vscode/openai": ["openai@4.104.0", "", { "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", "abort-controller": "^3.0.0", "agentkeepalive": "^4.2.1", "form-data-encoder": "1.7.2", "formdata-node": "^4.3.2", "node-fetch": "^2.6.7" }, "peerDependencies": { "ws": "^8.18.0", "zod": "^3.23.8" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA=="], + "bharatcode-agent/openai": ["openai@4.104.0", "", { "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", "abort-controller": "^3.0.0", "agentkeepalive": "^4.2.1", "form-data-encoder": "1.7.2", "formdata-node": "^4.3.2", "node-fetch": "^2.6.7" }, "peerDependencies": { "ws": "^8.18.0", "zod": "^3.23.8" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA=="], - "bharatcode-vscode/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + "bharatcode-agent/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], - "bharatcode-vscode/web-tree-sitter": ["web-tree-sitter@0.24.7", "", {}, "sha512-CdC/TqVFbXqR+C51v38hv6wOPatKEUGxa39scAeFSm98wIhZxAYonhRQPSMmfZ2w7JDI0zQDdzdmgtNk06/krQ=="], + "bharatcode-agent/web-tree-sitter": ["web-tree-sitter@0.24.7", "", {}, "sha512-CdC/TqVFbXqR+C51v38hv6wOPatKEUGxa39scAeFSm98wIhZxAYonhRQPSMmfZ2w7JDI0zQDdzdmgtNk06/krQ=="], - "bharatcode-vscode/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + "bharatcode-agent/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], "body-parser/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], diff --git a/packages/kilo-docs/source-links.md b/packages/kilo-docs/source-links.md index fc831921..8e218993 100644 --- a/packages/kilo-docs/source-links.md +++ b/packages/kilo-docs/source-links.md @@ -21,6 +21,8 @@ - +- + - - @@ -32,16 +34,15 @@ - - - + - - - + - @@ -77,6 +78,12 @@ - +- + +- + +- + - - @@ -101,12 +108,6 @@ - -- - -- - -- - - - diff --git a/packages/kilo-vscode/AGENTS.md b/packages/kilo-vscode/AGENTS.md index 115ccd5a..c0d275b7 100644 --- a/packages/kilo-vscode/AGENTS.md +++ b/packages/kilo-vscode/AGENTS.md @@ -224,8 +224,10 @@ Generated screenshot baselines live under `packages/kilo-docs/public/img/screens ## Naming Conventions -- All VSCode commands must use `kilo-code.new.` prefix (not `kilo-code.`) -- All view IDs must use `kilo-code.new.` prefix, **except** the sidebar view which uses `kilo-code.SidebarProvider` to preserve user sidebar position when upgrading from the legacy extension +- All VS Code commands, views, panels, context keys, menus, task types and contributed settings use the unique `bharatcode-agent.` prefix. Do not register legacy aliases: Kilo and other forks can be installed alongside BharatCode Agent. +- Keep publisher `bharatcode`, package name `bharatcode-agent`, and extension ID `bharatcode.bharatcode-agent` unchanged for updates and access to existing extension storage/secrets. +- Read settings through `src/configuration.ts`. On activation it copies explicit `kilo-code.new.*` values into the new namespace at their original scopes, without deleting old values or overwriting new preferences. Failed copies retain a read fallback; completed scopes are marked so resetting a new preference cannot resurrect legacy values. +- This isolation intentionally replaces the old sidebar-ID exception: saved sidebar placement and custom shortcuts targeting old command IDs may need reassigning. Never rename existing global/workspace state keys, backend `KILO_*` variables, auth stores, or project/chat paths as part of UI namespace changes. ## Kilocode Change Markers diff --git a/packages/kilo-vscode/CHANGELOG.md b/packages/kilo-vscode/CHANGELOG.md index cecd6802..8b01a1a2 100644 --- a/packages/kilo-vscode/CHANGELOG.md +++ b/packages/kilo-vscode/CHANGELOG.md @@ -5,6 +5,13 @@ to 7.8.8 are inherited from the upstream Kilo Code project; Kilo-Org pull-request and commit links point to the original upstream repository and are kept as historical references. +## 7.8.115 + +- Recover from temporary BharatCode model-catalog failures with bounded retries, while honoring Retry-After and retaining the last working models. +- Show loading, connection and sign-in errors clearly. Retry the catalog from the model selector without restarting a session or replaying tools. +- Give BharatCode Agent its own commands, sidebar, panels and settings so it can coexist with other Kilo-derived extensions. Existing chats and sign-ins stay in place; saved preferences are copied without deleting the originals. +- Scope shared keyboard shortcuts to BharatCode surfaces. Custom shortcuts that referenced `kilo-code.new.*` may need reassignment to `bharatcode-agent.*`; the BharatCode commands remain available in the Command Palette. + ## 7.8.16 ## 7.8.15 diff --git a/packages/kilo-vscode/README.md b/packages/kilo-vscode/README.md index 427f923b..5f2e7853 100644 --- a/packages/kilo-vscode/README.md +++ b/packages/kilo-vscode/README.md @@ -1,12 +1,12 @@
-BharatCode for VS Code — the VS Code extension for bharatcode.ai +BharatCode Agent — the VS Code extension for bharatcode.ai
### Your coding agent, ready in one click -**BharatCode for VS Code** installs the whole agent for you — runtime, provider, endpoint and models included. Sign in, and you are writing with it. MIT licensed, no telemetry, no second account. +**BharatCode Agent** installs the whole agent for you — runtime, provider, endpoint and models included. Sign in, and you are writing with it. MIT licensed, no telemetry, no second account.
@@ -18,17 +18,9 @@ **2. Open a folder.** `File → Open Folder`. Your project is what the agent reads and edits. -**3. Sign in.** BharatCode greets you on first launch with **both** ways in: +**3. Select Sign in with BharatCode.** Your browser opens the BharatCode website. Sign in if needed, approve access, then return to VS Code. No API key or model request is needed for setup. -| | **Sign in with BharatCode** | **API key** | -|---|---|---| -| **Best for** | Nearly everyone | Scripts, shared machines, CI | -| **How** | A browser tab opens; click approve; done | Paste a key from your bharatcode.ai account | -| **Typing** | None | One paste | - -Either path works on first run. Your credential stays in the extension backend, out of `settings.json` and out of your repo. - -Missed the prompt? `BharatCode: Connect Account` brings it back. +You can also run `BharatCode: Sign In` from the Command Palette. Already connected? Your existing connection keeps working. That is the entire setup: the base URL, provider, endpoint and model list all come preconfigured. @@ -58,7 +50,7 @@ Two models ship with your BharatCode account, and the extension wires both up fo | Model | Context | Best at | |---|---|---| -| `qwen-3.8-27b` | 262k | Everyday edits and fast iteration | +| `glm-5.3-flash` | 262k | Everyday edits and fast iteration | | `deepseek-v4.1-flash` | 1M | Whole-repo reasoning and long sessions | Both come from one OpenAI-compatible endpoint at `https://bharatcode.ai/api/model/v1`, and the list is read live from it. @@ -71,12 +63,12 @@ Both come from one OpenAI-compatible endpoint at `https://bharatcode.ai/api/mode A fork of [Kilo Code](https://github.com/Kilo-Org/kilocode), itself a fork of [OpenCode](https://github.com/anomalyco/opencode). Those projects and their contributors built the agent this package runs, and the credit is theirs — MIT licensed, attribution preserved in the licence. This fork brings that agent to the BharatCode provider and reconfigures the provider layer so bharatcode.ai is wired in from the start. -Read-only questions, bug reports and feature ideas: [GitHub Issues](https://github.com/thenabbu/BharatCode-VSCode-Extension/issues). Full docs, contribution guide and privacy statement are in the [repository](https://github.com/thenabbu/BharatCode-VSCode-Extension). +Read-only questions, bug reports and feature ideas: [GitHub Issues](https://github.com/BharatCode-ai/bharatcode-vscode/issues). Full docs, contribution guide and privacy statement are in the [repository](https://github.com/BharatCode-ai/bharatcode-vscode). ## License -[MIT](https://github.com/thenabbu/BharatCode-VSCode-Extension/blob/bc/main/LICENSE) — use it, modify it, ship it commercially, keeping the attribution and licence notices. +[MIT](https://github.com/BharatCode-ai/bharatcode-vscode/blob/bc/main/LICENSE) — use it, modify it, ship it commercially, keeping the attribution and licence notices. diff --git a/packages/kilo-vscode/package.json b/packages/kilo-vscode/package.json index 3202a49c..988d21e6 100644 --- a/packages/kilo-vscode/package.json +++ b/packages/kilo-vscode/package.json @@ -1,22 +1,22 @@ { - "name": "bharatcode-vscode", - "displayName": "BharatCode for VS Code", + "name": "bharatcode-agent", + "displayName": "BharatCode Agent", "description": "The VS Code extension for BharatCode (bharatcode.ai). Sign in and the agent runs - the provider, endpoint and models are configured for you, so there is nothing to set up by hand.", - "version": "7.8.112", + "version": "7.8.115", "icon": "assets/icons/logo-outline-black.png", "galleryBanner": { "color": "#111113", "theme": "dark" }, - "publisher": "thenabbu", + "publisher": "bharatcode", "repository": { "type": "git", - "url": "https://github.com/thenabbu/BharatCode-VSCode-Extension", + "url": "https://github.com/BharatCode-ai/bharatcode-vscode", "directory": "packages/kilo-vscode" }, - "homepage": "https://github.com/thenabbu/BharatCode-VSCode-Extension", + "homepage": "https://github.com/BharatCode-ai/bharatcode-vscode", "bugs": { - "url": "https://github.com/thenabbu/BharatCode-VSCode-Extension" + "url": "https://github.com/BharatCode-ai/bharatcode-vscode/issues" }, "engines": { "vscode": "^1.105.1" @@ -59,7 +59,7 @@ }, "taskDefinitions": [ { - "type": "kilo-worktree-setup", + "type": "bharatcode-agent.worktree-setup", "properties": { "script": { "type": "string", @@ -75,7 +75,7 @@ "viewsContainers": { "activitybar": [ { - "id": "kilo-code-ActivityBar", + "id": "bharatcode-agent-ActivityBar", "title": "BharatCode", "icon": "assets/icons/kilo-light.png", "darkIcon": "assets/icons/kilo-dark.png" @@ -83,104 +83,104 @@ ] }, "views": { - "kilo-code-ActivityBar": [ + "bharatcode-agent-ActivityBar": [ { "type": "webview", - "id": "kilo-code.SidebarProvider", + "id": "bharatcode-agent.SidebarProvider", "name": "BharatCode" } ] }, "commands": [ { - "command": "kilo-code.new.setBharatcodeKey", - "title": "Connect Account", + "command": "bharatcode-agent.setBharatcodeKey", + "title": "Sign In", "category": "BharatCode" }, { - "command": "kilo-code.new.plusButtonClicked", + "command": "bharatcode-agent.plusButtonClicked", "title": "New Task", "category": "BharatCode", "icon": "$(add)" }, { - "command": "kilo-code.new.closeTask", + "command": "bharatcode-agent.closeTask", "title": "Close Task", "category": "BharatCode" }, { - "command": "kilo-code.new.closeAllTasks", + "command": "bharatcode-agent.closeAllTasks", "title": "Close All Tasks", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManagerOpen", + "command": "bharatcode-agent.agentManagerOpen", "title": "Agent Manager", "category": "BharatCode", "icon": "$(organization)" }, { - "command": "kilo-code.new.marketplaceButtonClicked", + "command": "bharatcode-agent.marketplaceButtonClicked", "title": "Marketplace", "category": "BharatCode", "icon": "$(extensions)" }, { - "command": "kilo-code.new.historyButtonClicked", + "command": "bharatcode-agent.historyButtonClicked", "title": "History", "category": "BharatCode", "icon": "$(history)" }, { - "command": "kilo-code.new.profileButtonClicked", + "command": "bharatcode-agent.profileButtonClicked", "title": "Profile", "category": "BharatCode", "icon": "$(account)" }, { - "command": "kilo-code.new.settingsButtonClicked", + "command": "bharatcode-agent.settingsButtonClicked", "title": "Settings", "category": "BharatCode", "icon": "$(settings-gear)" }, { - "command": "kilo-code.new.settingsSearch", + "command": "bharatcode-agent.settingsSearch", "title": "Search Settings", "category": "BharatCode", "icon": "$(search)" }, { - "command": "kilo-code.new.sidebarTitle.plusButtonClicked", + "command": "bharatcode-agent.sidebarTitle.plusButtonClicked", "title": "New Task", "icon": "$(add)" }, { - "command": "kilo-code.new.sidebarTitle.agentManagerOpen", + "command": "bharatcode-agent.sidebarTitle.agentManagerOpen", "title": "Agent Manager", "icon": "$(organization)" }, { - "command": "kilo-code.new.sidebarTitle.marketplaceButtonClicked", + "command": "bharatcode-agent.sidebarTitle.marketplaceButtonClicked", "title": "Marketplace", "icon": "$(extensions)" }, { - "command": "kilo-code.new.sidebarTitle.historyButtonClicked", + "command": "bharatcode-agent.sidebarTitle.historyButtonClicked", "title": "History", "icon": "$(history)" }, { - "command": "kilo-code.new.sidebarTitle.profileButtonClicked", + "command": "bharatcode-agent.sidebarTitle.profileButtonClicked", "title": "Profile", "icon": "$(account)" }, { - "command": "kilo-code.new.sidebarTitle.settingsButtonClicked", + "command": "bharatcode-agent.sidebarTitle.settingsButtonClicked", "title": "Settings", "icon": "$(settings-gear)" }, { - "command": "kilo-code.new.openInTab", + "command": "bharatcode-agent.openInTab", "title": "Open in Tab", "category": "BharatCode", "icon": { @@ -189,198 +189,198 @@ } }, { - "command": "kilo-code.new.openBrowser", + "command": "bharatcode-agent.openBrowser", "title": "Open Integrated Browser", "category": "BharatCode", "icon": "$(globe)" }, { - "command": "kilo-code.new.showChanges", + "command": "bharatcode-agent.showChanges", "title": "Show Changes", "category": "BharatCode" }, { - "command": "kilo-code.new.showMemory", + "command": "bharatcode-agent.showMemory", "title": "Show Project Memory", "category": "BharatCode" }, { - "command": "kilo-code.new.toggleMemory", + "command": "bharatcode-agent.toggleMemory", "title": "Toggle Project Memory", "category": "BharatCode" }, { - "command": "kilo-code.new.toggleCaffeination", + "command": "bharatcode-agent.toggleCaffeination", "title": "Toggle Keep Awake", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.previousSession", + "command": "bharatcode-agent.agentManager.previousSession", "title": "Agent Manager: Previous Session", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.nextSession", + "command": "bharatcode-agent.agentManager.nextSession", "title": "Agent Manager: Next Session", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.previousTab", + "command": "bharatcode-agent.agentManager.previousTab", "title": "Previous Session Tab", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.nextTab", + "command": "bharatcode-agent.agentManager.nextTab", "title": "Next Session Tab", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.previousTerminal", + "command": "bharatcode-agent.agentManager.previousTerminal", "title": "Agent Manager: Previous Terminal", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.nextTerminal", + "command": "bharatcode-agent.agentManager.nextTerminal", "title": "Agent Manager: Next Terminal", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.diagnostics", + "command": "bharatcode-agent.agentManager.diagnostics", "title": "Agent Manager: Show Worktree Diagnostics", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.search", + "command": "bharatcode-agent.agentManager.search", "title": "Agent Manager: Search Worktrees and Sessions", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.showTerminal", + "command": "bharatcode-agent.agentManager.showTerminal", "title": "Agent Manager: Focus Terminal", "category": "BharatCode", "icon": "$(terminal)" }, { - "command": "kilo-code.new.agentManager.runScript", + "command": "bharatcode-agent.agentManager.runScript", "title": "Agent Manager: Run Script", "category": "BharatCode", "icon": "$(play)" }, { - "command": "kilo-code.new.agentManager.toggleDiff", + "command": "bharatcode-agent.agentManager.toggleDiff", "title": "Agent Manager: Toggle Diff Panel", "category": "BharatCode", "icon": "$(diff)" }, { - "command": "kilo-code.new.agentManager.showShortcuts", + "command": "bharatcode-agent.agentManager.showShortcuts", "title": "Agent Manager: Show Keyboard Shortcuts", "category": "BharatCode", "icon": "$(keyboard)" }, { - "command": "kilo-code.new.agentManager.newTab", + "command": "bharatcode-agent.agentManager.newTab", "title": "Agent Manager: New Tab", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.newTerminalTab", + "command": "bharatcode-agent.agentManager.newTerminalTab", "title": "Agent Manager: New Terminal Tab", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.newSideTerminal", + "command": "bharatcode-agent.agentManager.newSideTerminal", "title": "Agent Manager: New Sidebar Terminal Tab", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.closeTab", + "command": "bharatcode-agent.agentManager.closeTab", "title": "Agent Manager: Close Tab", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.newWorktree", + "command": "bharatcode-agent.agentManager.newWorktree", "title": "Agent Manager: Configure New Worktree", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.quickWorktree", + "command": "bharatcode-agent.agentManager.quickWorktree", "title": "Agent Manager: New Worktree", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.openWorktree", + "command": "bharatcode-agent.agentManager.openWorktree", "title": "Agent Manager: Open Worktree", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.updateFromBase", + "command": "bharatcode-agent.agentManager.updateFromBase", "title": "Agent Manager: Update from base", "category": "BharatCode", - "enablement": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "enablement": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.openPR", + "command": "bharatcode-agent.agentManager.openPR", "title": "Agent Manager: Open Pull Request", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.closeWorktree", + "command": "bharatcode-agent.agentManager.closeWorktree", "title": "Agent Manager: Close Worktree", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.advancedWorktree", + "command": "bharatcode-agent.agentManager.advancedWorktree", "title": "Agent Manager: Configure New Worktree", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.jumpTo1", + "command": "bharatcode-agent.agentManager.jumpTo1", "title": "Agent Manager: Jump to Item 1", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.jumpTo2", + "command": "bharatcode-agent.agentManager.jumpTo2", "title": "Agent Manager: Jump to Item 2", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.jumpTo3", + "command": "bharatcode-agent.agentManager.jumpTo3", "title": "Agent Manager: Jump to Item 3", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.jumpTo4", + "command": "bharatcode-agent.agentManager.jumpTo4", "title": "Agent Manager: Jump to Item 4", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.jumpTo5", + "command": "bharatcode-agent.agentManager.jumpTo5", "title": "Agent Manager: Jump to Item 5", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.jumpTo6", + "command": "bharatcode-agent.agentManager.jumpTo6", "title": "Agent Manager: Jump to Item 6", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.jumpTo7", + "command": "bharatcode-agent.agentManager.jumpTo7", "title": "Agent Manager: Jump to Item 7", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.jumpTo8", + "command": "bharatcode-agent.agentManager.jumpTo8", "title": "Agent Manager: Jump to Item 8", "category": "BharatCode" }, { - "command": "kilo-code.new.agentManager.jumpTo9", + "command": "bharatcode-agent.agentManager.jumpTo9", "title": "Agent Manager: Jump to Item 9", "category": "BharatCode" }, { - "command": "kilo-code.new.generateCommitMessage", + "command": "bharatcode-agent.generateCommitMessage", "title": "Generate Commit Message", "category": "BharatCode", "icon": { @@ -389,469 +389,468 @@ } }, { - "command": "kilo-code.new.explainCode", + "command": "bharatcode-agent.explainCode", "title": "Explain Code", "category": "BharatCode" }, { - "command": "kilo-code.new.fixCode", + "command": "bharatcode-agent.fixCode", "title": "Fix Code", "category": "BharatCode" }, { - "command": "kilo-code.new.improveCode", + "command": "bharatcode-agent.improveCode", "title": "Improve Code", "category": "BharatCode" }, { - "command": "kilo-code.new.addToContext", + "command": "bharatcode-agent.addToContext", "title": "Add to Context", "category": "BharatCode" }, { - "command": "kilo-code.new.terminalAddToContext", + "command": "bharatcode-agent.terminalAddToContext", "title": "Add Terminal Content to Context", "category": "BharatCode" }, { - "command": "kilo-code.new.terminalFixCommand", + "command": "bharatcode-agent.terminalFixCommand", "title": "Fix This Command", "category": "BharatCode" }, { - "command": "kilo-code.new.terminalExplainCommand", + "command": "bharatcode-agent.terminalExplainCommand", "title": "Explain This Command", "category": "BharatCode" }, { - "command": "kilo-code.new.focusChatInput", + "command": "bharatcode-agent.focusChatInput", "title": "Focus Chat Input", "category": "BharatCode" }, { - "command": "kilo-code.new.toggleChatSearch", + "command": "bharatcode-agent.toggleChatSearch", "title": "Toggle Chat Search", "category": "BharatCode" }, { - "command": "kilo-code.new.cycleAgentMode", + "command": "bharatcode-agent.cycleAgentMode", "title": "Cycle Agent Mode", "category": "BharatCode" }, { - "command": "kilo-code.new.cyclePreviousAgentMode", + "command": "bharatcode-agent.cyclePreviousAgentMode", "title": "Cycle Previous Agent Mode", "category": "BharatCode" }, { - "command": "kilo-code.new.toggleAutoApprove", + "command": "bharatcode-agent.toggleAutoApprove", "title": "Toggle Auto-Approve", "category": "BharatCode" }, { - "command": "kilo-code.new.generateTerminalCommand", + "command": "bharatcode-agent.generateTerminalCommand", "title": "Generate Terminal Command", "category": "BharatCode" }, { - "command": "kilo-code.new.takeHeapSnapshot", + "command": "bharatcode-agent.takeHeapSnapshot", "title": "Take Heap Snapshot", "category": "BharatCode" }, { - "command": "kilo-code.new.reload", + "command": "bharatcode-agent.reload", "title": "Reload Config and Skills", "category": "BharatCode" } ], "submenus": [ { - "id": "kilo-code.new.editorContextMenu", + "id": "bharatcode-agent.editorContextMenu", "label": "BharatCode" }, { - "id": "kilo-code.new.terminalContextMenu", + "id": "bharatcode-agent.terminalContextMenu", "label": "BharatCode" } ], "menus": { "commandPalette": [ { - "command": "kilo-code.new.sidebarTitle.plusButtonClicked", + "command": "bharatcode-agent.sidebarTitle.plusButtonClicked", "when": "false" }, { - "command": "kilo-code.new.sidebarTitle.historyButtonClicked", + "command": "bharatcode-agent.sidebarTitle.historyButtonClicked", "when": "false" }, { - "command": "kilo-code.new.sidebarTitle.agentManagerOpen", + "command": "bharatcode-agent.sidebarTitle.agentManagerOpen", "when": "false" }, { - "command": "kilo-code.new.agentManager.advancedWorktree", + "command": "bharatcode-agent.agentManager.advancedWorktree", "when": "false" }, { - "command": "kilo-code.new.sidebarTitle.marketplaceButtonClicked", + "command": "bharatcode-agent.sidebarTitle.marketplaceButtonClicked", "when": "false" }, { - "command": "kilo-code.new.sidebarTitle.profileButtonClicked", + "command": "bharatcode-agent.sidebarTitle.profileButtonClicked", "when": "false" }, { - "command": "kilo-code.new.sidebarTitle.settingsButtonClicked", + "command": "bharatcode-agent.sidebarTitle.settingsButtonClicked", "when": "false" } ], "view/title": [ { - "command": "kilo-code.new.sidebarTitle.plusButtonClicked", + "command": "bharatcode-agent.sidebarTitle.plusButtonClicked", "group": "navigation@0", - "when": "view == kilo-code.SidebarProvider && !kilo-code.new.isCursor" + "when": "view == bharatcode-agent.SidebarProvider && !bharatcode-agent.isCursor" }, { - "command": "kilo-code.new.sidebarTitle.historyButtonClicked", + "command": "bharatcode-agent.sidebarTitle.historyButtonClicked", "group": "navigation@1", - "when": "view == kilo-code.SidebarProvider && !kilo-code.new.isCursor" + "when": "view == bharatcode-agent.SidebarProvider && !bharatcode-agent.isCursor" }, { - "command": "kilo-code.new.sidebarTitle.agentManagerOpen", + "command": "bharatcode-agent.sidebarTitle.agentManagerOpen", "group": "navigation@2", - "when": "view == kilo-code.SidebarProvider && !kilo-code.new.isCursor" + "when": "view == bharatcode-agent.SidebarProvider && !bharatcode-agent.isCursor" }, { - "command": "kilo-code.new.sidebarTitle.marketplaceButtonClicked", + "command": "bharatcode-agent.sidebarTitle.marketplaceButtonClicked", "group": "navigation@3", - "when": "view == kilo-code.SidebarProvider && !kilo-code.new.isCursor" + "when": "view == bharatcode-agent.SidebarProvider && !bharatcode-agent.isCursor" }, { - "command": "kilo-code.new.sidebarTitle.profileButtonClicked", + "command": "bharatcode-agent.sidebarTitle.profileButtonClicked", "group": "navigation@4", - "when": "view == kilo-code.SidebarProvider && !kilo-code.new.isCursor" + "when": "view == bharatcode-agent.SidebarProvider && !bharatcode-agent.isCursor" }, { - "command": "kilo-code.new.sidebarTitle.settingsButtonClicked", + "command": "bharatcode-agent.sidebarTitle.settingsButtonClicked", "group": "navigation@5", - "when": "view == kilo-code.SidebarProvider && !kilo-code.new.isCursor" + "when": "view == bharatcode-agent.SidebarProvider && !bharatcode-agent.isCursor" } ], "scm/title": [ { - "command": "kilo-code.new.generateCommitMessage", + "command": "bharatcode-agent.generateCommitMessage", "group": "navigation", "when": "scmProvider == git" } ], "scm/input": [ { - "command": "kilo-code.new.generateCommitMessage", + "command": "bharatcode-agent.generateCommitMessage", "group": "navigation", "when": "scmProvider == git" } ], "editor/title": [ { - "command": "kilo-code.new.openInTab", + "command": "bharatcode-agent.openInTab", "group": "navigation", "when": "true" }, { - "command": "kilo-code.new.plusButtonClicked", + "command": "bharatcode-agent.plusButtonClicked", "group": "navigation@0", - "when": "activeWebviewPanelId == kilo-code.new.TabPanel && !kilo-code.new.isCursor" + "when": "activeWebviewPanelId == bharatcode-agent.TabPanel && !bharatcode-agent.isCursor" }, { - "command": "kilo-code.new.historyButtonClicked", + "command": "bharatcode-agent.historyButtonClicked", "group": "navigation@1", - "when": "activeWebviewPanelId == kilo-code.new.TabPanel && !kilo-code.new.isCursor" + "when": "activeWebviewPanelId == bharatcode-agent.TabPanel && !bharatcode-agent.isCursor" }, { - "command": "kilo-code.new.profileButtonClicked", + "command": "bharatcode-agent.profileButtonClicked", "group": "navigation@2", - "when": "activeWebviewPanelId == kilo-code.new.TabPanel && !kilo-code.new.isCursor" + "when": "activeWebviewPanelId == bharatcode-agent.TabPanel && !bharatcode-agent.isCursor" }, { - "command": "kilo-code.new.settingsButtonClicked", + "command": "bharatcode-agent.settingsButtonClicked", "group": "navigation@3", - "when": "activeWebviewPanelId == kilo-code.new.TabPanel && !kilo-code.new.isCursor" + "when": "activeWebviewPanelId == bharatcode-agent.TabPanel && !bharatcode-agent.isCursor" } ], "editor/context": [ { - "submenu": "kilo-code.new.editorContextMenu", - "group": "1_kilocode" + "submenu": "bharatcode-agent.editorContextMenu", + "group": "1_bharatcode-agent" } ], - "kilo-code.new.editorContextMenu": [ + "bharatcode-agent.editorContextMenu": [ { - "command": "kilo-code.new.explainCode", + "command": "bharatcode-agent.explainCode", "group": "1_actions@1" }, { - "command": "kilo-code.new.fixCode", + "command": "bharatcode-agent.fixCode", "group": "1_actions@2" }, { - "command": "kilo-code.new.improveCode", + "command": "bharatcode-agent.improveCode", "group": "1_actions@3" }, { - "command": "kilo-code.new.addToContext", + "command": "bharatcode-agent.addToContext", "group": "1_actions@4" } ], "terminal/context": [ { - "submenu": "kilo-code.new.terminalContextMenu", - "group": "2_kilocode" + "submenu": "bharatcode-agent.terminalContextMenu", + "group": "2_bharatcode-agent" } ], - "kilo-code.new.terminalContextMenu": [ + "bharatcode-agent.terminalContextMenu": [ { - "command": "kilo-code.new.terminalAddToContext", + "command": "bharatcode-agent.terminalAddToContext", "group": "1_actions@1" }, { - "command": "kilo-code.new.terminalFixCommand", + "command": "bharatcode-agent.terminalFixCommand", "group": "1_actions@2" }, { - "command": "kilo-code.new.terminalExplainCommand", + "command": "bharatcode-agent.terminalExplainCommand", "group": "1_actions@3" } ] }, "keybindings": [ { - "command": "kilo-code.new.focusChatInput", + "command": "bharatcode-agent.focusChatInput", "key": "ctrl+shift+a", - "mac": "cmd+shift+a" + "mac": "cmd+shift+a", + "when": "bharatcode-agent.sidebarFocused || activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' || activeWebviewPanelId == 'bharatcode-agent.TabPanel'" }, { - "command": "kilo-code.new.toggleAutoApprove", + "command": "bharatcode-agent.toggleAutoApprove", "key": "ctrl+alt+a", - "mac": "cmd+alt+a" + "mac": "cmd+alt+a", + "when": "bharatcode-agent.sidebarFocused || activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' || activeWebviewPanelId == 'bharatcode-agent.TabPanel'" }, { - "command": "kilo-code.new.generateTerminalCommand", + "command": "bharatcode-agent.generateTerminalCommand", "key": "ctrl+shift+g", - "mac": "cmd+shift+g" + "mac": "cmd+shift+g", + "when": "bharatcode-agent.sidebarFocused || activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' || activeWebviewPanelId == 'bharatcode-agent.TabPanel'" }, { - "command": "-workbench.actions.view.problems", + "command": "bharatcode-agent.agentManagerOpen", "key": "ctrl+shift+m", - "mac": "cmd+shift+m" + "mac": "cmd+shift+m", + "when": "bharatcode-agent.sidebarFocused || activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' || activeWebviewPanelId == 'bharatcode-agent.TabPanel'" }, { - "command": "kilo-code.new.agentManagerOpen", - "key": "ctrl+shift+m", - "mac": "cmd+shift+m" - }, - { - "command": "kilo-code.new.addToContext", + "command": "bharatcode-agent.addToContext", "key": "ctrl+k ctrl+a", "mac": "cmd+k cmd+a", "when": "editorTextFocus && editorHasSelection" }, { - "command": "kilo-code.new.agentManager.previousSession", + "command": "bharatcode-agent.agentManager.previousSession", "key": "ctrl+alt+up", "mac": "cmd+alt+up", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.nextSession", + "command": "bharatcode-agent.agentManager.nextSession", "key": "ctrl+alt+down", "mac": "cmd+alt+down", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.previousTab", + "command": "bharatcode-agent.agentManager.previousTab", "key": "ctrl+alt+left", "mac": "cmd+alt+left", - "when": "kilo-code.new.sidebarFocused || activeWebviewPanelId == 'kilo-code.new.TabPanel' || activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "bharatcode-agent.sidebarFocused || activeWebviewPanelId == 'bharatcode-agent.TabPanel' || activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.nextTab", + "command": "bharatcode-agent.agentManager.nextTab", "key": "ctrl+alt+right", "mac": "cmd+alt+right", - "when": "kilo-code.new.sidebarFocused || activeWebviewPanelId == 'kilo-code.new.TabPanel' || activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "bharatcode-agent.sidebarFocused || activeWebviewPanelId == 'bharatcode-agent.TabPanel' || activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.previousTerminal", + "command": "bharatcode-agent.agentManager.previousTerminal", "key": "ctrl+shift+[", "mac": "cmd+shift+[", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.nextTerminal", + "command": "bharatcode-agent.agentManager.nextTerminal", "key": "ctrl+shift+]", "mac": "cmd+shift+]", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.search", + "command": "bharatcode-agent.agentManager.search", "key": "ctrl+f", "mac": "cmd+f", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && !terminalFocus" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && !terminalFocus" }, { - "command": "kilo-code.new.agentManager.showTerminal", + "command": "bharatcode-agent.agentManager.showTerminal", "key": "ctrl+/", "mac": "cmd+/", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && !kilo-code.new.sidebarFocused" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && !bharatcode-agent.sidebarFocused" }, { - "command": "kilo-code.new.agentManager.runScript", + "command": "bharatcode-agent.agentManager.runScript", "key": "ctrl+e", "mac": "cmd+e", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && (isMac || !terminalFocus)" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && (isMac || !terminalFocus)" }, { - "command": "kilo-code.new.agentManager.toggleDiff", + "command": "bharatcode-agent.agentManager.toggleDiff", "key": "ctrl+d", "mac": "cmd+d", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.showShortcuts", + "command": "bharatcode-agent.agentManager.showShortcuts", "key": "ctrl+shift+/", "mac": "cmd+shift+/", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.newTab", + "command": "bharatcode-agent.agentManager.newTab", "key": "ctrl+t", "mac": "cmd+t", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && !kilo-code.new.agentManagerSideTerminalFocused" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && !bharatcode-agent.agentManagerSideTerminalFocused" }, { - "command": "kilo-code.new.agentManager.newTerminalTab", + "command": "bharatcode-agent.agentManager.newTerminalTab", "key": "ctrl+shift+t", "mac": "cmd+shift+t", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && !kilo-code.new.agentManagerSideTerminalFocused" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && !bharatcode-agent.agentManagerSideTerminalFocused" }, { - "command": "kilo-code.new.agentManager.newSideTerminal", + "command": "bharatcode-agent.agentManager.newSideTerminal", "key": "ctrl+t", "mac": "cmd+t", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && kilo-code.new.agentManagerSideTerminalFocused" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && bharatcode-agent.agentManagerSideTerminalFocused" }, { - "command": "kilo-code.new.agentManager.closeTab", + "command": "bharatcode-agent.agentManager.closeTab", "key": "ctrl+w", "mac": "cmd+w", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.newWorktree", + "command": "bharatcode-agent.agentManager.newWorktree", "key": "ctrl+n", "mac": "cmd+n", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.quickWorktree", + "command": "bharatcode-agent.agentManager.quickWorktree", "key": "ctrl+shift+n", "mac": "cmd+shift+n", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.openWorktree", + "command": "bharatcode-agent.agentManager.openWorktree", "key": "ctrl+shift+o", "mac": "cmd+shift+o", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.openPR", + "command": "bharatcode-agent.agentManager.openPR", "key": "ctrl+shift+r", "mac": "cmd+shift+r", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.closeWorktree", + "command": "bharatcode-agent.agentManager.closeWorktree", "key": "ctrl+shift+w", "mac": "cmd+shift+w", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.jumpTo1", + "command": "bharatcode-agent.agentManager.jumpTo1", "key": "ctrl+1", "mac": "cmd+1", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.jumpTo2", + "command": "bharatcode-agent.agentManager.jumpTo2", "key": "ctrl+2", "mac": "cmd+2", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.jumpTo3", + "command": "bharatcode-agent.agentManager.jumpTo3", "key": "ctrl+3", "mac": "cmd+3", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.jumpTo4", + "command": "bharatcode-agent.agentManager.jumpTo4", "key": "ctrl+4", "mac": "cmd+4", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.jumpTo5", + "command": "bharatcode-agent.agentManager.jumpTo5", "key": "ctrl+5", "mac": "cmd+5", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.jumpTo6", + "command": "bharatcode-agent.agentManager.jumpTo6", "key": "ctrl+6", "mac": "cmd+6", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.jumpTo7", + "command": "bharatcode-agent.agentManager.jumpTo7", "key": "ctrl+7", "mac": "cmd+7", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.jumpTo8", + "command": "bharatcode-agent.agentManager.jumpTo8", "key": "ctrl+8", "mac": "cmd+8", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.agentManager.jumpTo9", + "command": "bharatcode-agent.agentManager.jumpTo9", "key": "ctrl+9", "mac": "cmd+9", - "when": "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'" }, { - "command": "kilo-code.new.cycleAgentMode", + "command": "bharatcode-agent.cycleAgentMode", "key": "ctrl+.", "mac": "cmd+.", - "when": "kilo-code.new.sidebarFocused || activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' || activeWebviewPanelId == 'kilo-code.new.TabPanel'" + "when": "bharatcode-agent.sidebarFocused || activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' || activeWebviewPanelId == 'bharatcode-agent.TabPanel'" }, { - "command": "kilo-code.new.cyclePreviousAgentMode", + "command": "bharatcode-agent.cyclePreviousAgentMode", "key": "ctrl+shift+.", "mac": "cmd+shift+.", - "when": "kilo-code.new.sidebarFocused || activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' || activeWebviewPanelId == 'kilo-code.new.TabPanel'" + "when": "bharatcode-agent.sidebarFocused || activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' || activeWebviewPanelId == 'bharatcode-agent.TabPanel'" }, { - "command": "kilo-code.new.settingsSearch", + "command": "bharatcode-agent.settingsSearch", "key": "ctrl+f", "mac": "cmd+f", - "when": "activeWebviewPanelId == 'kilo-code.new.settingsPanel'" + "when": "activeWebviewPanelId == 'bharatcode-agent.settingsPanel'" } ], "configuration": { "title": "BharatCode", "properties": { - "kilo-code.new.language": { + "bharatcode-agent.language": { "type": "string", "default": "", "description": "Override the UI language for BharatCode (e.g. en, de, ja). Empty means use VS Code's display language.", @@ -904,7 +903,7 @@ "فارسی" ] }, - "kilo-code.new.languageCommitMessage": { + "bharatcode-agent.languageCommitMessage": { "type": "string", "default": "sync", "description": "Language used for AI-generated commit messages. Choose 'sync' to follow the BharatCode UI language, or select a specific language.", @@ -957,53 +956,53 @@ "فارسی" ] }, - "kilo-code.new.model.providerID": { + "bharatcode-agent.model.providerID": { "type": "string", "default": "bharatcode", "description": "Default model provider ID for new sessions" }, - "kilo-code.new.model.modelID": { + "bharatcode-agent.model.modelID": { "type": "string", "default": "qwen-3.8-27b", "description": "Default model ID for new sessions" }, - "kilo-code.new.agentManager.autoBranchNaming": { + "bharatcode-agent.agentManager.autoBranchNaming": { "type": "boolean", "default": true, "scope": "application", "description": "Automatically name new Agent Manager branches when the conversation describes a clear task. Explicitly named and published branches are never renamed." }, - "kilo-code.new.agentManager.branchPrefix": { + "bharatcode-agent.agentManager.branchPrefix": { "type": "string", "default": "", "scope": "application", "description": "Prefix for automatically named Agent Manager branches, for example 'marius/' or 'feature/'. Explicit branch names are unchanged." }, - "kilo-code.new.agentManager.worktreePool": { + "bharatcode-agent.agentManager.worktreePool": { "type": "boolean", "default": true, "scope": "application", "description": "Pre-warm a ready worktree in the background so new Agent Manager sessions start faster. Uses extra disk space equal to one checkout per open project. Turn off to create worktrees only on demand." }, - "kilo-code.new.experimental.browserAutomation": { + "bharatcode-agent.experimental.browserAutomation": { "type": "boolean", "default": false, "scope": "application", "description": "Enable the experimental Integrated Browser panel and browser_open tool in Agent Manager." }, - "kilo-code.new.experimental.conversationPromptHistory": { + "bharatcode-agent.experimental.conversationPromptHistory": { "type": "boolean", "default": false, "scope": "application", "description": "Keep the prompt input history (ArrowUp/ArrowDown recall) separate for each conversation instead of sharing one history across all conversations." }, - "kilo-code.new.experimental.claudeMigration": { + "bharatcode-agent.experimental.claudeMigration": { "type": "boolean", "default": false, "scope": "application", "description": "Experimental one-time import of supported global Claude Code instructions, simple skills, and disabled MCP definitions into BharatCode. The original Claude files are never changed." }, - "kilo-code.new.agentManager.terminalButtonDestination": { + "bharatcode-agent.agentManager.terminalButtonDestination": { "type": "string", "scope": "application", "default": "agentManager", @@ -1017,62 +1016,62 @@ ], "description": "Default destination for the Agent Manager terminal button and Focus Terminal keyboard shortcut. The terminal button's dropdown remembers its own choice per Agent Manager panel; this setting only applies to panels that never picked one." }, - "kilo-code.new.indexing.showButtonWhenDisabled": { + "bharatcode-agent.indexing.showButtonWhenDisabled": { "type": "boolean", "default": true, "scope": "application", "description": "Show the codebase indexing button below the prompt while indexing is disabled." }, - "kilo-code.new.claudeCodeCompat": { + "bharatcode-agent.claudeCodeCompat": { "type": "boolean", "default": false, "description": "Load CLAUDE.md instructions and skills from your Claude Code configuration directory into BharatCode sessions. Enable this if you want BharatCode to use your Claude Code instructions and skills." }, - "kilo-code.new.extraCaCerts": { + "bharatcode-agent.extraCaCerts": { "type": "string", "default": "", "description": "Absolute path to a PEM file containing extra CA certificates to trust when the BharatCode backend makes HTTPS requests (sets NODE_EXTRA_CA_CERTS on the CLI process). Use this if you're behind a corporate proxy that performs SSL inspection. Leave empty to rely on the OS trust store." }, - "kilo-code.new.autoApprove.enabled": { + "bharatcode-agent.autoApprove.enabled": { "type": "boolean", "default": false, "description": "Start BharatCode with the main auto-approve toggle enabled. When enabled, permission prompts are approved automatically. Sandbox escalation prompts are always excluded." }, - "kilo-code.new.maxCost": { + "bharatcode-agent.maxCost": { "type": "number", "default": 0, "minimum": 0, "description": "Show a non-blocking alert when a session exceeds this USD amount. Use whole dollars; set to 0 to disable." }, - "kilo-code.new.fontSize": { + "bharatcode-agent.fontSize": { "type": "number", "default": 13, "minimum": 10, "maximum": 24, "description": "Font size in pixels for the BharatCode webview UI." }, - "kilo-code.new.browserAutomation.enabled": { + "bharatcode-agent.browserAutomation.enabled": { "type": "boolean", "default": false, "description": "Enable browser automation powered by Playwright. When enabled, the AI agent can interact with web pages in a visible Chrome window." }, - "kilo-code.new.browserAutomation.useSystemChrome": { + "bharatcode-agent.browserAutomation.useSystemChrome": { "type": "boolean", "default": true, "description": "Use your system's installed Chrome browser instead of downloading a separate Chromium instance." }, - "kilo-code.new.browserAutomation.headless": { + "bharatcode-agent.browserAutomation.headless": { "type": "boolean", "default": false, "description": "Run browser automation in headless mode (no visible window). When disabled, you can watch the agent interact with the browser." }, - "kilo-code.new.agentManager.browser.useSystemChrome": { + "bharatcode-agent.agentManager.browser.useSystemChrome": { "type": "boolean", "default": true, "scope": "application", "description": "Use system-installed Google Chrome for the Integrated Browser. Disable only when a compatible Playwright Chromium browser is already installed." }, - "kilo-code.new.agentManager.browser.openLinksIn": { + "bharatcode-agent.agentManager.browser.openLinksIn": { "type": "string", "enum": [ "external", @@ -1086,22 +1085,22 @@ "scope": "application", "description": "Choose where web links open from BharatCode chats. Requires the experimental Integrated Browser." }, - "kilo-code.new.attention.enabled": { + "bharatcode-agent.attention.enabled": { "type": "boolean", "default": false, "description": "Play sounds when sessions complete, error, or need input" }, - "kilo-code.new.attention.notifications": { + "bharatcode-agent.attention.notifications": { "type": "boolean", "default": false, "description": "Show VS Code notifications when BharatCode completes a task or needs input. Notifications are suppressed while a BharatCode panel is active." }, - "kilo-code.new.attention.OSNotifications": { + "bharatcode-agent.attention.OSNotifications": { "type": "boolean", "default": false, "description": "Show native OS notification alerts when BharatCode completes a task or needs input while VS Code is not active." }, - "kilo-code.new.attention.sound": { + "bharatcode-agent.attention.sound": { "type": "string", "default": "default", "enum": [ @@ -1155,37 +1154,37 @@ ], "description": "Use different sounds for completion, input, and errors, or choose one sound for every event" }, - "kilo-code.new.showTaskTimeline": { + "bharatcode-agent.showTaskTimeline": { "type": "boolean", "default": true, "description": "Show the task timeline graph in the chat header" }, - "kilo-code.new.showShortcutHints": { + "bharatcode-agent.showShortcutHints": { "type": "boolean", "default": true, "description": "Show the keyboard shortcut that fits what you do now in the empty prompt, for example how to add selected code or return to the prompt." }, - "kilo-code.new.showTokenThroughput": { + "bharatcode-agent.showTokenThroughput": { "type": "boolean", "default": true, "description": "Show tokens-per-second (prompt-processing / text-generation) badges on assistant messages and the task header" }, - "kilo-code.new.showAutoApprovalReason": { + "bharatcode-agent.showAutoApprovalReason": { "type": "boolean", "default": true, "description": "Show a line on tool calls explaining why they were auto-approved (matched rule, agent default, YOLO mode, etc.)" }, - "kilo-code.new.chat.shiftTabCyclesVariant": { + "bharatcode-agent.chat.shiftTabCyclesVariant": { "type": "boolean", "default": true, "description": "Cycle through reasoning effort variants with Shift+Tab in prompt inputs. Disable to keep Shift+Tab for keyboard focus navigation." }, - "kilo-code.new.agentManager.pushFixes": { + "bharatcode-agent.agentManager.pushFixes": { "type": "boolean", "default": true, "description": "Agent Manager: when you send pull request CI failures or review comments to the agent, or update a worktree from its base, ask the agent to commit and push so the pull request updates. Permission prompts still apply. Disable to keep commits manual." }, - "kilo-code.new.agentWorkStyle": { + "bharatcode-agent.agentWorkStyle": { "type": "string", "scope": "application", "default": "unset", @@ -1203,12 +1202,12 @@ ], "description": "Preferred agent work style. Set to Unset to show the onboarding flow again." }, - "kilo-code.new.diff.renderMarkdown": { + "bharatcode-agent.diff.renderMarkdown": { "type": "boolean", "default": false, "description": "Render Markdown files in BharatCode diff viewers by default. Toggle this from a Markdown file header in the diff viewer." }, - "kilo-code.new.diff.style": { + "bharatcode-agent.diff.style": { "type": "string", "enum": [ "unified", diff --git a/packages/kilo-vscode/script/audit-vsix.py b/packages/kilo-vscode/script/audit-vsix.py new file mode 100644 index 00000000..f9053455 --- /dev/null +++ b/packages/kilo-vscode/script/audit-vsix.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Read-only VSIX audit, with optional checksums/receipt for a fresh candidate.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import xml.etree.ElementTree as ET +import zipfile + +PUBLISHER = "bharatcode" +NAME = "bharatcode-agent" +DISPLAY_NAME = "BharatCode Agent" +# Artifact filenames are a stable packaging convention, not the Marketplace ID. +ARTIFACT_PREFIX = "bharatcode-vscode" +IDENTITY = f"{PUBLISHER}.{NAME}" +TARGETS = ( + "win32-x64", "win32-arm64", "linux-x64", "linux-arm64", + "alpine-x64", "alpine-arm64", "darwin-x64", "darwin-arm64", +) + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def audit(file, target, version): + require(target in TARGETS, f"unknown target: {target}") + with zipfile.ZipFile(file) as archive: + names = archive.namelist() + require(len(names) == len(set(names)), "duplicate ZIP entries") + require(not any(name.endswith(".map") for name in names), "sourcemaps in VSIX") + manifest = json.loads(archive.read("extension/package.json")) + require(manifest["publisher"] == PUBLISHER and manifest["name"] == NAME, "package identity") + require(manifest.get("displayName") == DISPLAY_NAME, "package display name") + require(manifest["version"] == version, "package version") + xml = ET.fromstring(archive.read("extension.vsixmanifest")) + identity = xml.find("{*}Metadata/{*}Identity") + require(identity is not None, "missing VSIX XML identity") + for key, value in { + "Publisher": PUBLISHER, "Id": NAME, "Version": version, "TargetPlatform": target, + }.items(): + require(identity.get(key) == value, f"VSIX XML {key}") + require(xml.findtext("{*}Metadata/{*}DisplayName") == DISPLAY_NAME, "VSIX XML display name") + binary = "extension/bin/bharatcode" + (".exe" if target.startswith("win32-") else "") + other = "extension/bin/bharatcode" if binary.endswith(".exe") else binary + ".exe" + require(binary in names and other not in names, "platform binary") + license = archive.read("extension/LICENSE.txt").decode() + require("BharatCode modifications" in license and "Kilo Code" in license, "license attribution") + bundle = archive.read("extension/dist/extension.js") + require(IDENTITY.encode() in bundle, "compiled extension identity") + require(DISPLAY_NAME.encode() in bundle, "compiled display name") + require(b"Sign in with BharatCode" in bundle, "compiled website sign-in") + for name in names: + if name.startswith("extension/dist/") and name.endswith(".js"): + data = archive.read(name) + require(b"thenabbu.bharatcode-vscode" not in data, f"old publisher in {name}") + require(b"bharatcode.bharatcode-vscode" not in data, f"old extension identity in {name}") + require(not re.search(rb"bharatcode\.bharatcode(?![\w-])", data), f"CLI launcher identity in {name}") + + +def inspect(directory, version, targets=TARGETS, versioned=False): + require(len(targets) == len(set(targets)) and bool(targets), "duplicate or empty targets") + suffix = f"-{version}" if versioned else "" + expected = {f"{ARTIFACT_PREFIX}-{target}{suffix}.vsix": target for target in targets} + files = sorted(directory.glob("*.vsix")) + require({file.name for file in files} == set(expected), "unexpected or missing VSIX target set") + rows = [] + for file in files: + target = expected[file.name] + audit(file, target, version) + digest = hashlib.sha256() + with file.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + rows.append({"name": file.name, "target": target, "size": file.stat().st_size, "sha256": digest.hexdigest()}) + return rows + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--dir", type=Path, default=Path(__file__).resolve().parent.parent / "out") + parser.add_argument("--version", required=True) + parser.add_argument("--target", action="append", choices=TARGETS) + parser.add_argument("--versioned", action="store_true") + parser.add_argument("--checksums", action="store_true") + parser.add_argument("--receipt", action="store_true") + args = parser.parse_args() + rows = inspect(args.dir, args.version, args.target or TARGETS, args.versioned) + receipt = { + "version": args.version, "publisher": PUBLISHER, "name": NAME, + "extensionId": IDENTITY, "files": rows, + } + if args.receipt: + # Require CI provenance before writing any evidence. + receipt.update({ + "source": os.environ["GITHUB_SHA"], + "run": os.environ["GITHUB_RUN_ID"], + "attempt": os.environ["GITHUB_RUN_ATTEMPT"], + }) + require(re.fullmatch(r"[0-9a-f]{40}", receipt["source"]), "invalid source SHA") + require(receipt["run"].isdigit() and receipt["attempt"].isdigit(), "invalid run provenance") + (args.dir / "candidate.json").write_text(json.dumps(receipt, indent=2) + "\n") + if args.checksums or args.receipt: + (args.dir / "SHA256SUMS").write_text("".join(row["sha256"] + " " + row["name"] + "\n" for row in rows)) + print(json.dumps(receipt, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/packages/kilo-vscode/script/build.ts b/packages/kilo-vscode/script/build.ts index b3abd836..f5cad00f 100644 --- a/packages/kilo-vscode/script/build.ts +++ b/packages/kilo-vscode/script/build.ts @@ -8,9 +8,13 @@ import { copyTreeSitterResources, } from "../src/services/cli-backend/cli-resources" import { evidence as sbom } from "./sbom" +import { EXTENSION_ID } from "../src/constants" const packageJsonPath = join(import.meta.dir, "..", "package.json") const packageJson = await Bun.file(packageJsonPath).json() +if (EXTENSION_ID !== "bharatcode.bharatcode-agent" || `${packageJson.publisher}.${packageJson.name}` !== EXTENSION_ID) { + throw new Error("Refusing to package a different Marketplace identity") +} const version = process.env.KILO_VERSION ? process.env.KILO_VERSION : packageJson.version const prerelease = process.env.KILO_PRE_RELEASE === "true" diff --git a/packages/kilo-vscode/script/publish.ts b/packages/kilo-vscode/script/publish.ts index 23ffda3f..dcfeb001 100755 --- a/packages/kilo-vscode/script/publish.ts +++ b/packages/kilo-vscode/script/publish.ts @@ -41,6 +41,9 @@ for (const target of targets) { console.log(`\nFound ${vsixFiles.length} VSIX files`) +// Reject stale or relabelled packages before any irreversible upload. +await $`python3 ${join(import.meta.dir, "audit-vsix.py")} --dir ${outDir} --version ${Script.version}` + // CRA evidence is checked before the first irreversible Marketplace upload, not // after. Marketplace and Open VSX still receive only the VSIX; the sidecars are // published to the GitHub release, which is Kilo's SBOM record. diff --git a/packages/kilo-vscode/script/reuse-candidate.py b/packages/kilo-vscode/script/reuse-candidate.py new file mode 100644 index 00000000..ab16ecc1 --- /dev/null +++ b/packages/kilo-vscode/script/reuse-candidate.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Package-only reuse of one approved backend candidate; never execute its binaries.""" + +import argparse +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import stat +import zipfile + +spec = importlib.util.spec_from_file_location("audit_vsix", Path(__file__).with_name("audit-vsix.py")) +audit = importlib.util.module_from_spec(spec) +spec.loader.exec_module(audit) +require = audit.require + +REPOSITORY = "BharatCode-ai/bharatcode-vscode" +ARTIFACT = 14373729058 +RUN = "44186017306" +SOURCE = "09bcc0764e142829534f94475e90f863cd5a7f70" +VERSION = "7.8.113" +# Binds the complete reviewed eight-target VSIX size/hash list, not just a run name. +RECEIPT = "9543d01371adf81eef327f04d04f802fa6e73625aad21c72625a36f77deead84" +PREFIX = "extension/bin/" + + +def digest(stream): + value = hashlib.sha256() + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + value.update(chunk) + return value.hexdigest() + + +def checksum(file): + with file.open("rb") as stream: + return digest(stream) + + +def candidate(data): + require(hashlib.sha256(data).hexdigest() == RECEIPT, "unapproved parent receipt hash") + value = json.loads(data) + require(value["source"] == SOURCE and value["run"] == RUN and value["attempt"] == "1", "parent provenance") + require(value["version"] == VERSION and value["extensionId"] == "bharatcode.bharatcode-vscode", "parent identity/version") + rows = value["files"] + require(len(rows) == 8 and {row["target"] for row in rows} == set(audit.TARGETS), "parent target set") + for row in rows: + require(row["name"] == f"bharatcode-vscode-{row['target']}.vsix", "parent filename") + return value + + +def metadata(value): + require(value["id"] == ARTIFACT and value["expired"] is False, "wrong or expired parent artifact") + require(value["name"] == f"vscode-oauth-{SOURCE}", "parent artifact name") + require(str(value["workflow_run"]["id"]) == RUN and value["workflow_run"]["head_sha"] == SOURCE, "artifact run/source") + + +def regular(info): + mode = info.external_attr >> 16 + require(stat.S_IFMT(mode) in (0, stat.S_IFREG), f"non-regular ZIP entry: {info.filename}") + require(not info.flag_bits & 1, "encrypted ZIP entry") + return stat.S_IMODE(mode) + + +def members(archive, target): + names = archive.namelist() + require(len(names) == len(set(names)), "duplicate ZIP entries") + binary = "bharatcode.exe" if target.startswith("win32-") else "bharatcode" + required = {binary, "kilo-sandbox-mutation-worker.js", "tree-sitter/tree-sitter.wasm"} + if target.startswith(("linux-", "alpine-")): + required.update({"kilo-sandbox-network-relay.js", "kilo-sandbox-seccomp", "licenses/sandbox-runtime/LICENSE"}) + entries = [] + for info in archive.infolist(): + if not info.filename.startswith(PREFIX): + continue + name = info.filename.removeprefix(PREFIX) + require(name in required or re.fullmatch(r"tree-sitter/tree-sitter-[a-z0-9_]+\.wasm", name), f"unexpected backend path: {name}") + require(regular(info) in (0o644, 0o755), f"unsafe backend mode: {name}") + require(0 < info.file_size <= 400 * 1024 * 1024, f"invalid backend size: {name}") + entries.append(info) + require(required <= {info.filename.removeprefix(PREFIX) for info in entries}, "missing backend companion resources") + return sorted(entries, key=lambda info: info.filename) + + +def payload(file, target): + with zipfile.ZipFile(file) as archive: + rows = [] + for info in members(archive, target): + with archive.open(info) as stream: + rows.append({"path": info.filename.removeprefix(PREFIX), "size": info.file_size, + "mode": regular(info), "sha256": digest(stream)}) + return rows + + +def tree(rows): + return hashlib.sha256(json.dumps(rows, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +def validate(root): + value = candidate((root / "candidate.json").read_bytes()) + require({file.name for file in root.glob("*.vsix")} == {row["name"] for row in value["files"]}, "parent VSIX set") + for row in value["files"]: + file = root / row["name"] + require(not file.is_symlink() and file.stat().st_size == row["size"] and checksum(file) == row["sha256"], f"parent VSIX hash: {row['name']}") + expected = "".join(row["sha256"] + " " + row["name"] + "\n" for row in value["files"]) + require((root / "SHA256SUMS").read_text() == expected, "parent SHA256SUMS") + return value + + +def directory(target): + name = target.replace("win32-", "windows-").replace("alpine-", "linux-") + return "@kilocode/cli-" + name + ("-musl" if target.startswith("alpine-") else "") + + +def prepare(archive, meta, root): + metadata(json.loads(meta.read_text())) + require(not root.exists() and not root.is_symlink(), "reuse destination must not exist") + with zipfile.ZipFile(archive) as source: + names = source.namelist() + require(len(names) == len(set(names)), "duplicate artifact entries") + require(source.getinfo("candidate.json").file_size < 64 * 1024, "oversized parent receipt") + value = candidate(source.read("candidate.json")) + expected = {row["name"]: row["size"] for row in value["files"]} + expected.update({"candidate.json": 64 * 1024, "SHA256SUMS": 64 * 1024}) + require(set(names) == set(expected), "unexpected artifact entries") + for info in source.infolist(): + regular(info) + require(info.file_size <= expected[info.filename], "oversized artifact entry") + parent = root / "parent" + parent.mkdir(parents=True) + # Never extract arbitrary paths, symlinks, extension code, or package metadata into the build tree. + for name in sorted(expected): + with source.open(name) as stream, (parent / name).open("xb") as output: + shutil.copyfileobj(stream, output) + validate(parent) + for row in value["files"]: + destination = root / "dist" / directory(row["target"]) / "bin" + with zipfile.ZipFile(parent / row["name"]) as source: + for info in members(source, row["target"]): + output = destination / info.filename.removeprefix(PREFIX) + output.parent.mkdir(parents=True, exist_ok=True) + with source.open(info) as stream, output.open("xb") as file: + shutil.copyfileobj(stream, file) + output.chmod(regular(info)) + print(f"Verified and staged {len(value['files'])} parent backend/resource trees; no binaries executed") + + +def verify(root, out): + parent = validate(root / "parent") + rows = audit.inspect(out, VERSION) + originals = {row["target"]: row for row in parent["files"]} + for row in rows: + original = originals[row["target"]] + before = payload(root / "parent" / original["name"], row["target"]) + after = payload(out / row["name"], row["target"]) + require(before == after, f"backend/resource bytes or permissions changed: {row['target']}") + binary = "bharatcode.exe" if row["target"].startswith("win32-") else "bharatcode" + row["parent"] = original + row["backend"] = { + "sha256": next(entry["sha256"] for entry in after if entry["path"] == binary), + "resourcesSha256": tree([entry for entry in after if entry["path"] != binary]), + "parentPayloadSha256": tree(before), "payloadSha256": tree(after), "entries": after, + } + receipt = { + "kind": "derived-backend-reuse", "version": VERSION, + "publisher": audit.PUBLISHER, "name": audit.NAME, "extensionId": audit.IDENTITY, + "source": os.environ["GITHUB_SHA"], "run": os.environ["GITHUB_RUN_ID"], + "attempt": os.environ["GITHUB_RUN_ATTEMPT"], + "parent": {"repository": REPOSITORY, "artifact": ARTIFACT, "source": SOURCE, + "run": RUN, "attempt": "1", "candidateSha256": RECEIPT}, + "files": rows, + } + require(re.fullmatch(r"[0-9a-f]{40}", receipt["source"]), "invalid source SHA") + require(receipt["run"].isdigit() and receipt["attempt"].isdigit() and receipt["run"] != RUN, "invalid derived run provenance") + # Do not issue any receipt/checksums until all eight identity and payload audits pass. + (out / "candidate.json").write_text(json.dumps(receipt, indent=2) + "\n") + (out / "SHA256SUMS").write_text("".join(row["sha256"] + " " + row["name"] + "\n" for row in rows)) + print(f"Audited {len(rows)} derived VSIXes: parent backend/resource bytes and permissions identical") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + stage = commands.add_parser("prepare") + stage.add_argument("--archive", type=Path, required=True) + stage.add_argument("--metadata", type=Path, required=True) + stage.add_argument("--root", type=Path, required=True) + check = commands.add_parser("verify") + check.add_argument("--root", type=Path, required=True) + check.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + if args.command == "prepare": + prepare(args.archive, args.metadata, args.root) + return + verify(args.root, args.out) + + +if __name__ == "__main__": + main() diff --git a/packages/kilo-vscode/src/DiffVirtualProvider.ts b/packages/kilo-vscode/src/DiffVirtualProvider.ts index b4d1c16b..ed852a7d 100644 --- a/packages/kilo-vscode/src/DiffVirtualProvider.ts +++ b/packages/kilo-vscode/src/DiffVirtualProvider.ts @@ -1,3 +1,4 @@ +import { configuration } from "./configuration" import * as vscode from "vscode" import { buildWebviewHtml, getWebviewFontSize } from "./utils" import { watchFontSizeConfig } from "./kilo-provider/font-size" @@ -48,7 +49,7 @@ export class DiffVirtualProvider implements vscode.Disposable { return } - const panel = vscode.window.createWebviewPanel("kilo-code.new.DiffVirtualPanel", title, vscode.ViewColumn.One, { + const panel = vscode.window.createWebviewPanel("bharatcode-agent.DiffVirtualPanel", title, vscode.ViewColumn.One, { enableScripts: true, retainContextWhenHidden: true, localResourceRoots: [this.extensionUri], @@ -81,7 +82,7 @@ export class DiffVirtualProvider implements vscode.Disposable { this.post({ type: "ready", vscodeLanguage: vscode.env.language, - languageOverride: vscode.workspace.getConfiguration("kilo-code.new").get("language"), + languageOverride: configuration("bharatcode-agent").get("language"), fontSize: getWebviewFontSize(), workspaceDirectory: getWorkspaceRoot(), }) diff --git a/packages/kilo-vscode/src/DocumentViewerProvider.ts b/packages/kilo-vscode/src/DocumentViewerProvider.ts index da11a6cf..f08a5e43 100644 --- a/packages/kilo-vscode/src/DocumentViewerProvider.ts +++ b/packages/kilo-vscode/src/DocumentViewerProvider.ts @@ -18,7 +18,7 @@ export interface DocumentViewerOptions { } export class DocumentViewerProvider implements vscode.Disposable { - public static readonly viewType = "kilo-code.new.DocumentsPanel" + public static readonly viewType = "bharatcode-agent.DocumentsPanel" private panel: vscode.WebviewPanel | undefined private pending: { file: string; sessionId?: string; directory?: string; line?: number; column?: number } | undefined private readonly contexts = new Map() diff --git a/packages/kilo-vscode/src/KiloProvider.ts b/packages/kilo-vscode/src/KiloProvider.ts index 7a073e07..f3fd938f 100644 --- a/packages/kilo-vscode/src/KiloProvider.ts +++ b/packages/kilo-vscode/src/KiloProvider.ts @@ -1,3 +1,4 @@ +import { configuration } from "./configuration" import * as path from "path" import { existsSync, readFileSync } from "fs" import * as vscode from "vscode" @@ -408,7 +409,7 @@ function withGlobalSpeechToTextMessage(message: unknown): unknown { } export class KiloProvider implements vscode.WebviewViewProvider, TelemetryPropertiesProvider { - public static readonly viewType = "kilo-code.SidebarProvider" + public static readonly viewType = "bharatcode-agent.SidebarProvider" private readonly instanceId = crypto.randomUUID() private webview: vscode.Webview | null = null @@ -432,6 +433,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper private storedProviderKeys: Record = {} /** Coalesce provider refreshes — at most one follow-up rerun when a request lands mid-flight. */ private providersRefresh: Promise | null = null + private catalogRefresh: { promise: Promise; current: () => boolean } | null = null private providersQueued = false private providersRetry = false private providersGeneration = 0 @@ -783,10 +785,10 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper private openMarketplacePanel(directory: unknown): void { if (typeof directory === "string" && directory) { - vscode.commands.executeCommand("kilo-code.new.marketplaceButtonClicked", directory) + vscode.commands.executeCommand("bharatcode-agent.marketplaceButtonClicked", directory) return } - vscode.commands.executeCommand("kilo-code.new.marketplaceButtonClicked", this.projectDirectory) + vscode.commands.executeCommand("bharatcode-agent.marketplaceButtonClicked", this.projectDirectory) } // Strip metadata unused by the webview to keep session switches fast. @@ -864,7 +866,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper // Re-send ready so the webview can recover after refresh. if (serverInfo) { - const langConfig = vscode.workspace.getConfiguration("kilo-code.new") + const langConfig = configuration("bharatcode-agent") this.postMessage({ type: "ready", serverInfo, @@ -933,7 +935,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper private setSidebarVisible(visible: boolean): void { this.setStatsVisible(visible) this.setStreamVisibility(visible) - vscode.commands.executeCommand("setContext", "kilo-code.new.sidebarVisible", visible) + vscode.commands.executeCommand("setContext", "bharatcode-agent.sidebarVisible", visible) if (!visible) this.opts.onHidden?.() if (!visible && this.opts.focusContext) { void vscode.commands.executeCommand("setContext", this.opts.focusContext, false) @@ -1287,7 +1289,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper board: (msg) => this.handleBoardMessage(msg), cancelBackgroundJob: (jobID, sessionID, requestID) => this.cancelBackgroundJob(jobID, sessionID, requestID), promoteBackgroundJob: (jobID, sessionID) => this.promoteBackgroundJob(jobID, sessionID), - caffeination: () => void vscode.commands.executeCommand("kilo-code.new.toggleCaffeination"), + caffeination: () => void vscode.commands.executeCommand("bharatcode-agent.toggleCaffeination"), }) ) { return @@ -1308,10 +1310,10 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper if ( await handleSidebarWorktreeMessage(message, { post: (msg) => this.postMessage(msg), - openAgentManager: () => vscode.commands.executeCommand("kilo-code.new.agentManagerOpen"), - openAdvancedWorktree: () => vscode.commands.executeCommand("kilo-code.new.agentManager.advancedWorktree"), + openAgentManager: () => vscode.commands.executeCommand("bharatcode-agent.agentManagerOpen"), + openAdvancedWorktree: () => vscode.commands.executeCommand("bharatcode-agent.agentManager.advancedWorktree"), openChanges: (sessionId?: string, turnId?: string) => this.openChanges(sessionId, turnId), - openProfile: () => vscode.commands.executeCommand("kilo-code.new.profileButtonClicked"), + openProfile: () => vscode.commands.executeCommand("bharatcode-agent.profileButtonClicked"), currentSessionId: this.currentSession?.id, createWorktree: async (baseBranch, branchName) => { await this.createWorktreeHandler?.(baseBranch, branchName) @@ -1431,7 +1433,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper // BharatCode connect entry point for the webview // (the welcome screen has no other way to start a new user). case "connectBharatcode": - void vscode.commands.executeCommand("kilo-code.new.setBharatcodeKey") + void vscode.commands.executeCommand("bharatcode-agent.setBharatcodeKey") break case "cancelLogin": this.loginAttempt++ @@ -1446,7 +1448,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper } break case "openSettingsPanel": - vscode.commands.executeCommand("kilo-code.new.settingsButtonClicked", message.tab, message.projectId) + vscode.commands.executeCommand("bharatcode-agent.settingsButtonClicked", message.tab, message.projectId) break case "openVSCodeSettings": vscode.commands.executeCommand("workbench.action.openSettings", message.query) @@ -1473,7 +1475,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper break case "openSubAgentViewer": vscode.commands.executeCommand( - "kilo-code.new.openSubAgentViewer", + "bharatcode-agent.openSubAgentViewer", message.sessionID, message.title, this.getWorkspaceDirectory(message.parentSessionID), @@ -1482,7 +1484,8 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper case "saveImage": return saveImage(this.getWorkspaceDirectory(this.currentSession?.id), message) case "requestProviders": - this.fetchAndSendProviders().catch((e) => console.error("[BharatCode] fetchAndSendProviders failed:", e)) + if (message.refresh === true) void this.refreshBharatcodeCatalog() + else this.fetchAndSendProviders().catch((e) => console.error("[BharatCode] fetchAndSendProviders failed:", e)) break case "connectProvider": case "authorizeProviderOAuth": @@ -1594,15 +1597,17 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper break case "openSettingsTab": if (message.tab === "indexing") { - await vscode.commands.executeCommand("kilo-code.new.openIndexingSettings") + await vscode.commands.executeCommand("bharatcode-agent.openIndexingSettings") } else if (message.tab === "agentBehaviour" && message.subtab === "mcpServers") { - await vscode.commands.executeCommand("kilo-code.new.openMcpSettings", message.focus) + await vscode.commands.executeCommand("bharatcode-agent.openMcpSettings", message.focus) } break case "setLanguage": - await vscode.workspace - .getConfiguration("kilo-code.new") - .update("language", message.locale || undefined, vscode.ConfigurationTarget.Global) + await configuration("bharatcode-agent").update( + "language", + message.locale || undefined, + vscode.ConfigurationTarget.Global, + ) this.connectionService.notifyLanguageChanged(message.locale as string) break case "requestFileSearch": @@ -1877,7 +1882,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper this.diffViewerProvider.openFromCommand(args) return } - await vscode.commands.executeCommand("kilo-code.new.showChanges", args) + await vscode.commands.executeCommand("bharatcode-agent.showChanges", args) } private handleEditorOpenMessage(message: Parameters[0]): boolean { @@ -2132,7 +2137,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper this.connectionState = this.connectionService.getConnectionState() if (serverInfo) { - const langConfig = vscode.workspace.getConfiguration("kilo-code.new") + const langConfig = configuration("bharatcode-agent") this.postMessage({ type: "ready", serverInfo, @@ -2817,6 +2822,43 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper this.postMessage({ type: "providersLoading" }) } + /** Explicit catalog-only retry, coalesced across duplicate webview clicks. */ + private refreshBharatcodeCatalog(): Promise { + if (this.catalogRefresh?.current()) return this.catalogRefresh.promise + const client = this.client + const directory = this.getWorkspaceDirectory() + let generation = this.providersGeneration + const current = () => + client === this.client && + generation === this.providersGeneration && + sameDirectory(directory, this.getWorkspaceDirectory()) + this.postMessage({ type: "providersRefreshing" }) + const task = (async () => { + if (!client) { + this.providersRetry = true + this.postMessage({ type: "providersLoadFailed", failure: { providerID: "bharatcode", kind: "network" } }) + return + } + try { + // A catalog retry must never dispose the backend or replay a running tool. + await client.provider.refresh({ providerID: "bharatcode", directory }, { throwOnError: true }) + if (!current()) return + const refresh = this.fetchAndSendProviders() + // Keep duplicate clicks coalesced through our own provider-list generation. + generation = this.providersGeneration + await refresh + } catch { + if (!current()) return + this.postMessage({ type: "providersLoadFailed", failure: { providerID: "bharatcode", kind: "network" } }) + } + })() + const done = task.finally(() => { + if (this.catalogRefresh?.promise === done) this.catalogRefresh = null + }) + this.catalogRefresh = { promise: done, current } + return done + } + /** Fetch providers and send to webview. Coalesced: at most one in-flight + one queued. */ private async fetchAndSendProviders(): Promise { const next = ++this.providersGeneration @@ -2836,6 +2878,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper if (!this.cachedProvidersMessage) this.providersRetry = true if (this.cachedProvidersMessage && generation === this.providersGeneration) this.postMessage(this.cachedProvidersMessage) + else this.postMessage({ type: "providersLoadFailed", failure: { providerID: "bharatcode", kind: "network" } }) return } try { @@ -2847,7 +2890,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper continue } this.storedProviderKeys = storedKeys - const settings = vscode.workspace.getConfiguration("kilo-code.new.model") + const settings = configuration("bharatcode-agent.model") const message = { type: "providersLoaded", providers: indexProvidersById(response.all), @@ -2881,6 +2924,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper // Keep backing off while the last loaded Kilo catalog was unavailable. const last = this.cachedProvidersMessage as { kiloUnavailable?: boolean } | null this.catalogRetry.update(last?.kiloUnavailable === true) + this.postMessage({ type: "providersLoadFailed", failure: { providerID: "bharatcode", kind: "network" } }) console.error("[BharatCode] KiloProvider: Failed to fetch providers:", error) } if (!this.providersQueued) return @@ -3660,7 +3704,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper /** Read attention settings from VS Code config and push to webview. */ private sendNotificationSettings(): void { - const attention = vscode.workspace.getConfiguration("kilo-code.new.attention") + const attention = configuration("bharatcode-agent.attention") this.postMessage({ type: "notificationSettingsLoaded", settings: { @@ -4340,23 +4384,21 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper } private maxCostSetting(): number { - return this.setMaxCost(vscode.workspace.getConfiguration("kilo-code.new").get("maxCost", 0)) + return this.setMaxCost(configuration("bharatcode-agent").get("maxCost", 0)) } private commitMessageLanguageSetting(): string { - return vscode.workspace.getConfiguration("kilo-code.new").get("languageCommitMessage", "sync") + return configuration("bharatcode-agent").get("languageCommitMessage", "sync") } private claudeMigrationSetting(): boolean { - return vscode.workspace.getConfiguration("kilo-code.new.experimental").get("claudeMigration", false) + return configuration("bharatcode-agent.experimental").get("claudeMigration", false) } private conversationPromptHistorySetting(): boolean { - return vscode.workspace - .getConfiguration("kilo-code.new.experimental") - .get("conversationPromptHistory", false) + return configuration("bharatcode-agent.experimental").get("conversationPromptHistory", false) } private browserAutomationSetting(): boolean { - return vscode.workspace.getConfiguration("kilo-code.new.experimental").get("browserAutomation", false) + return configuration("bharatcode-agent.experimental").get("browserAutomation", false) } private async sendIndexingSettings(projectId?: string) { @@ -4432,7 +4474,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper } private configSettings() { - const naming = vscode.workspace.getConfiguration("kilo-code.new.agentManager") + const naming = configuration("bharatcode-agent.agentManager") return { maxCost: this.maxCostSetting(), languageCommitMessage: this.commitMessageLanguageSetting(), @@ -5121,9 +5163,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper private async handleUpdateSetting(key: string, value: unknown): Promise { if (key === "maxCost") { const normalized = this.setMaxCost(value) - await vscode.workspace - .getConfiguration("kilo-code.new") - .update("maxCost", normalized, vscode.ConfigurationTarget.Global) + await configuration("bharatcode-agent").update("maxCost", normalized, vscode.ConfigurationTarget.Global) for (const sid of this.trackedSessionIds) { const oldLimit = this.activeAlerts.get(sid) if (oldLimit !== undefined) { @@ -5138,7 +5178,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper const { section, leaf } = buildSettingPath(key) if (section === "indexing" && !validIndexingSetting(leaf, value)) return if (section === "chat" && !validChatSetting(leaf, value)) return - const config = vscode.workspace.getConfiguration(`kilo-code.new${section ? `.${section}` : ""}`) + const config = configuration(`bharatcode-agent${section ? `.${section}` : ""}`) // Normalize a webview-side clear to `undefined` so VS Code removes the // key from settings.json rather than persisting a literal `null`. This // lets the runtime fall back to the resolved default. @@ -5148,9 +5188,9 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper } /** - * Reset all "kilo-code.new.*" extension settings to their defaults by reading + * Reset all "bharatcode-agent.*" extension settings to their defaults by reading * contributes.configuration from the extension's package.json at runtime. - * Only resets settings under the "kilo-code.new." namespace to avoid touching + * Only resets settings under the "bharatcode-agent." namespace to avoid touching * settings from the previous version of the extension which shares the same * extension ID and "kilo-code.*" namespace. */ @@ -5162,7 +5202,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper ) if (confirmed !== "Reset") return - const prefix = "kilo-code.new." + const prefix = "bharatcode-agent." const ext = vscode.extensions.getExtension(EXTENSION_ID) const properties = ext?.packageJSON?.contributes?.configuration?.properties as Record | undefined if (!properties) return @@ -5172,7 +5212,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper const parts = key.split(".") const section = parts.slice(0, -1).join(".") const leaf = parts[parts.length - 1]! - const config = vscode.workspace.getConfiguration(section) + const config = configuration(section) await config.update(leaf, undefined, vscode.ConfigurationTarget.Global) } @@ -5211,7 +5251,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper * Read the current browser automation settings and push them to the webview. */ private sendBrowserSettings(): void { - const config = vscode.workspace.getConfiguration("kilo-code.new.browserAutomation") + const config = configuration("bharatcode-agent.browserAutomation") this.postMessage({ type: "browserSettingsLoaded", settings: { @@ -5226,7 +5266,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper * Read the current Claude Code compatibility setting and push it to the webview. */ private sendClaudeCompatSetting(): void { - const enabled = vscode.workspace.getConfiguration("kilo-code.new").get("claudeCodeCompat", false) + const enabled = configuration("bharatcode-agent").get("claudeCodeCompat", false) this.postMessage({ type: "claudeCompatSettingLoaded", enabled: enabled ?? false, @@ -6195,7 +6235,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper return buildWebviewHtml(webview, { // The rail follows the physical workbench edge. RTL text direction must not move it between chat and code. sidebar: sidebar - ? vscode.workspace.getConfiguration("workbench").get("sideBar.location") === "right" + ? configuration("workbench").get("sideBar.location") === "right" ? "right" : "left" : undefined, diff --git a/packages/kilo-vscode/src/MarketplacePanelProvider.ts b/packages/kilo-vscode/src/MarketplacePanelProvider.ts index 2983d6d3..c8cc546f 100644 --- a/packages/kilo-vscode/src/MarketplacePanelProvider.ts +++ b/packages/kilo-vscode/src/MarketplacePanelProvider.ts @@ -1,3 +1,4 @@ +import { configuration } from "./configuration" import * as os from "os" import * as vscode from "vscode" import type { GlobalEvent, SessionStatus } from "@kilocode/sdk/v2/client" @@ -34,7 +35,7 @@ interface MarketplaceMessage { } export class MarketplacePanelProvider implements vscode.Disposable { - public static readonly viewType = "kilo-code.new.marketplacePanel" + public static readonly viewType = "bharatcode-agent.marketplacePanel" private panel: vscode.WebviewPanel | undefined private project: string | null = null @@ -201,7 +202,7 @@ export class MarketplacePanelProvider implements vscode.Disposable { if (!this.ready) return const info = this.connection.getServerInfo() if (info) { - const cfg = vscode.workspace.getConfiguration("kilo-code.new") + const cfg = configuration("bharatcode-agent") this.post({ type: "ready", serverInfo: info, diff --git a/packages/kilo-vscode/src/SettingsEditorProvider.ts b/packages/kilo-vscode/src/SettingsEditorProvider.ts index 94c039dd..45a9fdb3 100644 --- a/packages/kilo-vscode/src/SettingsEditorProvider.ts +++ b/packages/kilo-vscode/src/SettingsEditorProvider.ts @@ -51,9 +51,9 @@ export class SettingsEditorProvider implements vscode.Disposable { return resolvePanelProjectDirectory(active, vscode.workspace.workspaceFolders) } - /** Extract the PanelView from a viewType string like "kilo-code.new.settingsPanel". */ + /** Extract the PanelView from a viewType string like "bharatcode-agent.settingsPanel". */ static viewFromType(type: string): PanelView | undefined { - const match = type.match(/^kilo-code\.new\.(\w+)Panel$/) + const match = type.match(/^bharatcode-agent\.(\w+)Panel$/) if (!match) return undefined const view = match[1] as PanelView if (!(view in PANEL_TITLES)) return undefined @@ -85,7 +85,7 @@ export class SettingsEditorProvider implements vscode.Disposable { } const panel = vscode.window.createWebviewPanel( - `kilo-code.new.${view}Panel`, + `bharatcode-agent.${view}Panel`, PANEL_TITLES[view], vscode.ViewColumn.Active, { diff --git a/packages/kilo-vscode/src/SubAgentViewerProvider.ts b/packages/kilo-vscode/src/SubAgentViewerProvider.ts index 8f62d93b..387bd6bd 100644 --- a/packages/kilo-vscode/src/SubAgentViewerProvider.ts +++ b/packages/kilo-vscode/src/SubAgentViewerProvider.ts @@ -31,11 +31,16 @@ export class SubAgentViewerProvider implements vscode.Disposable { const label = title ? `Sub-agent: ${title}` : "Sub-agent Viewer" - const panel = vscode.window.createWebviewPanel("kilo-code.new.SubAgentViewerPanel", label, vscode.ViewColumn.One, { - enableScripts: true, - retainContextWhenHidden: true, - localResourceRoots: [this.extensionUri], - }) + const panel = vscode.window.createWebviewPanel( + "bharatcode-agent.SubAgentViewerPanel", + label, + vscode.ViewColumn.One, + { + enableScripts: true, + retainContextWhenHidden: true, + localResourceRoots: [this.extensionUri], + }, + ) panel.iconPath = { light: vscode.Uri.joinPath(this.extensionUri, "assets", "icons", "kilo-light.svg"), diff --git a/packages/kilo-vscode/src/agent-manager/AgentManagerProvider.ts b/packages/kilo-vscode/src/agent-manager/AgentManagerProvider.ts index 837b1a80..26d5118f 100644 --- a/packages/kilo-vscode/src/agent-manager/AgentManagerProvider.ts +++ b/packages/kilo-vscode/src/agent-manager/AgentManagerProvider.ts @@ -103,7 +103,7 @@ import { createBrowserLifecycle } from "./browser-lifecycle" import { handleSessionLifecycle } from "./session-lifecycle" import { isRestrictedRoot } from "./home-workspace" export class AgentManagerProvider implements Disposable { - public static readonly viewType = "kilo-code.new.AgentManagerPanel" + public static readonly viewType = "bharatcode-agent.AgentManagerPanel" private panel: PanelContext | undefined private outputChannel: OutputHandle private readonly registry: ProjectRegistry diff --git a/packages/kilo-vscode/src/agent-manager/SessionTerminalManager.ts b/packages/kilo-vscode/src/agent-manager/SessionTerminalManager.ts index dbb9627d..2ddf4f5d 100644 --- a/packages/kilo-vscode/src/agent-manager/SessionTerminalManager.ts +++ b/packages/kilo-vscode/src/agent-manager/SessionTerminalManager.ts @@ -61,7 +61,7 @@ export class SessionTerminalManager { host.onActiveTerminalChanged((terminal) => { const managed = terminal ? this.isManaged(terminal) : false if (terminal) this.panelOpen = true - void host.setContext("kilo-code.agentTerminalFocus", managed) + void host.setContext("bharatcode-agent.agentTerminalFocus", managed) }), ) @@ -238,7 +238,7 @@ export class SessionTerminalManager { } dispose(): void { - void this.host.setContext("kilo-code.agentTerminalFocus", false) + void this.host.setContext("bharatcode-agent.agentTerminalFocus", false) for (const entry of this.terminals.values()) entry.terminal.dispose() this.terminals.clear() for (const d of this.commandDisposables.values()) d.dispose() @@ -299,7 +299,7 @@ export class SessionTerminalManager { const active = this.host.activeTerminal() const managed = active ? this.isManaged(active) : false if (active) this.panelOpen = true - void this.host.setContext("kilo-code.agentTerminalFocus", managed) + void this.host.setContext("bharatcode-agent.agentTerminalFocus", managed) } private showOrCreate(key: string, cwd: string, name: string): void { diff --git a/packages/kilo-vscode/src/agent-manager/SetupScriptRunner.ts b/packages/kilo-vscode/src/agent-manager/SetupScriptRunner.ts index bbda9010..9b7a9e43 100644 --- a/packages/kilo-vscode/src/agent-manager/SetupScriptRunner.ts +++ b/packages/kilo-vscode/src/agent-manager/SetupScriptRunner.ts @@ -55,7 +55,7 @@ export function buildSetupTaskCommand(script: SetupScriptInfo): { command: strin */ export function setupTaskIdentity(config: SetupTaskConfig) { return { - definition: { type: "kilo-worktree-setup", script: config.command, worktree: config.cwd }, + definition: { type: "bharatcode-agent.worktree-setup", script: config.command, worktree: config.cwd }, name: `Worktree Setup (${path.basename(config.cwd)})`, } } diff --git a/packages/kilo-vscode/src/agent-manager/format-keybinding.ts b/packages/kilo-vscode/src/agent-manager/format-keybinding.ts index d46b632f..34839798 100644 --- a/packages/kilo-vscode/src/agent-manager/format-keybinding.ts +++ b/packages/kilo-vscode/src/agent-manager/format-keybinding.ts @@ -41,16 +41,16 @@ export function formatKeybinding(raw: string, mac: boolean): string { } /** Agent Manager command prefix for keybinding extraction. */ -const AM_PREFIX = "kilo-code.new.agentManager." +const AM_PREFIX = "bharatcode-agent.agentManager." /** Global commands whose keybindings are forwarded to the webview. */ const GLOBAL_KEYBINDINGS: Record = { - "kilo-code.new.agentManagerOpen": "agentManagerOpen", - "kilo-code.new.cycleAgentMode": "cycleAgentMode", - "kilo-code.new.cyclePreviousAgentMode": "cyclePreviousAgentMode", - "kilo-code.new.focusChatInput": "focusChatInput", - "kilo-code.new.addToContext": "addToContext", - "kilo-code.new.settingsSearch": "settingsSearch", + "bharatcode-agent.agentManagerOpen": "agentManagerOpen", + "bharatcode-agent.cycleAgentMode": "cycleAgentMode", + "bharatcode-agent.cyclePreviousAgentMode": "cyclePreviousAgentMode", + "bharatcode-agent.focusChatInput": "focusChatInput", + "bharatcode-agent.addToContext": "addToContext", + "bharatcode-agent.settingsSearch": "settingsSearch", } /** [binding name, command suffix, key after the cmd/ctrl modifier] */ @@ -66,7 +66,7 @@ const FALLBACKS: Array<[string, string, string]> = [ ] function addBinding(bindings: Record, name: string, value: string, when?: string): void { - if (name === "newTerminalTab" && when?.includes("!kilo-code.new.agentManagerSideTerminalFocused")) { + if (name === "newTerminalTab" && when?.includes("!bharatcode-agent.agentManagerSideTerminalFocused")) { bindings.newTerminalCenter = value return } diff --git a/packages/kilo-vscode/src/agent-manager/run/task.ts b/packages/kilo-vscode/src/agent-manager/run/task.ts index a12a15dd..3536d4a1 100644 --- a/packages/kilo-vscode/src/agent-manager/run/task.ts +++ b/packages/kilo-vscode/src/agent-manager/run/task.ts @@ -31,7 +31,7 @@ export async function startVscodeRunTask(config: RunTaskConfig, done: (exit: Run env: config.env, }) const task = new vscode.Task( - { type: "kilo-worktree-run" }, + { type: "bharatcode-agent.worktree-run" }, vscode.TaskScope.Workspace, `Run: ${config.branch}`, "BharatCode", diff --git a/packages/kilo-vscode/src/agent-manager/terminal-destination.ts b/packages/kilo-vscode/src/agent-manager/terminal-destination.ts index b2a8b3d3..b90885fd 100644 --- a/packages/kilo-vscode/src/agent-manager/terminal-destination.ts +++ b/packages/kilo-vscode/src/agent-manager/terminal-destination.ts @@ -1,3 +1,4 @@ +import { configuration, affectsConfiguration } from "../configuration" /** * Read and watch the user's Agent Manager terminal destination setting. * @@ -11,7 +12,7 @@ import * as vscode from "vscode" export type TerminalDestination = "vscode" | "agentManager" -const KEY = "kilo-code.new.agentManager.terminalButtonDestination" +const KEY = "bharatcode-agent.agentManager.terminalButtonDestination" /** Unknown values fall back to the VS Code terminal so a stale or * hand-edited setting never strands the user without a terminal. */ @@ -20,12 +21,12 @@ export function resolveTerminalDestination(value: unknown): TerminalDestination } export function readTerminalDestination(): TerminalDestination { - const config = vscode.workspace.getConfiguration("kilo-code.new.agentManager") + const config = configuration("bharatcode-agent.agentManager") return resolveTerminalDestination(config.get("terminalButtonDestination")) } async function writeTerminalDestination(destination: TerminalDestination): Promise { - const config = vscode.workspace.getConfiguration("kilo-code.new.agentManager") + const config = configuration("bharatcode-agent.agentManager") await config.update("terminalButtonDestination", destination, vscode.ConfigurationTarget.Global) } @@ -64,7 +65,7 @@ export function handleDestination( } export function affectsTerminalDestination(e: vscode.ConfigurationChangeEvent): boolean { - return e.affectsConfiguration(KEY) + return affectsConfiguration(e, KEY) } /** Subscribe to destination changes. Returns a cleanup function. */ diff --git a/packages/kilo-vscode/src/agent-manager/vscode-host.ts b/packages/kilo-vscode/src/agent-manager/vscode-host.ts index 52286409..ad116039 100644 --- a/packages/kilo-vscode/src/agent-manager/vscode-host.ts +++ b/packages/kilo-vscode/src/agent-manager/vscode-host.ts @@ -1,3 +1,4 @@ +import { configuration, affectsConfiguration } from "../configuration" /** * VS Code adapter implementing the Host interface. * @@ -67,7 +68,7 @@ export class VscodeHost implements Host { worktreeDirectories?: () => string[] }): PanelContext { const panel = vscode.window.createWebviewPanel( - "kilo-code.new.AgentManagerPanel", + "bharatcode-agent.AgentManagerPanel", "Agent Manager", vscode.ViewColumn.One, { @@ -142,9 +143,9 @@ export class VscodeHost implements Host { disableViewedRegistration: true, disableStatsPolling: true, focusTargetContext: { - prompt: "kilo-code.new.agentManagerPromptFocused", - mainTerminal: "kilo-code.new.agentManagerMainTerminalFocused", - sideTerminal: "kilo-code.new.agentManagerSideTerminalFocused", + prompt: "bharatcode-agent.agentManagerPromptFocused", + mainTerminal: "bharatcode-agent.agentManagerMainTerminalFocused", + sideTerminal: "bharatcode-agent.agentManagerSideTerminalFocused", }, onFocused: () => this.focus?.gained(), routeService: this.routes, @@ -409,7 +410,7 @@ export class VscodeHost implements Host { } browserAutomation(): boolean { - return vscode.workspace.getConfiguration("kilo-code.new.experimental").get("browserAutomation", false) + return configuration("bharatcode-agent.experimental").get("browserAutomation", false) } async approveBrowserNavigation(origin: string): Promise { @@ -422,7 +423,7 @@ export class VscodeHost implements Host { } worktreePool(): boolean { - return vscode.workspace.getConfiguration("kilo-code.new.agentManager").get("worktreePool", true) + return configuration("bharatcode-agent.agentManager").get("worktreePool", true) } readProjects(): unknown { @@ -455,7 +456,7 @@ export class VscodeHost implements Host { onDidChangeWorktreePool(cb: (enabled: boolean) => void): Disposable { return vscode.workspace.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("kilo-code.new.agentManager.worktreePool")) cb(this.worktreePool()) + if (affectsConfiguration(e, "bharatcode-agent.agentManager.worktreePool")) cb(this.worktreePool()) }) } @@ -464,7 +465,7 @@ export class VscodeHost implements Host { } autoBranchNaming(): { enabled: boolean; prefix: string } { - const cfg = vscode.workspace.getConfiguration("kilo-code.new.agentManager") + const cfg = configuration("bharatcode-agent.agentManager") return { enabled: cfg.get("autoBranchNaming", true), prefix: cfg.get("branchPrefix", ""), @@ -549,7 +550,7 @@ export class VscodeHost implements Host { } openSettings(tab?: string, projectId?: string): void { - void vscode.commands.executeCommand("kilo-code.new.settingsButtonClicked", tab, projectId) + void vscode.commands.executeCommand("bharatcode-agent.settingsButtonClicked", tab, projectId) } refreshGit(): void { diff --git a/packages/kilo-vscode/src/browser-links.ts b/packages/kilo-vscode/src/browser-links.ts index 9ecfcfef..5d5cc6b5 100644 --- a/packages/kilo-vscode/src/browser-links.ts +++ b/packages/kilo-vscode/src/browser-links.ts @@ -1,7 +1,8 @@ +import { configuration } from "./configuration" import * as vscode from "vscode" import { integratedBrowserLinkDestination } from "./services/browser-automation/chrome-setting" -const BROWSER_AUTOMATION = "kilo-code.new.experimental" +const BROWSER_AUTOMATION = "bharatcode-agent.experimental" /** True when the URL is an http(s) web link, which is all the browser handles. */ export function isWebLink(url: string): boolean { @@ -20,8 +21,7 @@ export function isWebLink(url: string): boolean { */ export function shouldOpenLinkInIntegratedBrowser(url: string): boolean { if (!vscode.workspace.isTrusted) return false - if (vscode.workspace.getConfiguration(BROWSER_AUTOMATION).get("browserAutomation", false) !== true) - return false + if (configuration(BROWSER_AUTOMATION).get("browserAutomation", false) !== true) return false if (integratedBrowserLinkDestination() !== "integrated") return false return isWebLink(url) } diff --git a/packages/kilo-vscode/src/browser-tab/BrowserTabProvider.ts b/packages/kilo-vscode/src/browser-tab/BrowserTabProvider.ts index c44b89fc..ff5f9e08 100644 --- a/packages/kilo-vscode/src/browser-tab/BrowserTabProvider.ts +++ b/packages/kilo-vscode/src/browser-tab/BrowserTabProvider.ts @@ -118,7 +118,7 @@ export class BrowserTabProvider { return } const panel = vscode.window.createWebviewPanel( - "kilo-code.new.browser", + "bharatcode-agent.browser", "Integrated Browser", vscode.ViewColumn.Active, { @@ -290,7 +290,7 @@ export class BrowserTabProvider { return } if (message.type === "browserTab.openSettings") { - void vscode.commands.executeCommand("kilo-code.new.settingsButtonClicked", "experimental") + void vscode.commands.executeCommand("bharatcode-agent.settingsButtonClicked", "experimental") return } if (message.type === "browserTab.openExternal") { diff --git a/packages/kilo-vscode/src/commands/heap-snapshot.ts b/packages/kilo-vscode/src/commands/heap-snapshot.ts index 4b38111d..827d8735 100644 --- a/packages/kilo-vscode/src/commands/heap-snapshot.ts +++ b/packages/kilo-vscode/src/commands/heap-snapshot.ts @@ -3,7 +3,7 @@ import type { KiloConnectionService } from "../services/cli-backend/connection-s export function registerHeapSnapshot(context: vscode.ExtensionContext, connectionService: KiloConnectionService): void { context.subscriptions.push( - vscode.commands.registerCommand("kilo-code.new.takeHeapSnapshot", async () => { + vscode.commands.registerCommand("bharatcode-agent.takeHeapSnapshot", async () => { try { const file = await snapshot(connectionService) vscode.window.showInformationMessage(`Heap snapshot written to ${file}`) diff --git a/packages/kilo-vscode/src/commands/toggle-auto-approve.ts b/packages/kilo-vscode/src/commands/toggle-auto-approve.ts index eb686482..7bbdc6c3 100644 --- a/packages/kilo-vscode/src/commands/toggle-auto-approve.ts +++ b/packages/kilo-vscode/src/commands/toggle-auto-approve.ts @@ -1,3 +1,4 @@ +import { configuration, affectsConfiguration } from "../configuration" import * as vscode from "vscode" import type { Event, KiloClient } from "@kilocode/sdk/v2/client" import { replyOnce } from "../kilo-provider/handlers/permission-handler" @@ -24,7 +25,7 @@ export interface AutoApproveController { onChange(listener: (active: boolean) => void): { dispose(): void } } -const CONFIG = "kilo-code.new.autoApprove" +const CONFIG = "bharatcode-agent.autoApprove" const KEY = "enabled" /** @@ -53,7 +54,7 @@ export function registerToggleAutoApprove( active = next generation++ notify() - await vscode.workspace.getConfiguration(CONFIG).update(KEY, active, target()) + await configuration(CONFIG).update(KEY, active, target()) } const toggle = async () => { @@ -98,7 +99,7 @@ export function registerToggleAutoApprove( context.subscriptions.push( vscode.workspace.onDidChangeConfiguration((event) => { - if (!event.affectsConfiguration(`${CONFIG}.${KEY}`)) return + if (!affectsConfiguration(event, `${CONFIG}.${KEY}`)) return const next = readActive() if (next === active) return active = next @@ -107,7 +108,7 @@ export function registerToggleAutoApprove( }), ) - context.subscriptions.push(vscode.commands.registerCommand("kilo-code.new.toggleAutoApprove", toggle)) + context.subscriptions.push(vscode.commands.registerCommand("bharatcode-agent.toggleAutoApprove", toggle)) return { active: () => active, @@ -128,11 +129,11 @@ export function registerToggleAutoApprove( } function readActive(): boolean { - return vscode.workspace.getConfiguration(CONFIG).get(KEY, false) + return configuration(CONFIG).get(KEY, false) } function target(): vscode.ConfigurationTarget { - const info = vscode.workspace.getConfiguration(CONFIG).inspect(KEY) + const info = configuration(CONFIG).inspect(KEY) if (info?.workspaceFolderValue !== undefined) return vscode.ConfigurationTarget.WorkspaceFolder if (info?.workspaceValue !== undefined) return vscode.ConfigurationTarget.Workspace return vscode.ConfigurationTarget.Global diff --git a/packages/kilo-vscode/src/configuration.ts b/packages/kilo-vscode/src/configuration.ts new file mode 100644 index 00000000..6612c575 --- /dev/null +++ b/packages/kilo-vscode/src/configuration.ts @@ -0,0 +1,95 @@ +import * as vscode from "vscode" +import { copySettings, fallback, LEGACY_NAMESPACE, NAMESPACE } from "./namespace" + +const MARKER = "bharatcode-agent.settingsMigration.v1" +const completed = new Set() + +/** Read old settings only until their scope has been safely copied. Writes are always isolated. */ +export function configuration( + section: string, + scope?: vscode.Uri, + host = vscode.workspace, +): vscode.WorkspaceConfiguration { + const current = host.getConfiguration(section, scope) + if (section !== NAMESPACE && !section.startsWith(`${NAMESPACE}.`)) return current + const legacy = host.getConfiguration(LEGACY_NAMESPACE + section.slice(NAMESPACE.length), scope) + const folder = scope && host.getWorkspaceFolder(scope)?.uri.toString() + return fallback(current, legacy, [ + completed.has("global"), + completed.has("workspace"), + folder ? completed.has(folder) : false, + ]) +} + +export function affectsConfiguration(event: vscode.ConfigurationChangeEvent, section: string): boolean { + if (event.affectsConfiguration(section)) return true + if (section !== NAMESPACE && !section.startsWith(`${NAMESPACE}.`)) return false + return event.affectsConfiguration(LEGACY_NAMESPACE + section.slice(NAMESPACE.length)) +} + +/** Activation must await this before services read preferences or start the backend. */ +export async function migrateConfiguration(context: vscode.ExtensionContext): Promise { + if (context.globalState.get(MARKER)) completed.add("global") + for (const scope of context.workspaceState.get(MARKER, [])) completed.add(scope) + const properties = context.extension.packageJSON.contributes.configuration.properties as Record< + string, + { scope?: string } + > + const scopes: Array<{ + id: string + uri: vscode.Uri | undefined + level: Parameters[3] + target: vscode.ConfigurationTarget + }> = [ + { id: "global", uri: undefined, level: "globalValue", target: vscode.ConfigurationTarget.Global }, + ...(vscode.workspace.workspaceFolders?.length || vscode.workspace.workspaceFile + ? [ + { + id: "workspace", + uri: undefined, + level: "workspaceValue" as const, + target: vscode.ConfigurationTarget.Workspace, + }, + ] + : []), + ...(vscode.workspace.workspaceFolders ?? []).map((folder) => ({ + id: folder.uri.toString(), + uri: folder.uri, + level: "workspaceFolderValue" as const, + target: vscode.ConfigurationTarget.WorkspaceFolder, + })), + ] + for (const scope of scopes) { + if (completed.has(scope.id)) continue + const keys = Object.entries(properties) + .filter(([key, schema]) => { + if (!key.startsWith(`${NAMESPACE}.`)) return false + if (scope.level === "globalValue") return true + if (schema.scope === "application" || schema.scope === "machine") return false + return ( + scope.level !== "workspaceFolderValue" || + schema.scope === "resource" || + schema.scope === "language-overridable" + ) + }) + .map(([key]) => key.slice(NAMESPACE.length + 1)) + const success = await copySettings( + vscode.workspace.getConfiguration(NAMESPACE, scope.uri), + vscode.workspace.getConfiguration(LEGACY_NAMESPACE, scope.uri), + keys, + scope.level, + scope.target, + (key) => console.warn(`[BharatCode] Could not copy setting ${key}; keeping the legacy read fallback.`), + ) + if (!success) continue + // Mark only successful scopes: retries remain safe, and resetting a new setting + // later cannot resurrect its old value. Existing state keys are never touched. + if (scope.id === "global") await context.globalState.update(MARKER, true) + else + await context.workspaceState.update( + MARKER, + [...completed, scope.id].filter((id) => id !== "global"), + ) + completed.add(scope.id) + } +} diff --git a/packages/kilo-vscode/src/constants.ts b/packages/kilo-vscode/src/constants.ts index a8261b70..83cbc21d 100644 --- a/packages/kilo-vscode/src/constants.ts +++ b/packages/kilo-vscode/src/constants.ts @@ -1,2 +1,2 @@ -export const EXTENSION_DISPLAY_NAME = "BharatCode" -export const EXTENSION_ID = "thenabbu.bharatcode-vscode" +export const EXTENSION_DISPLAY_NAME = "BharatCode Agent" +export const EXTENSION_ID = "bharatcode.bharatcode-agent" diff --git a/packages/kilo-vscode/src/diff/DiffViewerProvider.ts b/packages/kilo-vscode/src/diff/DiffViewerProvider.ts index cdf1b5d5..518e9f3f 100644 --- a/packages/kilo-vscode/src/diff/DiffViewerProvider.ts +++ b/packages/kilo-vscode/src/diff/DiffViewerProvider.ts @@ -1,3 +1,4 @@ +import { configuration } from "../configuration" import * as vscode from "vscode" import { randomUUID } from "node:crypto" import { isHttpsUrl, type PRReviewCommentData } from "../shared/review-comments" @@ -112,7 +113,7 @@ export interface DiffViewerProviderOptions { * DiffSource. */ export class DiffViewerProvider implements vscode.Disposable { - public static readonly viewType = "kilo-code.new.DiffViewerPanel" + public static readonly viewType = "bharatcode-agent.DiffViewerPanel" private panel: vscode.WebviewPanel | undefined private ctx: PanelContext | undefined @@ -207,7 +208,7 @@ export class DiffViewerProvider implements vscode.Disposable { } /** - * Entry point for the `kilo-code.new.showChanges` command. Composes the + * Entry point for the `bharatcode-agent.showChanges` command. Composes the * PanelContext from the arg + injected session/workspace lookups so * callers don't have to know about it. * @@ -423,7 +424,7 @@ export class DiffViewerProvider implements vscode.Disposable { void this.panel.webview.postMessage({ type: "ready", vscodeLanguage: vscode.env.language, - languageOverride: vscode.workspace.getConfiguration("kilo-code.new").get("language"), + languageOverride: configuration("bharatcode-agent").get("language"), fontSize: getWebviewFontSize(), workspaceDirectory: this.ctx?.dir ?? getWorkspaceRoot(), }) diff --git a/packages/kilo-vscode/src/extension.ts b/packages/kilo-vscode/src/extension.ts index 4ec1061c..d9c48b9d 100644 --- a/packages/kilo-vscode/src/extension.ts +++ b/packages/kilo-vscode/src/extension.ts @@ -1,3 +1,4 @@ +import { configuration, affectsConfiguration, migrateConfiguration } from "./configuration" import * as vscode from "vscode" import { basename } from "node:path" import { realpathSync } from "node:fs" @@ -66,12 +67,23 @@ export async function activate(context: vscode.ExtensionContext) { console.log("BharatCode extension is now active") shuttingDown = false + await migrateConfiguration(context).catch((error: unknown) => + console.warn("[BharatCode] Settings migration failed; legacy preferences remain available:", error), + ) + context.subscriptions.push( + vscode.workspace.onDidChangeWorkspaceFolders(() => { + void migrateConfiguration(context).catch((error: unknown) => + console.warn("[BharatCode] Folder settings migration failed:", error), + ) + }), + ) + // Speech input downloads its FFmpeg helper on first use; it is no longer bundled in the vsix. setFfmpegCacheDir(context.globalStorageUri.fsPath) - // Drives the "!kilo-code.new.isCursor" guards on the native view/title and + // Drives the "!bharatcode-agent.isCursor" guards on the native view/title and // editor/title menu contributions — see isCursorHost() for why. - void vscode.commands.executeCommand("setContext", "kilo-code.new.isCursor", isCursorHost()) + void vscode.commands.executeCommand("setContext", "bharatcode-agent.isCursor", isCursorHost()) const telemetry = TelemetryProxy.getInstance() @@ -81,7 +93,7 @@ export async function activate(context: vscode.ExtensionContext) { const browserBroker = new BrowserBroker({ log: (...args) => console.warn("[BharatCode] BrowserBroker:", ...args), - enabled: () => vscode.workspace.getConfiguration("kilo-code.new.experimental").get("browserAutomation", false), + enabled: () => configuration("bharatcode-agent.experimental").get("browserAutomation", false), trusted: () => vscode.workspace.isTrusted, useSystemChrome: () => integratedBrowserUseSystemChrome(), fallback: () => process.platform === "linux" && integratedBrowserFallback(), @@ -96,7 +108,7 @@ export async function activate(context: vscode.ExtensionContext) { (dir): Promise => browserAutomationService.ready(dir), ) - // BharatCode first-run onboarding: prompt for the API key once (until stored). + // Invite disconnected users to sign in on the BharatCode website. startBharatcodeOnboarding(context, () => connectionService.getClientAsync()) // One MCP OAuth sign-in service for the whole extension (sidebar, Kilo tabs, Settings, Marketplace). @@ -189,7 +201,7 @@ export async function activate(context: vscode.ExtensionContext) { // Create the provider with shared service const provider = new KiloProvider(context.extensionUri, connectionService, context, { - focusContext: "kilo-code.new.sidebarFocused", + focusContext: "bharatcode-agent.sidebarFocused", onFocused: () => { focus.gained("sidebar") chat = provider @@ -233,11 +245,11 @@ export async function activate(context: vscode.ExtensionContext) { context.extensionUri, { browser: browserBroker, connectionPort: () => connectionService.getServerInfo()?.port }, { - enabled: () => vscode.workspace.getConfiguration("kilo-code.new.experimental").get("browserAutomation", false), + enabled: () => configuration("bharatcode-agent.experimental").get("browserAutomation", false), trusted: () => vscode.workspace.isTrusted, resolve: (route) => { if (!vscode.workspace.isTrusted) return - if (!vscode.workspace.getConfiguration("kilo-code.new.experimental").get("browserAutomation", false)) return + if (!configuration("bharatcode-agent.experimental").get("browserAutomation", false)) return // The Agent Manager owns project-scoped browser entries and keeps them // alive across session switches. Defer while it holds one for this // session so a shared root session does not get two browser entries. @@ -313,12 +325,12 @@ export async function activate(context: vscode.ExtensionContext) { // terminal.integrated.commandsToSkipShell, which only contains built-in // commands by default. const skip = [ - "kilo-code.new.agentManagerOpen", - "kilo-code.new.agentManager.showTerminal", - "kilo-code.new.agentManager.previousTerminal", - "kilo-code.new.agentManager.nextTerminal", + "bharatcode-agent.agentManagerOpen", + "bharatcode-agent.agentManager.showTerminal", + "bharatcode-agent.agentManager.previousTerminal", + "bharatcode-agent.agentManager.nextTerminal", ] - if (process.platform === "darwin") skip.push("kilo-code.new.agentManager.runScript") + if (process.platform === "darwin") skip.push("bharatcode-agent.agentManager.runScript") ensureCommandsSkipShell(skip) // Create Agent Manager provider for editor panel @@ -398,7 +410,7 @@ export async function activate(context: vscode.ExtensionContext) { agentManager = agentManagerProvider context.subscriptions.push( vscode.workspace.onDidChangeConfiguration((event) => { - if (event.affectsConfiguration("kilo-code.new.experimental.browserAutomation")) { + if (affectsConfiguration(event, "bharatcode-agent.experimental.browserAutomation")) { agentManagerProvider.refreshBrowserAutomation() } }), @@ -455,7 +467,7 @@ export async function activate(context: vscode.ExtensionContext) { os: showOSNotification, show: async (sessionID, directory) => { if (await agentManagerProvider.revealSession(sessionID)) return - await vscode.commands.executeCommand("kilo-code.SidebarProvider.focus") + await vscode.commands.executeCommand("bharatcode-agent.SidebarProvider.focus") await provider.openSession(sessionID, directory) }, }) @@ -518,7 +530,7 @@ export async function activate(context: vscode.ExtensionContext) { // Register serializer so "Open in Tab" restores when VS Code restarts context.subscriptions.push( - vscode.window.registerWebviewPanelSerializer("kilo-code.new.TabPanel", { + vscode.window.registerWebviewPanelSerializer("bharatcode-agent.TabPanel", { deserializeWebviewPanel(panel: vscode.WebviewPanel) { const tabProvider = attach(panel) panel.onDidDispose( @@ -585,7 +597,7 @@ export async function activate(context: vscode.ExtensionContext) { const settingsViews = ["settingsPanel", "profilePanel"] as const for (const suffix of settingsViews) { context.subscriptions.push( - vscode.window.registerWebviewPanelSerializer(`kilo-code.new.${suffix}`, { + vscode.window.registerWebviewPanelSerializer(`bharatcode-agent.${suffix}`, { deserializeWebviewPanel(panel: vscode.WebviewPanel) { settingsEditorProvider.deserializePanel(panel) return Promise.resolve() @@ -622,7 +634,7 @@ export async function activate(context: vscode.ExtensionContext) { ) context.subscriptions.push( - vscode.window.registerWebviewPanelSerializer("kilo-code.new.SubAgentViewerPanel", { + vscode.window.registerWebviewPanelSerializer("bharatcode-agent.SubAgentViewerPanel", { deserializeWebviewPanel(panel: vscode.WebviewPanel) { // Sub-agent viewer requires a session ID that can't be recovered // after restart, so dispose the stale panel cleanly. @@ -655,94 +667,94 @@ export async function activate(context: vscode.ExtensionContext) { // Register toolbar button command handlers context.subscriptions.push( - vscode.commands.registerCommand("kilo-code.new.sidebarTitle.plusButtonClicked", () => { - track("new_task", "kilo-code.new.plusButtonClicked") + vscode.commands.registerCommand("bharatcode-agent.sidebarTitle.plusButtonClicked", () => { + track("new_task", "bharatcode-agent.plusButtonClicked") }), - vscode.commands.registerCommand("kilo-code.new.sidebarTitle.historyButtonClicked", () => { - track("history", "kilo-code.new.historyButtonClicked") + vscode.commands.registerCommand("bharatcode-agent.sidebarTitle.historyButtonClicked", () => { + track("history", "bharatcode-agent.historyButtonClicked") }), - vscode.commands.registerCommand("kilo-code.new.sidebarTitle.agentManagerOpen", () => { - track("agent_manager", "kilo-code.new.agentManagerOpen") + vscode.commands.registerCommand("bharatcode-agent.sidebarTitle.agentManagerOpen", () => { + track("agent_manager", "bharatcode-agent.agentManagerOpen") }), - vscode.commands.registerCommand("kilo-code.new.sidebarTitle.marketplaceButtonClicked", () => { - track("marketplace", "kilo-code.new.marketplaceButtonClicked") + vscode.commands.registerCommand("bharatcode-agent.sidebarTitle.marketplaceButtonClicked", () => { + track("marketplace", "bharatcode-agent.marketplaceButtonClicked") }), - vscode.commands.registerCommand("kilo-code.new.sidebarTitle.profileButtonClicked", () => { - track("profile", "kilo-code.new.profileButtonClicked") + vscode.commands.registerCommand("bharatcode-agent.sidebarTitle.profileButtonClicked", () => { + track("profile", "bharatcode-agent.profileButtonClicked") }), - vscode.commands.registerCommand("kilo-code.new.sidebarTitle.settingsButtonClicked", () => { - track("settings", "kilo-code.new.settingsButtonClicked") + vscode.commands.registerCommand("bharatcode-agent.sidebarTitle.settingsButtonClicked", () => { + track("settings", "bharatcode-agent.settingsButtonClicked") }), - vscode.commands.registerCommand("kilo-code.new.plusButtonClicked", () => { + vscode.commands.registerCommand("bharatcode-agent.plusButtonClicked", () => { const tab = activeTabProvider() if (tab) tab.postMessage({ type: "action", action: "plusButtonClicked" }) else provider.postMessage({ type: "action", action: "plusButtonClicked" }) }), - vscode.commands.registerCommand("kilo-code.new.closeTask", () => { + vscode.commands.registerCommand("bharatcode-agent.closeTask", () => { taskTarget().postMessage({ type: "action", action: "closeTask" }) }), - vscode.commands.registerCommand("kilo-code.new.closeAllTasks", () => { + vscode.commands.registerCommand("bharatcode-agent.closeAllTasks", () => { taskTarget().postMessage({ type: "action", action: "closeAllTasks" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManagerOpen", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManagerOpen", () => { agentManagerProvider.openPanel() }), - vscode.commands.registerCommand("kilo-code.new.marketplaceButtonClicked", (directory?: string | null) => { + vscode.commands.registerCommand("bharatcode-agent.marketplaceButtonClicked", (directory?: string | null) => { marketplacePanelProvider.openPanel(directory) }), - vscode.commands.registerCommand("kilo-code.new.historyButtonClicked", () => { + vscode.commands.registerCommand("bharatcode-agent.historyButtonClicked", () => { const tab = activeTabProvider() if (tab) tab.postMessage({ type: "action", action: "historyButtonClicked" }) else provider.postMessage({ type: "action", action: "historyButtonClicked" }) }), - vscode.commands.registerCommand("kilo-code.new.cycleAgentMode", () => { + vscode.commands.registerCommand("bharatcode-agent.cycleAgentMode", () => { const tab = activeTabProvider() if (tab) tab.postMessage({ type: "action", action: "cycleAgentMode" }) else provider.postMessage({ type: "action", action: "cycleAgentMode" }) agentManagerProvider.postMessage({ type: "action", action: "cycleAgentMode" }) }), - vscode.commands.registerCommand("kilo-code.new.cyclePreviousAgentMode", () => { + vscode.commands.registerCommand("bharatcode-agent.cyclePreviousAgentMode", () => { const tab = activeTabProvider() if (tab) tab.postMessage({ type: "action", action: "cyclePreviousAgentMode" }) else provider.postMessage({ type: "action", action: "cyclePreviousAgentMode" }) agentManagerProvider.postMessage({ type: "action", action: "cyclePreviousAgentMode" }) }), - vscode.commands.registerCommand("kilo-code.new.profileButtonClicked", () => { + vscode.commands.registerCommand("bharatcode-agent.profileButtonClicked", () => { settingsEditorProvider.openPanel("profile") }), - vscode.commands.registerCommand("kilo-code.new.settingsButtonClicked", (tab?: string, projectId?: string) => { + vscode.commands.registerCommand("bharatcode-agent.settingsButtonClicked", (tab?: string, projectId?: string) => { settingsEditorProvider.openPanel("settings", tab, projectId) }), - vscode.commands.registerCommand("kilo-code.new.settingsSearch", () => { + vscode.commands.registerCommand("bharatcode-agent.settingsSearch", () => { settingsEditorProvider.focusSearch() }), - vscode.commands.registerCommand("kilo-code.new.openIndexingSettings", () => { + vscode.commands.registerCommand("bharatcode-agent.openIndexingSettings", () => { settingsEditorProvider.openPanel("settings", "indexing") }), - vscode.commands.registerCommand("kilo-code.new.openMcpSettings", (focus?: string) => { + vscode.commands.registerCommand("bharatcode-agent.openMcpSettings", (focus?: string) => { settingsEditorProvider.openPanel("settings", "agentBehaviour", undefined, "mcpServers", focus) }), - vscode.commands.registerCommand("kilo-code.new.showMemory", async () => { + vscode.commands.registerCommand("bharatcode-agent.showMemory", async () => { if (agentManagerProvider.isActive()) { await agentManagerProvider.showMemory() return } const target = activeTabProvider() ?? provider - if (target === provider) await vscode.commands.executeCommand("kilo-code.SidebarProvider.focus") + if (target === provider) await vscode.commands.executeCommand("bharatcode-agent.SidebarProvider.focus") await target.waitForReady() await target.showMemory() }), - vscode.commands.registerCommand("kilo-code.new.toggleMemory", async () => { + vscode.commands.registerCommand("bharatcode-agent.toggleMemory", async () => { if (agentManagerProvider.isActive()) { await agentManagerProvider.toggleMemory() return } const target = activeTabProvider() ?? provider - if (target === provider) await vscode.commands.executeCommand("kilo-code.SidebarProvider.focus") + if (target === provider) await vscode.commands.executeCommand("bharatcode-agent.SidebarProvider.focus") await target.waitForReady() await target.toggleMemory() }), - vscode.commands.registerCommand("kilo-code.new.toggleCaffeination", (enabled?: boolean) => { + vscode.commands.registerCommand("bharatcode-agent.toggleCaffeination", (enabled?: boolean) => { const state = awake.getState() const next = typeof enabled === "boolean" ? enabled : !(state.enabled || state.active) if (next && !state.available) { @@ -750,13 +762,13 @@ export async function activate(context: vscode.ExtensionContext) { } return toggle(next) }), - vscode.commands.registerCommand("kilo-code.new.generateTerminalCommand", async () => { + vscode.commands.registerCommand("bharatcode-agent.generateTerminalCommand", async () => { const input = await vscode.window.showInputBox({ prompt: "Describe the terminal command you want to generate", placeHolder: "e.g., find all .ts files modified in the last 24 hours", }) if (!input) return - await vscode.commands.executeCommand("kilo-code.SidebarProvider.focus") + await vscode.commands.executeCommand("bharatcode-agent.SidebarProvider.focus") await provider.waitForReady() provider.postMessage({ type: "triggerTask", @@ -764,23 +776,23 @@ export async function activate(context: vscode.ExtensionContext) { injectedTitle: "Generate terminal command", }) }), - vscode.commands.registerCommand("kilo-code.new.toggleRemote", () => { + vscode.commands.registerCommand("bharatcode-agent.toggleRemote", () => { remoteService.toggle().catch((err) => console.error("[BharatCode] toggleRemote command failed:", err)) }), - vscode.commands.registerCommand("kilo-code.new.openInTab", () => { + vscode.commands.registerCommand("bharatcode-agent.openInTab", () => { return openKiloInNewTab(context, tabPanels, attach) }), - vscode.commands.registerCommand("kilo-code.new.openBrowser", () => { + vscode.commands.registerCommand("bharatcode-agent.openBrowser", () => { openBrowserTab() }), vscode.commands.registerCommand( - "kilo-code.new.showChanges", + "bharatcode-agent.showChanges", (arg?: Parameters[0]) => { diffViewerProvider.openFromCommand(arg) }, ), vscode.commands.registerCommand( - "kilo-code.new.openSubAgentViewer", + "bharatcode-agent.openSubAgentViewer", (sessionID: string, title?: string, directory?: string) => { subAgentViewerProvider.openPanel(sessionID, title, directory) }, @@ -788,96 +800,96 @@ export async function activate(context: vscode.ExtensionContext) { // One shortcut pair serves the sidebar, Kilo editor tabs, and Agent Manager. // Every surface receives the action and acts only while it has focus, matching // cycleAgentMode, so one binding never depends on a shared focus context key. - vscode.commands.registerCommand("kilo-code.new.agentManager.previousSession", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.previousSession", () => { agentManagerProvider.postMessage({ type: "action", action: "sessionPrevious" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.nextSession", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.nextSession", () => { agentManagerProvider.postMessage({ type: "action", action: "sessionNext" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.previousTab", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.previousTab", () => { const tab = activeTabProvider() if (tab) tab.postMessage({ type: "action", action: "tabPrevious" }) provider.postMessage({ type: "action", action: "tabPrevious" }) agentManagerProvider.postMessage({ type: "action", action: "tabPrevious" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.nextTab", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.nextTab", () => { const tab = activeTabProvider() if (tab) tab.postMessage({ type: "action", action: "tabNext" }) provider.postMessage({ type: "action", action: "tabNext" }) agentManagerProvider.postMessage({ type: "action", action: "tabNext" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.previousTerminal", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.previousTerminal", () => { agentManagerProvider.postMessage({ type: "action", action: "terminalPrevious" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.nextTerminal", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.nextTerminal", () => { agentManagerProvider.postMessage({ type: "action", action: "terminalNext" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.diagnostics", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.diagnostics", () => { // diagnose() spawns git/gh probes and writes to the output channel; a rejection (disposed // channel, disposed context mid-probe) would otherwise be an invisible unhandled rejection. void agentManagerProvider.diagnose().catch((err: unknown) => { console.error("[BharatCode] Agent Manager diagnostics failed:", err) }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.search", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.search", () => { agentManagerProvider.postMessage({ type: "action", action: "search" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.showTerminal", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.showTerminal", () => { // Route through the webview so it can reach into the active session // state and open the VS Code integrated terminal for it. agentManagerProvider.postMessage({ type: "action", action: "showTerminal" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.runScript", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.runScript", () => { agentManagerProvider.postMessage({ type: "action", action: "runScript" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.toggleDiff", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.toggleDiff", () => { agentManagerProvider.postMessage({ type: "action", action: "toggleDiff" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.showShortcuts", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.showShortcuts", () => { agentManagerProvider.postMessage({ type: "action", action: "showShortcuts" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.newTab", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.newTab", () => { agentManagerProvider.postMessage({ type: "action", action: "newTab" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.newTerminalTab", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.newTerminalTab", () => { agentManagerProvider.postMessage({ type: "action", action: "newTerminalTab" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.newSideTerminal", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.newSideTerminal", () => { agentManagerProvider.postMessage({ type: "action", action: "newSideTerminal" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.closeTab", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.closeTab", () => { agentManagerProvider.postMessage({ type: "action", action: "closeTab" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.newWorktree", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.newWorktree", () => { agentManagerProvider.postMessage({ type: "action", action: "newWorktree" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.quickWorktree", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.quickWorktree", () => { agentManagerProvider.postMessage({ type: "action", action: "quickWorktree" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.openWorktree", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.openWorktree", () => { agentManagerProvider.postMessage({ type: "action", action: "openWorktree" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.updateFromBase", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.updateFromBase", () => { agentManagerProvider.postMessage({ type: "action", action: "updateFromBase" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.openPR", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.openPR", () => { agentManagerProvider.postMessage({ type: "action", action: "openPR" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.closeWorktree", () => { + vscode.commands.registerCommand("bharatcode-agent.agentManager.closeWorktree", () => { agentManagerProvider.postMessage({ type: "action", action: "closeWorktree" }) }), - vscode.commands.registerCommand("kilo-code.new.agentManager.advancedWorktree", () => + vscode.commands.registerCommand("bharatcode-agent.agentManager.advancedWorktree", () => agentManagerProvider.openAdvancedWorktree(), ), ...Array.from({ length: 9 }, (_, i) => - vscode.commands.registerCommand(`kilo-code.new.agentManager.jumpTo${i + 1}`, () => { + vscode.commands.registerCommand(`bharatcode-agent.agentManager.jumpTo${i + 1}`, () => { agentManagerProvider.postMessage({ type: "action", action: `jumpTo${i + 1}` }) }), ), ) - // Register URI handler for extension deep links (vscode://thenabbu.bharatcode-vscode/kilocode/...) + // Register URI handler for extension deep links (vscode://bharatcode.bharatcode-agent/kilocode/...) context.subscriptions.push( vscode.window.registerUriHandler({ async handleUri(uri: vscode.Uri) { @@ -908,7 +920,7 @@ export async function activate(context: vscode.ExtensionContext) { registerHeapSnapshot(context, connectionService) context.subscriptions.push( - vscode.commands.registerCommand("kilo-code.new.reload", () => { + vscode.commands.registerCommand("bharatcode-agent.reload", () => { provider.reload().catch((e) => console.error("[BharatCode] reload command failed:", e)) }), ) @@ -965,7 +977,7 @@ function openKiloInNewTab( attach: (panel: vscode.WebviewPanel) => KiloProvider, ) { const panel = vscode.window.createWebviewPanel( - "kilo-code.new.TabPanel", + "bharatcode-agent.TabPanel", EXTENSION_DISPLAY_NAME, vscode.ViewColumn.Active, { diff --git a/packages/kilo-vscode/src/kilo-provider/auto-approval-reason-settings.ts b/packages/kilo-vscode/src/kilo-provider/auto-approval-reason-settings.ts index 3f0ba8f2..6079ab86 100644 --- a/packages/kilo-vscode/src/kilo-provider/auto-approval-reason-settings.ts +++ b/packages/kilo-vscode/src/kilo-provider/auto-approval-reason-settings.ts @@ -1,9 +1,10 @@ +import { configuration, affectsConfiguration } from "../configuration" import * as vscode from "vscode" type Post = (msg: unknown) => void export function buildAutoApprovalReasonSettingMessage() { - const config = vscode.workspace.getConfiguration("kilo-code.new") + const config = configuration("bharatcode-agent") return { type: "autoApprovalReasonSettingLoaded" as const, visible: config.get("showAutoApprovalReason", true), @@ -12,7 +13,7 @@ export function buildAutoApprovalReasonSettingMessage() { export function watchAutoApprovalReasonConfig(post: Post): vscode.Disposable { return vscode.workspace.onDidChangeConfiguration((event) => { - if (event.affectsConfiguration("kilo-code.new.showAutoApprovalReason")) { + if (affectsConfiguration(event, "bharatcode-agent.showAutoApprovalReason")) { post(buildAutoApprovalReasonSettingMessage()) } }) diff --git a/packages/kilo-vscode/src/kilo-provider/chat-settings.ts b/packages/kilo-vscode/src/kilo-provider/chat-settings.ts index 9c385cd2..5f87bab0 100644 --- a/packages/kilo-vscode/src/kilo-provider/chat-settings.ts +++ b/packages/kilo-vscode/src/kilo-provider/chat-settings.ts @@ -1,17 +1,16 @@ +import { configuration, affectsConfiguration } from "../configuration" import * as vscode from "vscode" import { integratedBrowserLinkDestination } from "../services/browser-automation/chrome-setting" type Post = (msg: unknown) => void export function buildChatSettingsMessage() { - const config = vscode.workspace.getConfiguration("kilo-code.new.chat") + const config = configuration("bharatcode-agent.chat") return { type: "chatSettingsLoaded" as const, settings: { shiftTabCyclesVariant: config.get("shiftTabCyclesVariant", true), - browserAutomation: vscode.workspace - .getConfiguration("kilo-code.new.experimental") - .get("browserAutomation", false), + browserAutomation: configuration("bharatcode-agent.experimental").get("browserAutomation", false), agentManagerBrowserOpenLinksIn: integratedBrowserLinkDestination(), workspaceTrusted: vscode.workspace.isTrusted, }, @@ -19,7 +18,7 @@ export function buildChatSettingsMessage() { } export function buildTimelineSettingMessage() { - const config = vscode.workspace.getConfiguration("kilo-code.new") + const config = configuration("bharatcode-agent") return { type: "timelineSettingLoaded" as const, visible: config.get("showTaskTimeline", true), @@ -29,13 +28,13 @@ export function buildTimelineSettingMessage() { export function watchChatConfig(post: Post): vscode.Disposable { return vscode.workspace.onDidChangeConfiguration((event) => { if ( - event.affectsConfiguration("kilo-code.new.chat") || - event.affectsConfiguration("kilo-code.new.experimental.browserAutomation") || - event.affectsConfiguration("kilo-code.new.agentManager.browser.openLinksIn") + affectsConfiguration(event, "bharatcode-agent.chat") || + affectsConfiguration(event, "bharatcode-agent.experimental.browserAutomation") || + affectsConfiguration(event, "bharatcode-agent.agentManager.browser.openLinksIn") ) { post(buildChatSettingsMessage()) } - if (event.affectsConfiguration("kilo-code.new.showTaskTimeline")) { + if (affectsConfiguration(event, "bharatcode-agent.showTaskTimeline")) { post(buildTimelineSettingMessage()) } }) diff --git a/packages/kilo-vscode/src/kilo-provider/font-size.ts b/packages/kilo-vscode/src/kilo-provider/font-size.ts index 1338cbe3..b9e1cd1a 100644 --- a/packages/kilo-vscode/src/kilo-provider/font-size.ts +++ b/packages/kilo-vscode/src/kilo-provider/font-size.ts @@ -1,3 +1,4 @@ +import { affectsConfiguration } from "../configuration" import * as vscode from "vscode" import { getWebviewFontSize } from "../utils" @@ -6,7 +7,7 @@ export function watchFontSizeConfig( next?: vscode.Disposable, ) { const font = vscode.workspace.onDidChangeConfiguration((event) => { - if (event.affectsConfiguration("kilo-code.new.fontSize")) + if (affectsConfiguration(event, "bharatcode-agent.fontSize")) post({ type: "fontSizeChanged", fontSize: getWebviewFontSize() }) }) return next ? vscode.Disposable.from(font, next) : font diff --git a/packages/kilo-vscode/src/kilo-provider/indexing-settings.ts b/packages/kilo-vscode/src/kilo-provider/indexing-settings.ts index be8a580a..3af3a103 100644 --- a/packages/kilo-vscode/src/kilo-provider/indexing-settings.ts +++ b/packages/kilo-vscode/src/kilo-provider/indexing-settings.ts @@ -1,8 +1,9 @@ +import { configuration, affectsConfiguration } from "../configuration" import * as vscode from "vscode" import type { IndexingProject } from "../indexing-consent" export function buildIndexingSettingsMessage(consent = false, projects: IndexingProject[] = [], projectId?: string) { - const config = vscode.workspace.getConfiguration("kilo-code.new.indexing") + const config = configuration("bharatcode-agent.indexing") return { type: "indexingSettingsLoaded" as const, settings: { @@ -16,7 +17,7 @@ export function buildIndexingSettingsMessage(consent = false, projects: Indexing export function watchIndexingConfig(post: () => void): vscode.Disposable { return vscode.workspace.onDidChangeConfiguration((event) => { - if (event.affectsConfiguration("kilo-code.new.indexing")) { + if (affectsConfiguration(event, "bharatcode-agent.indexing")) { post() } }) diff --git a/packages/kilo-vscode/src/kilo-provider/push-fixes-settings.ts b/packages/kilo-vscode/src/kilo-provider/push-fixes-settings.ts index 1b7949cf..b919adc7 100644 --- a/packages/kilo-vscode/src/kilo-provider/push-fixes-settings.ts +++ b/packages/kilo-vscode/src/kilo-provider/push-fixes-settings.ts @@ -1,10 +1,11 @@ +import { configuration, affectsConfiguration } from "../configuration" import * as vscode from "vscode" type Post = (msg: unknown) => void /** Whether Agent Manager fix prompts ask the agent to commit and push so the pull request updates. */ export function pushFixes(): boolean { - return vscode.workspace.getConfiguration("kilo-code.new.agentManager").get("pushFixes", true) + return configuration("bharatcode-agent.agentManager").get("pushFixes", true) } export function buildPushFixesSettingMessage() { @@ -17,7 +18,7 @@ export function buildPushFixesSettingMessage() { /** Push the setting to every webview when another surface changes it. */ export function watchPushFixesConfig(post: Post): vscode.Disposable { return vscode.workspace.onDidChangeConfiguration((event) => { - if (!event.affectsConfiguration("kilo-code.new.agentManager.pushFixes")) return + if (!affectsConfiguration(event, "bharatcode-agent.agentManager.pushFixes")) return post(buildPushFixesSettingMessage()) }) } diff --git a/packages/kilo-vscode/src/kilo-provider/shortcut-hints-settings.ts b/packages/kilo-vscode/src/kilo-provider/shortcut-hints-settings.ts index 96842dd3..382e75c9 100644 --- a/packages/kilo-vscode/src/kilo-provider/shortcut-hints-settings.ts +++ b/packages/kilo-vscode/src/kilo-provider/shortcut-hints-settings.ts @@ -1,10 +1,11 @@ +import { configuration, affectsConfiguration } from "../configuration" import * as vscode from "vscode" type Post = (msg: unknown) => void /** Whether the prompt and empty Agent Manager sessions show keyboard shortcut hints. */ export function shortcutHints(): boolean { - return vscode.workspace.getConfiguration("kilo-code.new").get("showShortcutHints", true) + return configuration("bharatcode-agent").get("showShortcutHints", true) } export function buildShortcutHintsSettingMessage() { @@ -17,7 +18,7 @@ export function buildShortcutHintsSettingMessage() { /** Push the setting to every webview when another surface changes it. */ export function watchShortcutHintsConfig(post: Post): vscode.Disposable { return vscode.workspace.onDidChangeConfiguration((event) => { - if (!event.affectsConfiguration("kilo-code.new.showShortcutHints")) return + if (!affectsConfiguration(event, "bharatcode-agent.showShortcutHints")) return post(buildShortcutHintsSettingMessage()) }) } diff --git a/packages/kilo-vscode/src/kilo-provider/throughput-settings.ts b/packages/kilo-vscode/src/kilo-provider/throughput-settings.ts index 224213ce..37705fca 100644 --- a/packages/kilo-vscode/src/kilo-provider/throughput-settings.ts +++ b/packages/kilo-vscode/src/kilo-provider/throughput-settings.ts @@ -1,9 +1,10 @@ +import { configuration, affectsConfiguration } from "../configuration" import * as vscode from "vscode" type Post = (msg: unknown) => void export function buildThroughputSettingMessage() { - const config = vscode.workspace.getConfiguration("kilo-code.new") + const config = configuration("bharatcode-agent") return { type: "throughputSettingLoaded" as const, visible: config.get("showTokenThroughput", true), @@ -12,7 +13,7 @@ export function buildThroughputSettingMessage() { export function watchThroughputConfig(post: Post): vscode.Disposable { return vscode.workspace.onDidChangeConfiguration((event) => { - if (event.affectsConfiguration("kilo-code.new.showTokenThroughput")) { + if (affectsConfiguration(event, "bharatcode-agent.showTokenThroughput")) { post(buildThroughputSettingMessage()) } }) diff --git a/packages/kilo-vscode/src/kilo-provider/work-style-apply-handler.ts b/packages/kilo-vscode/src/kilo-provider/work-style-apply-handler.ts index 5652b84e..665d7bee 100644 --- a/packages/kilo-vscode/src/kilo-provider/work-style-apply-handler.ts +++ b/packages/kilo-vscode/src/kilo-provider/work-style-apply-handler.ts @@ -1,3 +1,4 @@ +import { configuration } from "../configuration" import * as vscode from "vscode" import type { Config } from "@kilocode/sdk/v2/client" import type { KiloConnectionService } from "../services/cli-backend/connection-service" @@ -14,7 +15,7 @@ function inspect(config: vscode.WorkspaceConfiguration, key: string): WorkStyleS } async function apply(connection: KiloConnectionService, directory: string, style: WorkStyle) { - const settings = vscode.workspace.getConfiguration("kilo-code.new") + const settings = configuration("bharatcode-agent") return applyWorkStyle(style, { read: async () => { const client = await connection.getClientAsync(directory) diff --git a/packages/kilo-vscode/src/kilo-provider/work-style.ts b/packages/kilo-vscode/src/kilo-provider/work-style.ts index 6342fd36..104bf53b 100644 --- a/packages/kilo-vscode/src/kilo-provider/work-style.ts +++ b/packages/kilo-vscode/src/kilo-provider/work-style.ts @@ -1,3 +1,4 @@ +import { configuration, affectsConfiguration } from "../configuration" import * as vscode from "vscode" import type { KiloConnectionService } from "../services/cli-backend/connection-service" import { getInitialWorkStyle, type WorkStyleState } from "../shared/work-style-presets" @@ -6,7 +7,7 @@ import { handleWorkStyleApplyMessage } from "./work-style-apply-handler" export const WORK_STYLE_SETTING_KEYS = ["showTaskTimeline", "showAutoApprovalReason"] as const function getConfig() { - return vscode.workspace.getConfiguration("kilo-code.new") + return configuration("bharatcode-agent") } function isWorkStyleConfigured(): boolean { @@ -27,7 +28,7 @@ export function isWorkStyleSetting(key: string): boolean { export function watchWorkStyleConfig(post: (message: unknown) => void, next?: vscode.Disposable) { const keys = ["agentWorkStyle", ...WORK_STYLE_SETTING_KEYS] const watcher = vscode.workspace.onDidChangeConfiguration((event) => { - if (keys.some((key) => event.affectsConfiguration(`kilo-code.new.${key}`))) post(getWorkStylePayload()) + if (keys.some((key) => affectsConfiguration(event, `bharatcode-agent.${key}`))) post(getWorkStylePayload()) }) return next ? vscode.Disposable.from(watcher, next) : watcher } diff --git a/packages/kilo-vscode/src/namespace.ts b/packages/kilo-vscode/src/namespace.ts new file mode 100644 index 00000000..1adddf39 --- /dev/null +++ b/packages/kilo-vscode/src/namespace.ts @@ -0,0 +1,66 @@ +import type { ConfigurationTarget, WorkspaceConfiguration } from "vscode" + +// Public VS Code registrations are independent of the extension/storage identity. +export const NAMESPACE = "bharatcode-agent" +export const LEGACY_NAMESPACE = "kilo-code.new" + +const levels = ["globalValue", "workspaceValue", "workspaceFolderValue"] as const +type Level = (typeof levels)[number] + +/** Only explicit old values are eligible; another extension's defaults are not ours. */ +export function fallback( + current: WorkspaceConfiguration, + legacy: WorkspaceConfiguration, + completed: readonly boolean[] = [], +): WorkspaceConfiguration { + const inspect: WorkspaceConfiguration["inspect"] = (key: string) => { + const next = current.inspect?.(key) + const old = legacy.inspect?.(key) + if (!next && !old) return undefined + const result = { ...next, key: next?.key ?? key } + for (const [index, level] of levels.entries()) { + if (result[level] === undefined && !completed[index] && old?.[level] !== undefined) result[level] = old[level] + } + return result + } + const get = (key: string, value?: T): T | undefined => { + const next = current.inspect?.(key) + const old = legacy.inspect?.(key) + for (const [index, level] of [...levels.entries()].reverse()) { + // Let VS Code resolve the new value (including policy/default behavior). + if (next?.[level] !== undefined) return current.get(key) ?? value + if (!completed[index] && old?.[level] !== undefined) return old[level] + } + return current.get(key) ?? value + } + return { + ...current, + get: get as WorkspaceConfiguration["get"], + inspect, + has: (key) => get(key) !== undefined, + update: (key, value, target, language) => current.update(key, value, target, language), + } +} + +/** Copy one scope, never deleting legacy values or overwriting explicit new values. */ +export async function copySettings( + current: WorkspaceConfiguration, + legacy: WorkspaceConfiguration, + keys: readonly string[], + level: Level, + target: ConfigurationTarget, + failed: (key: string, error: unknown) => void, +): Promise { + let complete = true + for (const key of keys) { + const value = legacy.inspect(key)?.[level] + if (value === undefined || current.inspect(key)?.[level] !== undefined) continue + try { + await current.update(key, value, target) + } catch (error) { + complete = false + failed(key, error) + } + } + return complete +} diff --git a/packages/kilo-vscode/src/onboarding/bharatcode.ts b/packages/kilo-vscode/src/onboarding/bharatcode.ts index f03ef458..4955156a 100644 --- a/packages/kilo-vscode/src/onboarding/bharatcode.ts +++ b/packages/kilo-vscode/src/onboarding/bharatcode.ts @@ -1,192 +1,100 @@ +// The command is isolated; the persisted sign-in flag remains unchanged. import * as vscode from "vscode" import type { KiloClient } from "@kilocode/sdk/v2/client" -import { fetchProviderData } from "../provider-actions" -export const BHARATCODE_BASE_URL = "https://bharatcode.ai/api/model/v1" -const SET_KEY_COMMAND = "kilo-code.new.setBharatcodeKey" -const KEY_SET_FLAG = "bharatcode.apiKeySet" +const SET_KEY_COMMAND = "bharatcode-agent.setBharatcodeKey" +const CONNECTED_FLAG = "bharatcode.apiKeySet" +const SIGN_IN = "Sign in with BharatCode" -// GET /models on bharatcode.ai answers without auth, so it cannot verify a -// key; a 1-token chat completion can (bad key -> 401 invalid_credentials). -async function valid(key: string): Promise { - try { - const res = await fetch(BHARATCODE_BASE_URL + "/chat/completions", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: "Bearer " + key }, - body: JSON.stringify({ - model: "qwen-3.8-27b", - messages: [{ role: "user", content: "hi" }], - max_tokens: 1, - }), - signal: AbortSignal.timeout(20_000), - }) - return res.ok - } catch (error) { - console.warn("[BharatCode] BharatCode key validation failed:", error) - return false - } +function explain(error: unknown) { + const status = (error as { status?: number } | null)?.status + if (status === 409 || /already in use|EADDRINUSE/i.test(String((error as Error)?.message))) + return "Another BharatCode sign-in is using the callback port. Finish that sign-in and try again." + if (status === 429) return "Too many sign-in attempts. Wait a minute and try again." + return "Sign-in didn’t finish. Run BharatCode: Sign In to try again." } -async function ask(): Promise { - for (;;) { - const raw = await vscode.window.showInputBox({ - title: "BharatCode API key", - prompt: "Paste your API key from https://bharatcode.ai - stored by the extension backend, never in settings.", - password: true, - ignoreFocusOut: true, - validateInput: (value) => (value.trim().length >= 8 ? undefined : "That does not look like an API key"), - }) - if (!raw) return undefined - const key = raw.trim() - if (await valid(key)) return key - const retry = await vscode.window.showErrorMessage( - "BharatCode rejected that key (401). Copy the key from your BharatCode account and try again.", - "Retry", +export function start(ctx: vscode.ExtensionContext, client: () => Promise) { + let pending: Promise | undefined + const folder = () => vscode.workspace.workspaceFolders?.[0]?.uri.fsPath + + async function signIn() { + const directory = folder() + if (!directory) { + void vscode.window.showInformationMessage("Open a project folder, then run BharatCode: Sign In.") + return + } + if (vscode.env.remoteName) { + // The registered OAuth callback is a loopback URL; never replace it with a public tunnel. + const forwarded = await vscode.env.asExternalUri(vscode.Uri.parse("http://127.0.0.1:27182/callback")) + const local = new URL(forwarded.toString()) + if ( + local.protocol !== "http:" || + !["localhost", "127.0.0.1"].includes(local.hostname) || + local.port !== "27182" + ) { + void vscode.window.showErrorMessage( + "Forward port 27182 to local port 27182 in VS Code’s Ports view, or sign in from a local project window.", + ) + return + } + } + const c = await client() + const params = { providerID: "bharatcode", method: 0, directory } + const { data } = await c.provider.oauth.authorize(params, { throwOnError: true }) + const url = data?.url && new URL(data.url) + if ( + !url || + url.origin !== "https://auth.bharatcode.ai" || + url.pathname !== "/auth/v1/oauth/authorize" || + url.username || + url.password || + url.hash ) - if (retry !== "Retry") return undefined + throw new Error("Unexpected authorization URL") + if (!(await vscode.env.openExternal(vscode.Uri.parse(url.href)))) throw new Error("Browser unavailable") + await c.provider.oauth.callback(params, { throwOnError: true }) + await ctx.globalState.update(CONNECTED_FLAG, true).then(undefined, () => {}) + await c.global.dispose().catch(() => {}) + void vscode.commands.executeCommand("bharatcode-agent.SidebarProvider.focus") + void vscode.window.showInformationMessage("BharatCode connected.") } -} - -type AuthChoice = "oauth" | "api" -/** First-run picker: OAuth (recommended) or a pasted API key — user's call. */ -async function choose(): Promise { - const picked = await vscode.window.showQuickPick( - [ - { - label: "$(account) Sign in with BharatCode", - description: "Recommended - opens your browser, no API key needed", - choice: "oauth" as const, - }, - { - label: "$(key) Use an API key", - description: "Paste a key from bharatcode.ai instead", - choice: "api" as const, - }, - ], - { - title: "Connect BharatCode", - placeHolder: "BharatCode is the primary provider of this extension", - ignoreFocusOut: true, - }, - ) - return picked?.choice -} - -/** - * First-party OAuth (auth.bharatcode.ai) via the backend's bharatcode auth - * method (PKCE + loopback callback). Mirrors the settings-page connect flow: - * authorize -> open the browser -> block on the callback -> reset the backend - * so the provider picks the session up immediately. - * - * Sign-in needs the CLI backend running, and the backend needs a workspace - * root, so an empty window must be explained up front instead of surfacing - * the connection layer's "No workspace folder open". - */ -async function signInWithBrowser(client: () => Promise): Promise { - const c = await client() - const directory = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath - const scope = directory ? { directory } : {} - const { data: authorization } = await c.provider.oauth.authorize( - { providerID: "bharatcode", method: 0, ...scope }, - { throwOnError: true }, - ) - if (!authorization?.url) throw new Error("BharatCode sign-in did not return a URL.") - const opened = await vscode.env.openExternal(vscode.Uri.parse(authorization.url)) - if (!opened) throw new Error("Could not open the browser for BharatCode sign-in.") - await c.provider.oauth.callback({ providerID: "bharatcode", method: 0, ...scope }, { throwOnError: true }) - await c.global.dispose().catch(() => {}) -} - -/** - * First-run flow: nothing stored -> offer OAuth or API key -> run the picked - * path -> auth (type oauth or api) lands in the backend store. - */ -/** Human-readable next step for a failed sign-in, so a retry is informed. */ -function explain(error: unknown): string { - const raw = String((error as Error)?.message ?? error ?? "").trim() - const status = (error as { status?: number })?.status - if (status === 409 || /already in use|EADDRINUSE/i.test(raw)) - return "Another BharatCode sign-in is already in progress (the CLI holds the callback port). Finish or cancel that one, then try again." - if (status === 401 || status === 403) - return "BharatCode rejected the sign-in. Make sure you are signed in at bharatcode.ai, then try again." - if (status === 429) return "Too many sign-in attempts. Wait a minute, then try again." - if (status && status >= 500) - return "BharatCode's sign-in service is temporarily unavailable. Try again in a moment, or use an API key instead." - if (/No workspace folder open/i.test(raw)) - return "Open a folder in VS Code first (File > Open Folder), then run BharatCode: Set API Key." - return raw || "BharatCode sign-in failed. Try again, or use an API key instead." -} - -/** - * The flag is only a fast path: credentials can disappear underneath it (a - * sign-out, a wiped credential store, or an auth-server cutover that - * invalidated every stored session). Ask the backend before trusting it, so a - * user whose stored login no longer exists is offered the picker again - * instead of being left with a silent extension. - */ -async function hasStoredCredentials(client: () => Promise): Promise { - try { - const c = await client() - const directory = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath - if (!directory) return false - // fetchProviderData returns { response, authMethods, authStates, ... }; - // the provider list (and its `connected` array) lives under .response. - const { response } = await fetchProviderData(c, directory) - return (response.connected ?? []).includes("bharatcode") - } catch (error) { - console.warn("[BharatCode] Could not read stored BharatCode credentials:", error) - // Unknown state: trust the flag rather than nagging a connected user. - return true + function connect() { + // A click from the sidebar and the command palette share one PKCE exchange. + return (pending ??= signIn() + .catch((error: unknown) => { + void vscode.window.showErrorMessage(explain(error)) + }) + .finally(() => { + pending = undefined + })) } -} -export async function ensureKey(ctx: vscode.ExtensionContext, client: () => Promise): Promise { - if (ctx.globalState.get(KEY_SET_FLAG) && (await hasStoredCredentials(client))) return - for (;;) { - const choice = await choose() - if (!choice) return + async function welcome() { + const directory = folder() + if (!directory) return try { - if (choice === "oauth") { - await signInWithBrowser(client) - } else { - const key = await ask() - if (!key) continue - const c = await client() - await c.auth.set({ providerID: "bharatcode", auth: { type: "api", key } }, { throwOnError: true }) - } - await ctx.globalState.update(KEY_SET_FLAG, true) - // The panel is the onboarding surface (a centre-top toast is easy to - // miss), so surface it rather than reporting into the void. - void vscode.commands.executeCommand("kilo-code.SidebarProvider.focus") - void vscode.window.showInformationMessage("BharatCode connected.") - return - } catch (error) { - console.warn("[BharatCode] BharatCode sign-in failed:", error) - const retry = await vscode.window.showErrorMessage("BharatCode sign-in failed: " + explain(error), "Try again") - if (retry !== "Try again") return + const c = await client() + const { data } = await c.provider.list({ directory }, { throwOnError: true }) + if (data.connected.includes("bharatcode")) return + } catch { + if (ctx.globalState.get(CONNECTED_FLAG)) return } + // Opening an editor must not launch a browser without a user gesture. + if ( + (await vscode.window.showInformationMessage("Connect BharatCode to start your first chat.", SIGN_IN)) === SIGN_IN + ) + await connect() } -} -/** Registers the palette command and kicks off the first-run prompt. */ -export function start(ctx: vscode.ExtensionContext, client: () => Promise): void { - ctx.subscriptions.push( - vscode.commands.registerCommand(SET_KEY_COMMAND, async () => { - await ctx.globalState.update(KEY_SET_FLAG, false) - await ensureKey(ctx, client) - }), - ) - // The backend needs a workspace root, so an empty window cannot sign in. - // Prompt once a folder exists instead of failing on startup. - const hasFolder = () => (vscode.workspace.workspaceFolders?.length ?? 0) > 0 - if (hasFolder()) { - void ensureKey(ctx, client).catch((error) => console.warn("[BharatCode] BharatCode onboarding:", error)) - } else { + ctx.subscriptions.push(vscode.commands.registerCommand(SET_KEY_COMMAND, connect)) + if (folder()) void welcome() + else { const listener = vscode.workspace.onDidChangeWorkspaceFolders(() => { - if (!hasFolder()) return + if (!folder()) return listener.dispose() - void ensureKey(ctx, client).catch((error) => console.warn("[BharatCode] BharatCode onboarding:", error)) + void welcome() }) ctx.subscriptions.push(listener) } diff --git a/packages/kilo-vscode/src/provider-actions.ts b/packages/kilo-vscode/src/provider-actions.ts index f3106a69..ff9783a8 100644 --- a/packages/kilo-vscode/src/provider-actions.ts +++ b/packages/kilo-vscode/src/provider-actions.ts @@ -111,6 +111,7 @@ export async function fetchProviderData(client: KiloClient, dir: string) { authStates, storedKeys, organizationId, + // Catalog completion is tracked separately from Kilo auth readiness in the webview. ready: !!kiloAuth, unavailable: catalogUnavailable(response.failed, all, organizationId), } diff --git a/packages/kilo-vscode/src/review-settings.ts b/packages/kilo-vscode/src/review-settings.ts index 5d70fcd7..84c458d4 100644 --- a/packages/kilo-vscode/src/review-settings.ts +++ b/packages/kilo-vscode/src/review-settings.ts @@ -1,14 +1,15 @@ +import { configuration } from "./configuration" import * as vscode from "vscode" -const CONFIG = "kilo-code.new" +const CONFIG = "bharatcode-agent" const KEY = "diff.renderMarkdown" export function getDiffMarkdownRender(): boolean { - return vscode.workspace.getConfiguration(CONFIG).get(KEY, false) + return configuration(CONFIG).get(KEY, false) } export async function setDiffMarkdownRender(value: boolean): Promise { - await vscode.workspace.getConfiguration(CONFIG).update(KEY, value, vscode.ConfigurationTarget.Global) + await configuration(CONFIG).update(KEY, value, vscode.ConfigurationTarget.Global) } export type DiffStyle = "unified" | "split" @@ -20,11 +21,11 @@ export type DiffStyle = "unified" | "split" * diffs open split, permission-dock expand opens unified). */ export function getUserDiffStyle(): DiffStyle | undefined { - const value = vscode.workspace.getConfiguration(CONFIG).get("diff.style") + const value = configuration(CONFIG).get("diff.style") if (value === "unified" || value === "split") return value return undefined } export async function setUserDiffStyle(style: DiffStyle): Promise { - await vscode.workspace.getConfiguration(CONFIG).update("diff.style", style, vscode.ConfigurationTarget.Global) + await configuration(CONFIG).update("diff.style", style, vscode.ConfigurationTarget.Global) } diff --git a/packages/kilo-vscode/src/services/RemoteStatusService.ts b/packages/kilo-vscode/src/services/RemoteStatusService.ts index a27c2c1b..4c067890 100644 --- a/packages/kilo-vscode/src/services/RemoteStatusService.ts +++ b/packages/kilo-vscode/src/services/RemoteStatusService.ts @@ -19,7 +19,7 @@ export class RemoteStatusService implements vscode.Disposable { constructor() { this.bar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 99) - this.bar.command = "kilo-code.new.toggleRemote" + this.bar.command = "bharatcode-agent.toggleRemote" this.sync() } diff --git a/packages/kilo-vscode/src/services/attention/service.ts b/packages/kilo-vscode/src/services/attention/service.ts index ec2cfab5..cf49070b 100644 --- a/packages/kilo-vscode/src/services/attention/service.ts +++ b/packages/kilo-vscode/src/services/attention/service.ts @@ -1,3 +1,4 @@ +import { configuration } from "../../configuration" import * as vscode from "vscode" import type { TuiAttentionSoundName } from "@kilocode/plugin/tui" import type { SSEPayload } from "../cli-backend/sdk-sse-adapter" @@ -164,7 +165,7 @@ export class AttentionService implements vscode.Disposable { } private sound(sound: TuiAttentionSoundName) { - const config = vscode.workspace.getConfiguration("kilo-code.new.attention") + const config = configuration("bharatcode-agent.attention") if (!config.get("enabled", false)) return void playSound(sound, resolveSoundID(config.get("sound", "default"))) } @@ -203,7 +204,7 @@ export class AttentionService implements vscode.Disposable { /** Picks which delivery channels should fire; independently, both, one, or neither. */ private channels(sessionID: string) { - const config = vscode.workspace.getConfiguration("kilo-code.new.attention") + const config = configuration("bharatcode-agent.attention") const focused = this.opts.focused?.() ?? vscode.window.state.focused // `os` is only wired up on hosts that can deliver a native notification, so other platforms fall through. const os = Boolean(this.opts.os) && config.get("OSNotifications", false) && !focused diff --git a/packages/kilo-vscode/src/services/browser-automation/browser-automation-service.ts b/packages/kilo-vscode/src/services/browser-automation/browser-automation-service.ts index 1a741588..dace1067 100644 --- a/packages/kilo-vscode/src/services/browser-automation/browser-automation-service.ts +++ b/packages/kilo-vscode/src/services/browser-automation/browser-automation-service.ts @@ -1,3 +1,4 @@ +import { configuration, affectsConfiguration } from "../../configuration" import * as vscode from "vscode" import type { KiloClient } from "@kilocode/sdk/v2/client" import type { KiloConnectionService } from "../cli-backend" @@ -24,7 +25,7 @@ export class BrowserAutomationService implements vscode.Disposable { ) { this.disposables.push( vscode.workspace.onDidChangeConfiguration((event) => { - if (!event.affectsConfiguration("kilo-code.new.browserAutomation")) return + if (!affectsConfiguration(event, "bharatcode-agent.browserAutomation")) return void this.syncWithSettings() }), vscode.workspace.onDidChangeWorkspaceFolders(() => this.enqueue(() => this.apply(true))), @@ -146,11 +147,11 @@ export class BrowserAutomationService implements vscode.Disposable { } private enabled(): boolean { - return vscode.workspace.getConfiguration("kilo-code.new.browserAutomation").get("enabled", false) === true + return configuration("bharatcode-agent.browserAutomation").get("enabled", false) === true } private command(): string[] { - const config = vscode.workspace.getConfiguration("kilo-code.new.browserAutomation") + const config = configuration("bharatcode-agent.browserAutomation") return playwrightCommand({ headless: config.get("headless", false), useSystemChrome: config.get("useSystemChrome", true), diff --git a/packages/kilo-vscode/src/services/browser-automation/chrome-setting.ts b/packages/kilo-vscode/src/services/browser-automation/chrome-setting.ts index 556078ee..7dce55ae 100644 --- a/packages/kilo-vscode/src/services/browser-automation/chrome-setting.ts +++ b/packages/kilo-vscode/src/services/browser-automation/chrome-setting.ts @@ -1,7 +1,8 @@ +import { configuration } from "../../configuration" import * as vscode from "vscode" -const INTEGRATED_BROWSER = "kilo-code.new.agentManager.browser" -const BROWSER_AUTOMATION = "kilo-code.new.browserAutomation" +const INTEGRATED_BROWSER = "bharatcode-agent.agentManager.browser" +const BROWSER_AUTOMATION = "bharatcode-agent.browserAutomation" /** * Read the Chrome preference for the Agent Manager Integrated Browser. @@ -11,19 +12,16 @@ const BROWSER_AUTOMATION = "kilo-code.new.browserAutomation" * stays independent. */ export function integratedBrowserUseSystemChrome(): boolean { - return vscode.workspace.getConfiguration(INTEGRATED_BROWSER).get("useSystemChrome", true) + return configuration(INTEGRATED_BROWSER).get("useSystemChrome", true) } export function integratedBrowserFallback(remote = vscode.env.remoteName): boolean { - return ( - remote === "wsl" && - vscode.workspace.getConfiguration(INTEGRATED_BROWSER).inspect("useSystemChrome")?.globalValue == null - ) + return remote === "wsl" && configuration(INTEGRATED_BROWSER).inspect("useSystemChrome")?.globalValue == null } /** Keep the settings payload and effective link destination in sync. */ export function integratedBrowserLinkDestination() { - const value = vscode.workspace.getConfiguration(INTEGRATED_BROWSER).get("openLinksIn", "integrated") + const value = configuration(INTEGRATED_BROWSER).get("openLinksIn", "integrated") return value === "external" ? "external" : "integrated" } @@ -37,9 +35,9 @@ export function integratedBrowserLinkDestination() { * the current key is application-scoped and cannot store them. */ export async function migrateIntegratedBrowserUseSystemChrome(): Promise { - const browser = vscode.workspace.getConfiguration(INTEGRATED_BROWSER) + const browser = configuration(INTEGRATED_BROWSER) if (browser.inspect?.("useSystemChrome")?.globalValue !== undefined) return - const value = vscode.workspace.getConfiguration(BROWSER_AUTOMATION).inspect?.("useSystemChrome")?.globalValue + const value = configuration(BROWSER_AUTOMATION).inspect?.("useSystemChrome")?.globalValue if (value === undefined) return await browser.update("useSystemChrome", value, vscode.ConfigurationTarget.Global) } diff --git a/packages/kilo-vscode/src/services/cli-backend/server-manager.ts b/packages/kilo-vscode/src/services/cli-backend/server-manager.ts index 435c8889..e50f4e20 100644 --- a/packages/kilo-vscode/src/services/cli-backend/server-manager.ts +++ b/packages/kilo-vscode/src/services/cli-backend/server-manager.ts @@ -1,3 +1,4 @@ +import { configuration } from "../../configuration" import { type ChildProcess } from "child_process" import { spawn } from "../../util/process" import * as crypto from "crypto" @@ -98,7 +99,7 @@ export class ServerManager { const extraEnv = await this.env?.() return new Promise((resolve, reject) => { console.log("[BharatCode] ServerManager: 🎬 Spawning CLI process:", cliPath, ["serve", "--port", "0"]) - const cfg = vscode.workspace.getConfiguration("kilo-code.new") + const cfg = configuration("bharatcode-agent") const claudeCompat = cfg.get("claudeCodeCompat", false) const claudeMigration = resolveClaudeMigrationEnv( { ...process.env, ...(extraEnv ?? {}) }, @@ -119,7 +120,7 @@ export class ServerManager { // trust store (Windows cert store, macOS keychain, Linux /etc/ssl). // Mirrors VS Code's `http.systemCertificates` default (true). // - Allow users behind MITM proxies to point at a custom CA bundle via - // `kilo-code.new.extraCaCerts` (NODE_EXTRA_CA_CERTS). + // `bharatcode-agent.extraCaCerts` (NODE_EXTRA_CA_CERTS). // - Honor VS Code's `http.proxyStrictSSL=false` as an explicit opt-out // from verification, matching what VS Code already does for its own // requests. Users explicitly set that; we don't flip it ourselves. diff --git a/packages/kilo-vscode/src/services/code-actions/code-action-provider.ts b/packages/kilo-vscode/src/services/code-actions/code-action-provider.ts index 62c61575..797525f8 100644 --- a/packages/kilo-vscode/src/services/code-actions/code-action-provider.ts +++ b/packages/kilo-vscode/src/services/code-actions/code-action-provider.ts @@ -15,25 +15,25 @@ export class KiloCodeActionProvider implements vscode.CodeActionProvider { const actions: vscode.CodeAction[] = [] const add = new vscode.CodeAction("Add to BharatCode", vscode.CodeActionKind.RefactorRewrite) - add.command = { command: "kilo-code.new.addToContext", title: "Add to BharatCode" } + add.command = { command: "bharatcode-agent.addToContext", title: "Add to BharatCode" } actions.push(add) const hasDiagnostics = context.diagnostics.length > 0 if (hasDiagnostics) { const fix = new vscode.CodeAction("Fix with BharatCode", vscode.CodeActionKind.QuickFix) - fix.command = { command: "kilo-code.new.fixCode", title: "Fix with BharatCode" } + fix.command = { command: "bharatcode-agent.fixCode", title: "Fix with BharatCode" } fix.isPreferred = true actions.push(fix) } if (!hasDiagnostics) { const explain = new vscode.CodeAction("Explain with BharatCode", vscode.CodeActionKind.RefactorRewrite) - explain.command = { command: "kilo-code.new.explainCode", title: "Explain with BharatCode" } + explain.command = { command: "bharatcode-agent.explainCode", title: "Explain with BharatCode" } actions.push(explain) const improve = new vscode.CodeAction("Improve with BharatCode", vscode.CodeActionKind.RefactorRewrite) - improve.command = { command: "kilo-code.new.improveCode", title: "Improve with BharatCode" } + improve.command = { command: "bharatcode-agent.improveCode", title: "Improve with BharatCode" } actions.push(improve) } diff --git a/packages/kilo-vscode/src/services/code-actions/register-code-actions.ts b/packages/kilo-vscode/src/services/code-actions/register-code-actions.ts index e04e0962..51151132 100644 --- a/packages/kilo-vscode/src/services/code-actions/register-code-actions.ts +++ b/packages/kilo-vscode/src/services/code-actions/register-code-actions.ts @@ -13,7 +13,7 @@ export function registerCodeActions( ): void { const target = () => (agentManager?.isActive() ? agentManager : (activeTabProvider?.() ?? provider)) const reveal = async () => { - await vscode.commands.executeCommand("kilo-code.SidebarProvider.focus") + await vscode.commands.executeCommand("bharatcode-agent.SidebarProvider.focus") await provider.waitForReady() } // Only the sidebar `provider` branch used to await readiness before @@ -41,7 +41,7 @@ export function registerCodeActions( } context.subscriptions.push( - vscode.commands.registerCommand("kilo-code.new.explainCode", async () => { + vscode.commands.registerCommand("bharatcode-agent.explainCode", async () => { const ctx = getEditorContext() if (!ctx) return const prompt = createPrompt("EXPLAIN", { @@ -55,7 +55,7 @@ export function registerCodeActions( provider.postMessage({ type: "triggerTask", text: prompt, injectedTitle: "Explain selected code" }) }), - vscode.commands.registerCommand("kilo-code.new.fixCode", async () => { + vscode.commands.registerCommand("bharatcode-agent.fixCode", async () => { const ctx = getEditorContext() if (!ctx) return const prompt = createPrompt("FIX", { @@ -70,7 +70,7 @@ export function registerCodeActions( provider.postMessage({ type: "triggerTask", text: prompt, injectedTitle: "Fix code problems" }) }), - vscode.commands.registerCommand("kilo-code.new.improveCode", async () => { + vscode.commands.registerCommand("bharatcode-agent.improveCode", async () => { const ctx = getEditorContext() if (!ctx) return const prompt = createPrompt("IMPROVE", { @@ -84,7 +84,7 @@ export function registerCodeActions( provider.postMessage({ type: "triggerTask", text: prompt, injectedTitle: "Improve selected code" }) }), - vscode.commands.registerCommand("kilo-code.new.addToContext", async () => { + vscode.commands.registerCommand("bharatcode-agent.addToContext", async () => { const ctx = getEditorContext() if (!ctx) return const view = lastFocusedChat?.() ?? target() @@ -101,7 +101,7 @@ export function registerCodeActions( }) }), - vscode.commands.registerCommand("kilo-code.new.focusChatInput", async () => { + vscode.commands.registerCommand("bharatcode-agent.focusChatInput", async () => { const view = target() if (!(await revealTarget(view))) return view.postMessage({ type: "action", action: "focusInput" }) @@ -113,7 +113,7 @@ export function registerCodeActions( // focus; invoking straight from the palette sidesteps that path // entirely, the same way terminalAddToContext etc. do. Toggles: the // webview closes the search bar itself if it's already open. - vscode.commands.registerCommand("kilo-code.new.toggleChatSearch", async () => { + vscode.commands.registerCommand("bharatcode-agent.toggleChatSearch", async () => { const view = target() if (!(await revealTarget(view))) return view.postMessage({ type: "action", action: "focusSearch" }) diff --git a/packages/kilo-vscode/src/services/code-actions/register-terminal-actions.ts b/packages/kilo-vscode/src/services/code-actions/register-terminal-actions.ts index 01afd20f..7da2dedf 100644 --- a/packages/kilo-vscode/src/services/code-actions/register-terminal-actions.ts +++ b/packages/kilo-vscode/src/services/code-actions/register-terminal-actions.ts @@ -11,12 +11,12 @@ export function registerTerminalActions( ): void { const target = () => (agentManager?.isActive() ? agentManager : provider) const reveal = async () => { - await vscode.commands.executeCommand("kilo-code.SidebarProvider.focus") + await vscode.commands.executeCommand("bharatcode-agent.SidebarProvider.focus") await provider.waitForReady() } context.subscriptions.push( - vscode.commands.registerCommand("kilo-code.new.terminalAddToContext", async (args: any) => { + vscode.commands.registerCommand("bharatcode-agent.terminalAddToContext", async (args: any) => { let content = args?.selection as string | undefined if (!content) { content = (await getTerminalContents(-1)).content @@ -37,7 +37,7 @@ export function registerTerminalActions( view.postMessage({ type: "action", action: "focusInput" }) }), - vscode.commands.registerCommand("kilo-code.new.terminalFixCommand", async (args: any) => { + vscode.commands.registerCommand("bharatcode-agent.terminalFixCommand", async (args: any) => { let content = args?.selection as string | undefined if (!content) { content = (await getTerminalContents(1)).content @@ -57,7 +57,7 @@ export function registerTerminalActions( view.postMessage({ type: "triggerTask", text: prompt, injectedTitle: "Fix terminal command" }) }), - vscode.commands.registerCommand("kilo-code.new.terminalExplainCommand", async (args: any) => { + vscode.commands.registerCommand("bharatcode-agent.terminalExplainCommand", async (args: any) => { let content = args?.selection as string | undefined if (!content) { content = (await getTerminalContents(1)).content diff --git a/packages/kilo-vscode/src/services/commit-message/__tests__/index.spec.ts b/packages/kilo-vscode/src/services/commit-message/__tests__/index.spec.ts index 2a8e9d85..4849e768 100644 --- a/packages/kilo-vscode/src/services/commit-message/__tests__/index.spec.ts +++ b/packages/kilo-vscode/src/services/commit-message/__tests__/index.spec.ts @@ -66,11 +66,11 @@ describe("commit-message service", () => { expect(disposables.length).toBeGreaterThan(0) }) - it("registers the kilo-code.new.generateCommitMessage command", () => { + it("registers the bharatcode-agent.generateCommitMessage command", () => { registerCommitMessageService(mockContext, mockConnectionService) expect(vscode.commands.registerCommand).toHaveBeenCalledWith( - "kilo-code.new.generateCommitMessage", + "bharatcode-agent.generateCommitMessage", expect.any(Function), ) }) diff --git a/packages/kilo-vscode/src/services/commit-message/index.ts b/packages/kilo-vscode/src/services/commit-message/index.ts index 7f17932d..ff0179c5 100644 --- a/packages/kilo-vscode/src/services/commit-message/index.ts +++ b/packages/kilo-vscode/src/services/commit-message/index.ts @@ -34,7 +34,7 @@ export function registerCommitMessageService( connectionService: KiloConnectionService, ): vscode.Disposable[] { const command = vscode.commands.registerCommand( - "kilo-code.new.generateCommitMessage", + "bharatcode-agent.generateCommitMessage", async (arg?: vscode.SourceControl) => { const extension = vscode.extensions.getExtension("vscode.git") if (!extension) { diff --git a/packages/kilo-vscode/src/services/i18n/index.ts b/packages/kilo-vscode/src/services/i18n/index.ts index 1090b84b..1137dfd6 100644 --- a/packages/kilo-vscode/src/services/i18n/index.ts +++ b/packages/kilo-vscode/src/services/i18n/index.ts @@ -1,3 +1,4 @@ +import { configuration } from "../../configuration" import { dict as ar } from "./ar" import { dict as br } from "./br" import { dict as bs } from "./bs" @@ -63,13 +64,13 @@ export function resolveLocale(lang: string | undefined): string { } export function selectedLocale(vscode: typeof import("vscode")): string { - const cfg = vscode.workspace.getConfiguration("kilo-code.new") + const cfg = configuration("bharatcode-agent", undefined, vscode.workspace) const lang = cfg.get("language") return resolveLocale(lang || vscode.env.language) } export function getCommitMessageLanguage(vscode: typeof import("vscode")): string { - const cfg = vscode.workspace.getConfiguration("kilo-code.new") + const cfg = configuration("bharatcode-agent", undefined, vscode.workspace) const commitLang = cfg.get("languageCommitMessage") ?? "sync" if (commitLang === "sync") return selectedLocale(vscode) return resolveLocale(commitLang) diff --git a/packages/kilo-vscode/src/shared/bharatcode-catalog.ts b/packages/kilo-vscode/src/shared/bharatcode-catalog.ts new file mode 100644 index 00000000..b064a376 --- /dev/null +++ b/packages/kilo-vscode/src/shared/bharatcode-catalog.ts @@ -0,0 +1,24 @@ +import type { ProviderFailure } from "@kilocode/sdk/v2/client" + +/** Only typed, sanitized failures enter the webview. Never display a response body or credential. */ +export function catalogNotice(input: { + ready: boolean + connected: string[] + failures: ProviderFailure[] + hasModels: boolean +}) { + const failure = input.failures.find((item) => item.providerID === "bharatcode") + if (!input.ready) return { key: "bharatcode.catalog.loading", action: undefined } + if (failure) { + const signIn = failure.kind === "unauthorized" || failure.kind === "unauthenticated" + return { + key: `bharatcode.catalog.${failure.kind}`, + vars: { status: failure.status ?? "" }, + action: signIn ? ("signIn" as const) : ("retry" as const), + } + } + if (input.hasModels) return undefined + return input.connected.includes("bharatcode") + ? { key: "bharatcode.catalog.empty", action: "retry" as const } + : { key: "bharatcode.catalog.signIn", action: "signIn" as const } +} diff --git a/packages/kilo-vscode/src/utils.ts b/packages/kilo-vscode/src/utils.ts index 1cd31f30..8da0e7b8 100644 --- a/packages/kilo-vscode/src/utils.ts +++ b/packages/kilo-vscode/src/utils.ts @@ -1,3 +1,4 @@ +import { configuration } from "./configuration" import * as crypto from "crypto" import * as vscode from "vscode" import { buildCspString } from "./webview-html-utils" @@ -14,7 +15,7 @@ function clamp(size: number) { } export function getWebviewFontSize(): number { - const raw = vscode.workspace.getConfiguration("kilo-code.new").get("fontSize", 13) + const raw = configuration("bharatcode-agent").get("fontSize", 13) return clamp(raw) } diff --git a/packages/kilo-vscode/tests/bharatcode-catalog-recovery.spec.ts b/packages/kilo-vscode/tests/bharatcode-catalog-recovery.spec.ts new file mode 100644 index 00000000..328e77c2 --- /dev/null +++ b/packages/kilo-vscode/tests/bharatcode-catalog-recovery.spec.ts @@ -0,0 +1,82 @@ +import { expect, test } from "@playwright/test" + +test("an empty catalog has an actionable error and recovers without reloading the chat", async ({ page }, testInfo) => { + test.setTimeout(180_000) + await page.addInitScript(() => { + ;(window as any).__catalogRefreshes = 0 + ;(window as any).acquireVsCodeApi = () => ({ + getState: () => undefined, + setState: () => {}, + postMessage: (message: any) => { + if (message.type !== "requestProviders") return + const send = (data: unknown) => window.postMessage(data, window.location.origin) + if (!message.refresh) { + setTimeout( + () => + send({ type: "providersLoadFailed", failure: { providerID: "bharatcode", kind: "http", status: 503 } }), + 20, + ) + return + } + ;(window as any).__catalogRefreshes++ + send({ type: "providersRefreshing" }) + setTimeout( + () => + send({ + type: "providersLoaded", + providers: { + bharatcode: { + id: "bharatcode", + name: "BharatCode", + models: { "glm-5.3-flash": { id: "glm-5.3-flash", name: "GLM 5.3 Flash" } }, + }, + }, + connected: ["bharatcode"], + defaults: { bharatcode: "glm-5.3-flash" }, + defaultSelection: { providerID: "bharatcode", modelID: "glm-5.3-flash" }, + authMethods: {}, + authStates: { bharatcode: "oauth" }, + ready: true, + failures: [], + }), + 100, + ) + }, + }) + }) + await page.goto( + "/iframe.html?id=shared--model-selector-bharatcode-recovery&viewMode=story&globals=theme:kilo-vscode;vscodeTheme:dark-modern", + ) + await page.waitForSelector("#storybook-root button", { timeout: 120_000 }) + const trigger = page.getByRole("button", { name: "Select model: Models unavailable" }) + await expect(trigger).toBeEnabled() + await trigger.click() + await expect(page.getByRole("status")).toContainText("HTTP 503") + await page.screenshot({ path: testInfo.outputPath("catalog-error.png") }) + const retry = page.getByRole("button", { name: "Retry model catalog" }) + await retry.focus() + await page.keyboard.press("Enter") + await expect(page.getByRole("treeitem", { name: /GLM 5.3 Flash/ })).toBeVisible() + expect(await page.evaluate(() => (window as any).__catalogRefreshes)).toBe(1) + await expect(page.getByRole("button", { name: "Retry model catalog" })).toHaveCount(0) + await expect(page.locator(".model-selector-notice")).toHaveCount(0) + + await page.evaluate(() => + window.postMessage( + { + type: "providersLoadFailed", + failure: { providerID: "bharatcode", kind: "network" }, + }, + window.location.origin, + ), + ) + await expect(page.getByRole("treeitem", { name: /GLM 5.3 Flash/ })).toBeVisible() + await expect(page.getByRole("status")).toContainText("Your chats and sign-in are unchanged") + await page.getByRole("button", { name: "Retry model catalog" }).focus() + await page.keyboard.press("Enter") + await expect.poll(() => page.evaluate(() => (window as any).__catalogRefreshes)).toBe(2) + await expect(page.getByRole("button", { name: "Retry model catalog" })).toHaveCount(0) + await expect(page.getByRole("treeitem", { name: /GLM 5.3 Flash/ })).toBeVisible() + await expect(page.locator(".model-selector-notice")).toHaveCount(0) + await page.screenshot({ path: testInfo.outputPath("catalog-recovered.png") }) +}) diff --git a/packages/kilo-vscode/tests/test_identity.py b/packages/kilo-vscode/tests/test_identity.py new file mode 100644 index 00000000..ad988368 --- /dev/null +++ b/packages/kilo-vscode/tests/test_identity.py @@ -0,0 +1,185 @@ +"""Small synthetic VSIXes only: no installed extension, profile or credential access.""" + +import importlib.util +import io +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +import zipfile + +spec = importlib.util.spec_from_file_location("audit_vsix", Path(__file__).parents[1] / "script/audit-vsix.py") +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +VERSION = "7.8.113" + + +def fixture(target="linux-x64", publisher="bharatcode", name="bharatcode-agent", xml=None, bundle=None, extra=None, display="BharatCode Agent"): + binary = "extension/bin/bharatcode" + (".exe" if target.startswith("win32-") else "") + entries = { + "extension/package.json": json.dumps({"publisher": publisher, "name": name, "displayName": display, "version": VERSION}), + "extension.vsixmanifest": xml or ( + '' + f'' + f'{display}' + '' + ), + "extension/dist/extension.js": bundle or f'"{publisher}.{name}"; "{display}"; "Sign in with BharatCode"', + "extension/LICENSE.txt": "BharatCode modifications\nKilo Code", + binary: "synthetic binary", + } + entries.update(extra or {}) + stream = io.BytesIO() + with zipfile.ZipFile(stream, "w") as archive: + for path, data in entries.items(): + archive.writestr(path, data) + stream.seek(0) + return stream + + +class IdentityTests(unittest.TestCase): + def test_all_platforms(self): + for target in module.TARGETS: + with self.subTest(target=target): + module.audit(fixture(target), target, VERSION) + + def test_old_publisher(self): + with self.assertRaisesRegex(ValueError, "package identity"): + module.audit(fixture(publisher="thenabbu"), "linux-x64", VERSION) + + def test_cli_launcher_listing(self): + with self.assertRaisesRegex(ValueError, "package identity"): + module.audit(fixture(name="bharatcode"), "linux-x64", VERSION) + + def test_previous_listing(self): + with self.assertRaisesRegex(ValueError, "package identity"): + module.audit(fixture(name="bharatcode-vscode"), "linux-x64", VERSION) + + def test_display_name(self): + with self.assertRaisesRegex(ValueError, "package display name"): + module.audit(fixture(display="BharatCode for VS Code"), "linux-x64", VERSION) + with zipfile.ZipFile(fixture()) as archive: + xml = archive.read("extension.vsixmanifest").decode().replace("BharatCode Agent", "BharatCode") + with self.assertRaisesRegex(ValueError, "VSIX XML display name"): + module.audit(fixture(xml=xml), "linux-x64", VERSION) + with self.assertRaisesRegex(ValueError, "compiled display name"): + module.audit(fixture(bundle='"bharatcode.bharatcode-agent"; "Sign in with BharatCode"'), "linux-x64", VERSION) + + def test_json_only_relabel(self): + xml = '' + with self.assertRaisesRegex(ValueError, "VSIX XML Publisher"): + module.audit(fixture(xml=xml), "linux-x64", VERSION) + + def test_stale_compiled_runtime(self): + with self.assertRaisesRegex(ValueError, "compiled extension identity"): + module.audit(fixture(bundle='"thenabbu.bharatcode-vscode"; "Sign in with BharatCode"'), "linux-x64", VERSION) + + def test_stale_webview(self): + for identity in ["thenabbu.bharatcode-vscode", "bharatcode.bharatcode-vscode", "bharatcode.bharatcode"]: + with self.subTest(identity=identity), self.assertRaisesRegex(ValueError, "identity|publisher"): + module.audit(fixture(extra={"extension/dist/webview/chunk.js": f'"{identity}"'}), "linux-x64", VERSION) + + def test_wrong_platform(self): + with self.assertRaisesRegex(ValueError, "VSIX XML TargetPlatform"): + module.audit(fixture("win32-x64"), "linux-x64", VERSION) + + def test_wrong_binary(self): + with self.assertRaisesRegex(ValueError, "platform binary"): + module.audit(fixture(extra={"extension/bin/bharatcode.exe": "wrong"}), "linux-x64", VERSION) + + def test_source_map(self): + with self.assertRaisesRegex(ValueError, "sourcemaps"): + module.audit(fixture(extra={"extension/dist/extension.js.map": "{}"}), "linux-x64", VERSION) + + def test_version(self): + with self.assertRaisesRegex(ValueError, "package version"): + module.audit(fixture(), "linux-x64", "7.8.114") + + def test_license(self): + with self.assertRaisesRegex(ValueError, "license attribution"): + module.audit(fixture(extra={"extension/LICENSE.txt": "MIT"}), "linux-x64", VERSION) + + def test_signin(self): + with self.assertRaisesRegex(ValueError, "compiled website sign-in"): + module.audit(fixture(bundle='"bharatcode.bharatcode-agent"; "BharatCode Agent"'), "linux-x64", VERSION) + + def test_exact_matrix_and_hashes(self): + with tempfile.TemporaryDirectory(prefix="bharatcode-identity-") as tmp: + root = Path(tmp) + for target in module.TARGETS: + (root / f"bharatcode-vscode-{target}.vsix").write_bytes(fixture(target).getvalue()) + rows = module.inspect(root, VERSION) + self.assertEqual(len(rows), 8) + self.assertTrue(all(len(row["sha256"]) == 64 and row["size"] > 0 for row in rows)) + self.assertFalse((root / "candidate.json").exists()) + (root / "unexpected.vsix").write_bytes(b"not a candidate") + with self.assertRaisesRegex(ValueError, "target set"): + module.inspect(root, VERSION) + + def test_missing_platform(self): + with tempfile.TemporaryDirectory(prefix="bharatcode-identity-") as tmp: + with self.assertRaisesRegex(ValueError, "target set"): + module.inspect(Path(tmp), VERSION) + + def test_versioned_release_matrix(self): + with tempfile.TemporaryDirectory(prefix="bharatcode-identity-") as tmp: + root = Path(tmp) + for target in module.TARGETS: + (root / f"bharatcode-vscode-{target}-{VERSION}.vsix").write_bytes(fixture(target).getvalue()) + self.assertEqual(len(module.inspect(root, VERSION, versioned=True)), 8) + + def test_receipt_and_checksums_bind_exact_files(self): + with tempfile.TemporaryDirectory(prefix="bharatcode-identity-") as tmp: + root = Path(tmp) + for target in module.TARGETS: + (root / f"bharatcode-vscode-{target}.vsix").write_bytes(fixture(target).getvalue()) + result = subprocess.run( + [sys.executable, "-B", module.__file__, "--dir", tmp, "--version", VERSION, "--receipt"], + env={**os.environ, "GITHUB_SHA": "a" * 40, "GITHUB_RUN_ID": "123", "GITHUB_RUN_ATTEMPT": "2"}, + capture_output=True, text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + receipt = json.loads((root / "candidate.json").read_text()) + self.assertEqual(receipt["extensionId"], "bharatcode.bharatcode-agent") + self.assertEqual(receipt["publisher"], "bharatcode") + self.assertEqual(receipt["source"], "a" * 40) + self.assertEqual(receipt["run"], "123") + self.assertEqual(receipt["attempt"], "2") + self.assertEqual({row["target"] for row in receipt["files"]}, set(module.TARGETS)) + for row in receipt["files"]: + self.assertEqual(row["sha256"], hashlib.sha256((root / row["name"]).read_bytes()).hexdigest()) + self.assertEqual( + (root / "SHA256SUMS").read_text(), + "".join(row["sha256"] + " " + row["name"] + "\n" for row in receipt["files"]), + ) + # A failed re-audit must not replace existing evidence. + original = (root / "candidate.json").read_bytes() + (root / "bharatcode-vscode-linux-x64.vsix").write_bytes(fixture(publisher="thenabbu").getvalue()) + result = subprocess.run( + [sys.executable, "-B", module.__file__, "--dir", tmp, "--version", VERSION, "--receipt"], + capture_output=True, text=True, + ) + self.assertNotEqual(result.returncode, 0) + self.assertEqual((root / "candidate.json").read_bytes(), original) + + def test_receipt_requires_provenance(self): + with tempfile.TemporaryDirectory(prefix="bharatcode-identity-") as tmp: + root = Path(tmp) + (root / "bharatcode-vscode-linux-x64.vsix").write_bytes(fixture().getvalue()) + result = subprocess.run( + [sys.executable, "-B", module.__file__, "--dir", tmp, "--version", VERSION, + "--target", "linux-x64", "--receipt"], + env={key: value for key, value in os.environ.items() if not key.startswith("GITHUB_")}, + capture_output=True, text=True, + ) + self.assertNotEqual(result.returncode, 0) + self.assertFalse((root / "candidate.json").exists()) + self.assertFalse((root / "SHA256SUMS").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/kilo-vscode/tests/test_reuse_candidate.py b/packages/kilo-vscode/tests/test_reuse_candidate.py new file mode 100644 index 00000000..fa73bf49 --- /dev/null +++ b/packages/kilo-vscode/tests/test_reuse_candidate.py @@ -0,0 +1,200 @@ +"""Tiny eight-platform packaging fixtures; no real profiles, binaries or network.""" + +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import stat +import tempfile +import unittest +from unittest.mock import patch +import warnings +import zipfile + +from test_identity import fixture + +spec = importlib.util.spec_from_file_location("reuse_candidate", Path(__file__).parents[1] / "script/reuse-candidate.py") +reuse = importlib.util.module_from_spec(spec) +spec.loader.exec_module(reuse) + + +def package(target, changes=None, mode=None, duplicate=False, parent=False): + entries = { + "extension/bin/kilo-sandbox-mutation-worker.js": "worker", + "extension/bin/tree-sitter/tree-sitter.wasm": "runtime", + "extension/bin/tree-sitter/tree-sitter-bash.wasm": "grammar", + } + if target.startswith(("linux-", "alpine-")): + entries.update({ + "extension/bin/kilo-sandbox-network-relay.js": "relay", + "extension/bin/kilo-sandbox-seccomp": "seccomp", + "extension/bin/licenses/sandbox-runtime/LICENSE": "license", + }) + entries.update(changes or {}) + result = io.BytesIO() + original = {"name": "bharatcode-vscode", "display": "BharatCode for VS Code"} if parent else {} + with zipfile.ZipFile(fixture(target, extra=entries, **original)) as source, zipfile.ZipFile(result, "w") as archive: + for name in source.namelist(): + info = zipfile.ZipInfo(name) + info.create_system = 3 + info.external_attr = (stat.S_IFREG | (0o755 if name.endswith(("bharatcode", ".exe", "seccomp", ".wasm")) else 0o644)) << 16 + if mode and name == mode[0]: + info.external_attr = mode[1] << 16 + archive.writestr(info, source.read(name)) + if duplicate: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + archive.writestr("extension/bin/kilo-sandbox-mutation-worker.js", "duplicate") + return result.getvalue() + + +class ReuseTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="bharatcode-reuse-") + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.stage = self.root / "stage" + self.out = self.root / "out" + self.out.mkdir() + self.archive = self.root / "artifact.zip" + self.meta = self.root / "metadata.json" + self.metadata = { + "id": reuse.ARTIFACT, "expired": False, "name": f"vscode-oauth-{reuse.SOURCE}", + "workflow_run": {"id": int(reuse.RUN), "head_sha": reuse.SOURCE}, + } + self.meta.write_text(json.dumps(self.metadata)) + self.files = {f"bharatcode-vscode-{target}.vsix": package(target, parent=True) for target in reuse.audit.TARGETS} + self.environ = patch.dict(os.environ, {"GITHUB_SHA": "a" * 40, "GITHUB_RUN_ID": "123", "GITHUB_RUN_ATTEMPT": "1"}) + self.environ.start() + self.addCleanup(self.environ.stop) + + def parent(self, extra=None, symlink=False): + rows = [{"name": name, "target": name.removeprefix("bharatcode-vscode-").removesuffix(".vsix"), + "size": len(data), "sha256": hashlib.sha256(data).hexdigest()} for name, data in sorted(self.files.items())] + receipt = json.dumps({"source": reuse.SOURCE, "run": reuse.RUN, "attempt": "1", "version": reuse.VERSION, + "extensionId": "bharatcode.bharatcode-vscode", "files": rows}).encode() + # Only the pinned digest is replaced: real validation/extraction/auditing runs on tiny fixtures. + pin = patch.object(reuse, "RECEIPT", hashlib.sha256(receipt).hexdigest()) + pin.start() + self.addCleanup(pin.stop) + entries = {**self.files, "candidate.json": receipt, + "SHA256SUMS": "".join(row["sha256"] + " " + row["name"] + "\n" for row in rows)} + entries.update(extra or {}) + with zipfile.ZipFile(self.archive, "w") as archive: + for name, data in entries.items(): + info = zipfile.ZipInfo(name) + info.external_attr = (stat.S_IFLNK | 0o777 if symlink else stat.S_IFREG | 0o644) << 16 + archive.writestr(info, data) + + def prepare(self): + reuse.prepare(self.archive, self.meta, self.stage) + for target in reuse.audit.TARGETS: + (self.out / f"bharatcode-vscode-{target}.vsix").write_bytes(package(target)) + + def test_all_eight_extraction_and_derived_receipt(self): + self.parent() + self.prepare() + for target in reuse.audit.TARGETS: + binary = "bharatcode.exe" if target.startswith("win32-") else "bharatcode" + folder = self.stage / "dist" / reuse.directory(target) / "bin" + self.assertEqual((folder / binary).read_bytes(), b"synthetic binary") + self.assertEqual(stat.S_IMODE((folder / binary).stat().st_mode), 0o755) + self.assertFalse((folder.parent / "package.json").exists()) + reuse.verify(self.stage, self.out) + receipt = json.loads((self.out / "candidate.json").read_text()) + self.assertEqual(receipt["kind"], "derived-backend-reuse") + self.assertEqual(receipt["extensionId"], "bharatcode.bharatcode-agent") + self.assertEqual(receipt["name"], "bharatcode-agent") + parent = json.loads((self.stage / "parent/candidate.json").read_text()) + self.assertEqual(parent["extensionId"], "bharatcode.bharatcode-vscode") + self.assertEqual(receipt["parent"]["artifact"], reuse.ARTIFACT) + self.assertEqual(receipt["parent"]["candidateSha256"], reuse.RECEIPT) + self.assertEqual(receipt["source"], "a" * 40) + self.assertEqual(receipt["parent"]["source"], reuse.SOURCE) + self.assertEqual(len(receipt["files"]), 8) + for row in receipt["files"]: + self.assertEqual(row["backend"]["payloadSha256"], row["backend"]["parentPayloadSha256"]) + self.assertEqual(row["parent"]["sha256"], hashlib.sha256(self.files[row["name"]]).hexdigest()) + self.assertNotEqual(row["sha256"], row["parent"]["sha256"]) + self.assertEqual((self.out / "SHA256SUMS").read_text(), "".join(row["sha256"] + " " + row["name"] + "\n" for row in receipt["files"])) + + def test_unapproved_receipt(self): + with self.assertRaisesRegex(ValueError, "receipt hash"): + reuse.candidate(b"{}") + + def test_wrong_or_expired_artifact(self): + for field, value in [("id", 123), ("expired", True), ("name", "other"), ("workflow_run", {"id": 123, "head_sha": reuse.SOURCE})]: + with self.subTest(field=field), self.assertRaises(ValueError): + reuse.metadata({**self.metadata, field: value}) + + def test_outer_traversal(self): + self.parent({"../escape": "no"}) + with self.assertRaisesRegex(ValueError, "unexpected artifact entries"): + self.prepare() + self.assertFalse(self.stage.exists()) + self.assertFalse((self.root / "escape").exists()) + + def test_outer_symlink(self): + self.parent(symlink=True) + with self.assertRaisesRegex(ValueError, "non-regular"): + self.prepare() + + def test_corrupt_parent_vsix(self): + self.parent({"bharatcode-vscode-linux-x64.vsix": b"corrupt"}) + with self.assertRaisesRegex(ValueError, "parent VSIX hash"): + self.prepare() + self.assertFalse((self.stage / "dist").exists()) + + def test_existing_destination_is_never_deleted(self): + self.parent() + self.stage.mkdir() + sentinel = self.stage / "sentinel" + sentinel.write_text("keep") + with self.assertRaisesRegex(ValueError, "must not exist"): + self.prepare() + self.assertEqual(sentinel.read_text(), "keep") + + def test_unsafe_backend_entries(self): + for name in ["../escape", "/escape", "C:/escape", "tree-sitter/../escape", "tree-sitter\\escape", "unexpected"]: + with self.subTest(name=name), self.assertRaisesRegex(ValueError, "unexpected backend path"): + reuse.payload(io.BytesIO(package("linux-x64", {"extension/bin/" + name: "bad"})), "linux-x64") + for mode in [stat.S_IFLNK | 0o777, stat.S_IFREG | 0o4755]: + with self.subTest(mode=mode), self.assertRaisesRegex(ValueError, "non-regular|unsafe backend mode"): + reuse.payload(io.BytesIO(package("linux-x64", mode=("extension/bin/bharatcode", mode))), "linux-x64") + with self.assertRaisesRegex(ValueError, "duplicate ZIP entries"): + reuse.payload(io.BytesIO(package("linux-x64", duplicate=True)), "linux-x64") + + def test_modified_binary_resource_or_mode_blocks_receipt(self): + self.parent() + self.prepare() + for name in ["bharatcode", "tree-sitter/tree-sitter.wasm", "licenses/sandbox-runtime/LICENSE", "kilo-sandbox-mutation-worker.js"]: + with self.subTest(name=name): + (self.out / "bharatcode-vscode-linux-x64.vsix").write_bytes(package("linux-x64", {"extension/bin/" + name: "changed"})) + with self.assertRaisesRegex(ValueError, "bytes or permissions changed"): + reuse.verify(self.stage, self.out) + self.assertFalse((self.out / "candidate.json").exists()) + self.assertFalse((self.out / "SHA256SUMS").exists()) + (self.out / "bharatcode-vscode-linux-x64.vsix").write_bytes(package("linux-x64", mode=("extension/bin/bharatcode", stat.S_IFREG | 0o644))) + with self.assertRaisesRegex(ValueError, "bytes or permissions changed"): + reuse.verify(self.stage, self.out) + + def test_stale_identity_missing_platform_and_parent_run_cannot_issue_receipt(self): + self.parent() + self.prepare() + file = self.out / "bharatcode-vscode-linux-x64.vsix" + file.write_bytes(package("linux-x64", {"extension/dist/extension.js": "old identity"})) + with self.assertRaisesRegex(ValueError, "compiled extension identity"): + reuse.verify(self.stage, self.out) + file.unlink() + with self.assertRaisesRegex(ValueError, "target set"): + reuse.verify(self.stage, self.out) + file.write_bytes(package("linux-x64")) + with patch.dict(os.environ, {"GITHUB_RUN_ID": reuse.RUN}), self.assertRaisesRegex(ValueError, "derived run provenance"): + reuse.verify(self.stage, self.out) + self.assertFalse((self.out / "candidate.json").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/kilo-vscode/tests/unit/agent-manager-arch.test.ts b/packages/kilo-vscode/tests/unit/agent-manager-arch.test.ts index 316c837a..57759656 100644 --- a/packages/kilo-vscode/tests/unit/agent-manager-arch.test.ts +++ b/packages/kilo-vscode/tests/unit/agent-manager-arch.test.ts @@ -555,10 +555,10 @@ describe("Agent Manager Worktree Actions", () => { contributes: { keybindings: { command: string; key?: string; mac?: string }[] } } const dialog = manifest.contributes.keybindings.find( - (item) => item.command === "kilo-code.new.agentManager.newWorktree", + (item) => item.command === "bharatcode-agent.agentManager.newWorktree", ) const quick = manifest.contributes.keybindings.find( - (item) => item.command === "kilo-code.new.agentManager.quickWorktree", + (item) => item.command === "bharatcode-agent.agentManager.quickWorktree", ) expect(dialog).toMatchObject({ key: "ctrl+n", mac: "cmd+n" }) @@ -573,7 +573,9 @@ describe("Agent Manager Worktree Actions", () => { contributes: { keybindings: { command: string; key?: string; mac?: string }[] } } const removed = manifest.contributes.keybindings.find((item) => item.command === "-workbench.actions.view.problems") - const manager = manifest.contributes.keybindings.find((item) => item.command === "kilo-code.new.agentManagerOpen") + const manager = manifest.contributes.keybindings.find( + (item) => item.command === "bharatcode-agent.agentManagerOpen", + ) expect(removed).toMatchObject({ key: "ctrl+shift+m", mac: "cmd+shift+m" }) expect(manager).toMatchObject({ key: "ctrl+shift+m", mac: "cmd+shift+m" }) @@ -607,8 +609,8 @@ describe("Agent Manager Worktree Actions", () => { it("forwards the quick-worktree command to immediate creation", () => { const source = fs.readFileSync(path.join(ROOT, "src/extension.ts"), "utf-8") - const start = source.indexOf('vscode.commands.registerCommand("kilo-code.new.agentManager.quickWorktree"') - const end = source.indexOf('vscode.commands.registerCommand("kilo-code.new.agentManager.openWorktree"', start) + const start = source.indexOf('vscode.commands.registerCommand("bharatcode-agent.agentManager.quickWorktree"') + const end = source.indexOf('vscode.commands.registerCommand("bharatcode-agent.agentManager.openWorktree"', start) const command = source.slice(start, end) expect(start).toBeGreaterThanOrEqual(0) diff --git a/packages/kilo-vscode/tests/unit/agent-manager-settings.test.ts b/packages/kilo-vscode/tests/unit/agent-manager-settings.test.ts index 59e8e43f..d31f0357 100644 --- a/packages/kilo-vscode/tests/unit/agent-manager-settings.test.ts +++ b/packages/kilo-vscode/tests/unit/agent-manager-settings.test.ts @@ -63,7 +63,9 @@ describe("Agent Manager settings navigation", () => { describe("Agent Manager application settings", () => { it("does not register a multi-project opt-in setting", async () => { const manifest = await Bun.file(join(ROOT, "package.json")).json() - expect(manifest.contributes.configuration.properties).not.toHaveProperty("kilo-code.new.experimental.multiProject") + expect(manifest.contributes.configuration.properties).not.toHaveProperty( + "bharatcode-agent.experimental.multiProject", + ) }) it.each([ @@ -80,7 +82,7 @@ describe("Agent Manager application settings", () => { const writes: unknown[] = [] vscode.workspace.getConfiguration = ((section?: string) => ({ get: (key: string, fallback: unknown) => - section === "kilo-code.new.agentManager" && values.has(key) ? values.get(key) : fallback, + section === "bharatcode-agent.agentManager" && values.has(key) ? values.get(key) : fallback, update: async (key: string, value: unknown, target: unknown) => { writes.push({ section, key, value, target }) values.set(key, value) @@ -99,13 +101,13 @@ describe("Agent Manager application settings", () => { await provider.handleUpdateSetting("agentManager.branchPrefix", "") expect(writes).toEqual([ { - section: "kilo-code.new.agentManager", + section: "bharatcode-agent.agentManager", key: "autoBranchNaming", value: !expected, target: vscode.ConfigurationTarget.Global, }, { - section: "kilo-code.new.agentManager", + section: "bharatcode-agent.agentManager", key: "branchPrefix", value: "", target: vscode.ConfigurationTarget.Global, @@ -121,7 +123,7 @@ describe("Agent Manager application settings", () => { describe("Claude migration application setting", () => { it("declares an opt-in application setting", () => { - expect(PACKAGE.contributes.configuration.properties["kilo-code.new.experimental.claudeMigration"]).toEqual({ + expect(PACKAGE.contributes.configuration.properties["bharatcode-agent.experimental.claudeMigration"]).toEqual({ type: "boolean", default: false, scope: "application", @@ -137,7 +139,7 @@ describe("Claude migration application setting", () => { const writes: unknown[] = [] vscode.workspace.getConfiguration = ((section?: string) => ({ get: (key: string, fallback: unknown) => - section === "kilo-code.new.experimental" && values.has(key) ? values.get(key) : fallback, + section === "bharatcode-agent.experimental" && values.has(key) ? values.get(key) : fallback, update: async (key: string, value: unknown, target: unknown) => { writes.push({ section, key, value, target }) values.set(key, value) @@ -152,7 +154,7 @@ describe("Claude migration application setting", () => { await provider.handleUpdateSetting("experimental.claudeMigration", true) expect(writes).toEqual([ { - section: "kilo-code.new.experimental", + section: "bharatcode-agent.experimental", key: "claudeMigration", value: true, target: vscode.ConfigurationTarget.Global, diff --git a/packages/kilo-vscode/tests/unit/agent-manager-terminal-destination.test.ts b/packages/kilo-vscode/tests/unit/agent-manager-terminal-destination.test.ts index eefda3d8..0718803a 100644 --- a/packages/kilo-vscode/tests/unit/agent-manager-terminal-destination.test.ts +++ b/packages/kilo-vscode/tests/unit/agent-manager-terminal-destination.test.ts @@ -23,7 +23,7 @@ describe("Agent Manager terminal destination", () => { }) it("watches only the terminal button destination setting", () => { - expect(affectsTerminalDestination(event("kilo-code.new.agentManager.terminalButtonDestination"))).toBe(true) + expect(affectsTerminalDestination(event("bharatcode-agent.agentManager.terminalButtonDestination"))).toBe(true) expect(affectsTerminalDestination(event("terminal.integrated.fontFamily"))).toBe(false) }) diff --git a/packages/kilo-vscode/tests/unit/attention.test.ts b/packages/kilo-vscode/tests/unit/attention.test.ts index 2d06f126..4f9052e4 100644 --- a/packages/kilo-vscode/tests/unit/attention.test.ts +++ b/packages/kilo-vscode/tests/unit/attention.test.ts @@ -450,14 +450,14 @@ describe("attention defaults", () => { } const properties = manifest.contributes.configuration.properties - expect(properties["kilo-code.new.attention.enabled"]?.default).toBe(false) - expect(properties["kilo-code.new.attention.notifications"]?.default).toBe(false) - expect(properties["kilo-code.new.attention.OSNotifications"]?.default).toBe(false) - expect(properties["kilo-code.new.attention.sound"]?.default).toBe("default") - expect(properties["kilo-code.new.attention.sound"]?.enum).toEqual(["default", "system", ...CustomSoundIDs]) - expect(properties["kilo-code.new.sounds.agentEnabled"]).toBeUndefined() - expect(properties["kilo-code.new.sounds.permissionsEnabled"]).toBeUndefined() - expect(properties["kilo-code.new.sounds.errorsEnabled"]).toBeUndefined() + expect(properties["bharatcode-agent.attention.enabled"]?.default).toBe(false) + expect(properties["bharatcode-agent.attention.notifications"]?.default).toBe(false) + expect(properties["bharatcode-agent.attention.OSNotifications"]?.default).toBe(false) + expect(properties["bharatcode-agent.attention.sound"]?.default).toBe("default") + expect(properties["bharatcode-agent.attention.sound"]?.enum).toEqual(["default", "system", ...CustomSoundIDs]) + expect(properties["bharatcode-agent.sounds.agentEnabled"]).toBeUndefined() + expect(properties["bharatcode-agent.sounds.permissionsEnabled"]).toBeUndefined() + expect(properties["bharatcode-agent.sounds.errorsEnabled"]).toBeUndefined() }) it("resolves global sound choices safely", () => { diff --git a/packages/kilo-vscode/tests/unit/auto-approve.test.ts b/packages/kilo-vscode/tests/unit/auto-approve.test.ts index 62717eb8..26009d4e 100644 --- a/packages/kilo-vscode/tests/unit/auto-approve.test.ts +++ b/packages/kilo-vscode/tests/unit/auto-approve.test.ts @@ -69,7 +69,7 @@ function config(initial: boolean, info: Record = {}) { set active(value: boolean) { state.active = value }, - emit(key = "kilo-code.new.autoApprove.enabled") { + emit(key = "bharatcode-agent.autoApprove.enabled") { for (const handler of handlers) handler({ affectsConfiguration: (name) => name === key }) }, } diff --git a/packages/kilo-vscode/tests/unit/bharatcode-catalog-ui.test.ts b/packages/kilo-vscode/tests/unit/bharatcode-catalog-ui.test.ts new file mode 100644 index 00000000..1f169114 --- /dev/null +++ b/packages/kilo-vscode/tests/unit/bharatcode-catalog-ui.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, test } from "bun:test" +import { catalogNotice } from "../../src/shared/bharatcode-catalog" + +const loaded = { ready: true, connected: ["bharatcode"], failures: [], hasModels: true } + +describe("BharatCode catalog recovery notice", () => { + test("loading is distinct from signed out or empty", () => { + expect(catalogNotice({ ...loaded, ready: false })?.key).toBe("bharatcode.catalog.loading") + expect(catalogNotice({ ...loaded, connected: [], hasModels: false })?.action).toBe("signIn") + expect(catalogNotice({ ...loaded, hasModels: false })?.action).toBe("retry") + }) + + test("catalog failures offer retry even when the provider was removed from connected", () => { + for (const kind of ["network", "http", "schema"] as const) { + const notice = catalogNotice({ + ...loaded, + connected: [], + hasModels: false, + failures: [{ providerID: "bharatcode", kind, status: 503 }], + }) + expect(notice?.key).toBe(`bharatcode.catalog.${kind}`) + expect(notice?.action).toBe("retry") + } + }) + + test("last-good models remain selectable while a refresh failure is explained", () => { + expect(catalogNotice({ ...loaded, failures: [{ providerID: "bharatcode", kind: "network" }] })?.action).toBe( + "retry", + ) + expect(catalogNotice(loaded)).toBeUndefined() + }) + + test("authentication failures ask for sign-in, not repeated network retries", () => { + for (const kind of ["unauthorized", "unauthenticated"] as const) { + expect(catalogNotice({ ...loaded, failures: [{ providerID: "bharatcode", kind }] })?.action).toBe("signIn") + } + }) +}) diff --git a/packages/kilo-vscode/tests/unit/bharatcode-website-signin.test.ts b/packages/kilo-vscode/tests/unit/bharatcode-website-signin.test.ts new file mode 100644 index 00000000..489ad14b --- /dev/null +++ b/packages/kilo-vscode/tests/unit/bharatcode-website-signin.test.ts @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, mock, spyOn, test } from "bun:test" +import * as vscode from "vscode" +import { start } from "../../src/onboarding/bharatcode" + +const website = "https://auth.bharatcode.ai/auth/v1/oauth/authorize" +const tick = () => new Promise((resolve) => setImmediate(resolve)) + +function fixture(input: { connected?: boolean; open?: boolean; url?: string; fail?: boolean } = {}) { + const information = spyOn(vscode.window, "showInformationMessage").mockImplementation(async () => undefined) + const errors = spyOn(vscode.window, "showErrorMessage").mockImplementation(async () => undefined) + const browser = spyOn(vscode.env, "openExternal").mockResolvedValue(input.open ?? true) + const authorize = mock(async () => ({ data: { url: input.url ?? website } })) + const callback = mock(async () => { + if (input.fail) throw new Error("cancelled") + }) + const update = mock(async () => {}) + let click!: () => Promise + spyOn(vscode.commands, "registerCommand").mockImplementation((_id, cmd) => { + click = cmd + return { dispose() {} } + }) + const c = { + provider: { + list: async () => ({ data: { connected: input.connected ? ["bharatcode"] : [] } }), + oauth: { authorize, callback }, + }, + global: { dispose: async () => {} }, + } + start({ subscriptions: [], globalState: { get: () => false, update } } as never, async () => c as never) + return { click: () => click(), information, errors, browser, authorize, callback, update } +} + +afterEach(() => mock.restore()) +describe("BharatCode website sign-in", () => { + test("a fresh installation invites sign-in without opening a browser or making a model call", async () => { + const f = fixture() + await tick() + expect(f.information).toHaveBeenCalledWith( + "Connect BharatCode to start your first chat.", + "Sign in with BharatCode", + ) + expect(f.browser).not.toHaveBeenCalled() + expect(f.update).not.toHaveBeenCalled() + }) + test("an existing connection is not prompted to replace its credential", async () => { + const f = fixture({ connected: true }) + await tick() + expect(f.information).not.toHaveBeenCalled() + expect(f.authorize).not.toHaveBeenCalled() + }) + test("two explicit clicks complete one browser exchange, then remember the connection", async () => { + const f = fixture() + await tick() + await Promise.all([f.click(), f.click()]) + expect(f.authorize).toHaveBeenCalledTimes(1) + expect(f.browser).toHaveBeenCalledTimes(1) + expect(f.callback).toHaveBeenCalledTimes(1) + expect(f.update).toHaveBeenCalledWith("bharatcode.apiKeySet", true) + }) + test("a denied exchange leaves setup incomplete and can be retried", async () => { + const config = { fail: true } + const f = fixture(config) + await tick() + await f.click() + expect(f.errors).toHaveBeenCalledTimes(1) + expect(f.update).not.toHaveBeenCalled() + config.fail = false + await f.click() + expect(f.update).toHaveBeenCalledTimes(1) + }) + test("a refused browser launch never reports a successful sign-in", async () => { + const f = fixture({ open: false }) + await tick() + await f.click() + expect(f.callback).not.toHaveBeenCalled() + expect(f.update).not.toHaveBeenCalled() + expect(f.errors).toHaveBeenCalledTimes(1) + }) + test("a non-BharatCode authorization destination is not opened", async () => { + const f = fixture({ url: "https://example.invalid/login" }) + await tick() + await f.click() + expect(f.browser).not.toHaveBeenCalled() + expect(f.callback).not.toHaveBeenCalled() + }) +}) diff --git a/packages/kilo-vscode/tests/unit/browser-automation-chrome-setting.test.ts b/packages/kilo-vscode/tests/unit/browser-automation-chrome-setting.test.ts index 519d5559..f0422128 100644 --- a/packages/kilo-vscode/tests/unit/browser-automation-chrome-setting.test.ts +++ b/packages/kilo-vscode/tests/unit/browser-automation-chrome-setting.test.ts @@ -6,7 +6,7 @@ import { migrateIntegratedBrowserUseSystemChrome, } from "../../src/services/browser-automation/chrome-setting" -const INTEGRATED_BROWSER = "kilo-code.new.agentManager.browser" +const INTEGRATED_BROWSER = "bharatcode-agent.agentManager.browser" describe("Integrated Browser Chrome preference", () => { const descriptors = Object.getOwnPropertyDescriptors(vscode.workspace) diff --git a/packages/kilo-vscode/tests/unit/chat-settings-message.test.ts b/packages/kilo-vscode/tests/unit/chat-settings-message.test.ts index c41ec354..09c36d24 100644 --- a/packages/kilo-vscode/tests/unit/chat-settings-message.test.ts +++ b/packages/kilo-vscode/tests/unit/chat-settings-message.test.ts @@ -20,7 +20,7 @@ const original = { trusted: Object.getOwnPropertyDescriptor(vscode.workspace, "isTrusted"), } -function stubConfig(state: Map, scope = "kilo-code.new.chat") { +function stubConfig(state: Map, scope = "bharatcode-agent.chat") { ;(vscode.workspace as unknown as Stub).getConfiguration = (section?: string) => { if (section !== scope) { return { get: (_key: string, fallback?: T) => fallback } @@ -61,8 +61,8 @@ describe("buildChatSettingsMessage", () => { Object.defineProperty(vscode.workspace, "isTrusted", { configurable: true, value: true }) const workspace = vscode.workspace as unknown as Stub const prefs = new Map([ - ["kilo-code.new.experimental.browserAutomation", true], - ["kilo-code.new.agentManager.browser.openLinksIn", "integrated"], + ["bharatcode-agent.experimental.browserAutomation", true], + ["bharatcode-agent.agentManager.browser.openLinksIn", "integrated"], ]) workspace.getConfiguration = (section) => ({ get: (key: string, fallback?: T) => (prefs.get(`${section}.${key}`) as T | undefined) ?? fallback, @@ -76,7 +76,7 @@ describe("buildChatSettingsMessage", () => { const child: unknown[] = [] const main = watchChatConfig((message) => parent.push(message)) const viewer = watchChatConfig((message) => child.push(message)) - const key = "kilo-code.new.agentManager.browser.openLinksIn" + const key = "bharatcode-agent.agentManager.browser.openLinksIn" prefs.set(key, "external") for (const listener of listeners) listener({ affectsConfiguration: (name) => name === key }) expect(parent).toEqual([ @@ -101,7 +101,7 @@ describe("timeline settings", () => { it.each([undefined, false, true])("returns the saved visibility %s", (visible) => { const state = new Map() if (visible !== undefined) state.set("showTaskTimeline", visible) - stubConfig(state, "kilo-code.new") + stubConfig(state, "bharatcode-agent") expect(buildTimelineSettingMessage()).toEqual({ type: "timelineSettingLoaded", @@ -111,7 +111,7 @@ describe("timeline settings", () => { it("synchronizes open viewers and stops sending after disposal", () => { const state = new Map() - stubConfig(state, "kilo-code.new") + stubConfig(state, "bharatcode-agent") const listeners = new Set<(event: vscode.ConfigurationChangeEvent) => void>() const workspace = vscode.workspace as unknown as Stub workspace.onDidChangeConfiguration = (listener) => { @@ -126,23 +126,23 @@ describe("timeline settings", () => { const main = watchChatConfig((msg) => parent.push(msg)) const viewer = watchChatConfig((msg) => child.push(msg)) - emit("kilo-code.new.showTokenThroughput") + emit("bharatcode-agent.showTokenThroughput") expect(parent).toEqual([]) expect(child).toEqual([]) state.set("showTaskTimeline", false) - emit("kilo-code.new.showTaskTimeline") + emit("bharatcode-agent.showTaskTimeline") expect(parent).toEqual([{ type: "timelineSettingLoaded", visible: false }]) expect(child).toEqual(parent) state.set("showTaskTimeline", true) - emit("kilo-code.new.showTaskTimeline") + emit("bharatcode-agent.showTaskTimeline") expect(parent.at(-1)).toEqual({ type: "timelineSettingLoaded", visible: true }) expect(child).toEqual(parent) viewer.dispose() state.set("showTaskTimeline", false) - emit("kilo-code.new.showTaskTimeline") + emit("bharatcode-agent.showTaskTimeline") expect(parent).toHaveLength(3) expect(child).toHaveLength(2) main.dispose() diff --git a/packages/kilo-vscode/tests/unit/code-action-provider.test.ts b/packages/kilo-vscode/tests/unit/code-action-provider.test.ts index 75b18baf..5ffb0339 100644 --- a/packages/kilo-vscode/tests/unit/code-action-provider.test.ts +++ b/packages/kilo-vscode/tests/unit/code-action-provider.test.ts @@ -47,9 +47,9 @@ describe("KiloCodeActionProvider", () => { it("uses correct command IDs", () => { const result = provider.provideCodeActions({} as never, makeRange(false) as never, makeContext(0) as never) const commands = result.map((a) => a.command?.command) - expect(commands).toContain("kilo-code.new.addToContext") - expect(commands).toContain("kilo-code.new.explainCode") - expect(commands).toContain("kilo-code.new.improveCode") + expect(commands).toContain("bharatcode-agent.addToContext") + expect(commands).toContain("bharatcode-agent.explainCode") + expect(commands).toContain("bharatcode-agent.improveCode") }) it("no action is preferred", () => { @@ -93,7 +93,7 @@ describe("KiloCodeActionProvider", () => { it("uses correct Fix command ID", () => { const result = provider.provideCodeActions({} as never, makeRange(false) as never, makeContext(1) as never) const fix = result.find((a) => a.title === "Fix with BharatCode") - expect(fix?.command?.command).toBe("kilo-code.new.fixCode") + expect(fix?.command?.command).toBe("bharatcode-agent.fixCode") }) }) }) diff --git a/packages/kilo-vscode/tests/unit/configuration-lifecycle.test.ts b/packages/kilo-vscode/tests/unit/configuration-lifecycle.test.ts new file mode 100644 index 00000000..abce39ae --- /dev/null +++ b/packages/kilo-vscode/tests/unit/configuration-lifecycle.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "bun:test" +import * as vscode from "vscode" +import { configuration, migrateConfiguration } from "../../src/configuration" +import { LEGACY_NAMESPACE, NAMESPACE } from "../../src/namespace" + +describe("configuration migration lifecycle", () => { + it("preserves existing extension/chat/sign-in state, retries a failed copy and does not restore reset values", async () => { + const marker = "bharatcode-agent.settingsMigration.v1" + const global = new Map([ + ["bharatcode.apiKeySet", true], + ["favoriteModels", ["bharatcode/qwen"]], + ["recentModels", ["bharatcode/deepseek"]], + ["variantSelections", { existing: "high" }], + ]) + const local = new Map([["kilo.workbench.restore", { agentManager: true }]]) + const before = { global: [...global], local: [...local] } + const memento = (state: Map) => ({ + get: (key: string, value?: unknown) => (state.has(key) ? state.get(key) : value), + update: async (key: string, value: unknown) => { + state.set(key, value) + }, + }) + const properties = { + [`${NAMESPACE}.fontSize`]: { default: 13 }, + [`${NAMESPACE}.model.modelID`]: { default: "" }, + [`${NAMESPACE}.agentWorkStyle`]: { default: "unset", scope: "application" }, + } + type Values = { globalValue?: unknown; workspaceValue?: unknown; defaultValue?: unknown } + const legacy: Record = { + fontSize: { globalValue: 17, workspaceValue: 19 }, + "model.modelID": { globalValue: "existing-model" }, + agentWorkStyle: { globalValue: "autonomous" }, + } + const current: Record = { fontSize: { defaultValue: 13 }, "model.modelID": { defaultValue: "" } } + const snapshot = structuredClone(legacy) + const writes: Array<{ section: string; key: string; value: unknown; target: unknown }> = [] + let blocked = true + const context = { + extension: { packageJSON: { contributes: { configuration: { properties } } } }, + globalState: memento(global), + workspaceState: memento(local), + get secrets() { + throw new Error("migration must not touch credentials") + }, + get globalStorageUri() { + throw new Error("migration must not move chat storage") + }, + } as unknown as vscode.ExtensionContext + const original = vscode.workspace.getConfiguration + const folders = Object.getOwnPropertyDescriptor(vscode.workspace, "workspaceFolders") + Object.defineProperty(vscode.workspace, "workspaceFolders", { + configurable: true, + value: [{ uri: { toString: () => "file:///existing-project" } }], + }) + vscode.workspace.getConfiguration = ((section: string) => { + const old = section === LEGACY_NAMESPACE || section.startsWith(`${LEGACY_NAMESPACE}.`) + const values = old ? legacy : current + const prefix = section.slice((old ? LEGACY_NAMESPACE : NAMESPACE).length + 1) + const full = (key: string) => (prefix ? `${prefix}.${key}` : key) + return { + inspect: (key: string) => ({ key, ...values[full(key)] }), + get: (key: string, value?: unknown) => { + const info = values[full(key)] + return info?.workspaceValue ?? info?.globalValue ?? info?.defaultValue ?? value + }, + update: async (key: string, value: unknown, target: number) => { + if (blocked && full(key) === "model.modelID") throw new Error("settings locked") + writes.push({ section, key, value, target }) + const level = target === vscode.ConfigurationTarget.Workspace ? "workspaceValue" : "globalValue" + ;(values[full(key)] ??= {})[level] = value + }, + } + }) as typeof vscode.workspace.getConfiguration + try { + await migrateConfiguration(context) + expect(global.has(marker)).toBe(false) + expect(configuration(`${NAMESPACE}.model`).get("modelID")).toBe("existing-model") + expect(configuration(NAMESPACE).get("fontSize")).toBe(19) + blocked = false + await migrateConfiguration(context) + expect(global.get(marker)).toBe(true) + expect(current["model.modelID"]?.globalValue).toBe("existing-model") + const count = writes.length + await migrateConfiguration(context) + expect(writes).toHaveLength(count) + await configuration(`${NAMESPACE}.model`).update("modelID", undefined, vscode.ConfigurationTarget.Global) + await migrateConfiguration(context) + expect(configuration(`${NAMESPACE}.model`).get("modelID")).toBe("") + expect(legacy).toEqual(snapshot) + expect(writes.every((write) => write.section.startsWith(NAMESPACE))).toBe(true) + expect([...global].filter(([key]) => key !== marker)).toEqual(before.global) + expect([...local].filter(([key]) => key !== marker)).toEqual(before.local) + } finally { + vscode.workspace.getConfiguration = original + if (folders) Object.defineProperty(vscode.workspace, "workspaceFolders", folders) + } + }) +}) diff --git a/packages/kilo-vscode/tests/unit/extension-arch.test.ts b/packages/kilo-vscode/tests/unit/extension-arch.test.ts index 55bd2ce3..331f80ed 100644 --- a/packages/kilo-vscode/tests/unit/extension-arch.test.ts +++ b/packages/kilo-vscode/tests/unit/extension-arch.test.ts @@ -71,8 +71,8 @@ describe("Extension — package.json command sync", () => { // Commands generated via template literals can't be extracted by regex, // so verify the dynamic registration pattern exists in source instead. const dynamic: Record = { - "kilo-code.new.agentManager.jumpTo": "registerCommand(`kilo-code.new.agentManager.jumpTo${", - "kilo-code.new.setBharatcodeKey": "registerCommand(SET_KEY_COMMAND", + "bharatcode-agent.agentManager.jumpTo": "registerCommand(`bharatcode-agent.agentManager.jumpTo${", + "bharatcode-agent.setBharatcodeKey": "registerCommand(SET_KEY_COMMAND", } const missing: string[] = [] @@ -95,74 +95,76 @@ describe("Extension — package.json command sync", () => { }) /** - * All declared commands must use the kilo-code.new. prefix. - * The legacy kilo-code.* namespace (without .new.) belongs to the old - * extension and must not be reintroduced. + * All declared commands must use the bharatcode-agent. prefix. + * Legacy kilo-code.* IDs belong to other installed forks and must not be + * reintroduced, even as compatibility aliases. */ - it("all declared commands use the kilo-code.new. prefix", () => { - const bad = declared.filter((cmd) => !cmd.startsWith("kilo-code.new.")) + it("all declared commands use the bharatcode-agent. prefix", () => { + const bad = declared.filter((cmd) => !cmd.startsWith("bharatcode-agent.")) expect( bad, - `Commands without "kilo-code.new." prefix — use the namespaced form:\n` + bad.map((b) => ` - ${b}`).join("\n"), + `Commands without "bharatcode-agent." prefix — use the namespaced form:\n` + + bad.map((b) => ` - ${b}`).join("\n"), ).toEqual([]) }) it("scopes Agent Manager search to the panel and leaves the integrated terminal alone", () => { const binding = pkg.contributes?.keybindings?.find( - (item: { command: string }) => item.command === "kilo-code.new.agentManager.search", + (item: { command: string }) => item.command === "bharatcode-agent.agentManager.search", ) expect(binding).toMatchObject({ key: "ctrl+f", mac: "cmd+f", - when: "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && !terminalFocus", + when: "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && !terminalFocus", }) }) it("keeps Agent Manager session and terminal shortcuts focus-aware", () => { const terminal = pkg.contributes?.keybindings?.find( - (item: { command: string }) => item.command === "kilo-code.new.agentManager.showTerminal", + (item: { command: string }) => item.command === "bharatcode-agent.agentManager.showTerminal", ) const create = pkg.contributes?.keybindings?.find( - (item: { command: string }) => item.command === "kilo-code.new.agentManager.newTerminalTab", + (item: { command: string }) => item.command === "bharatcode-agent.agentManager.newTerminalTab", ) const sessionCreate = pkg.contributes?.keybindings?.find( - (item: { command: string }) => item.command === "kilo-code.new.agentManager.newTab", + (item: { command: string }) => item.command === "bharatcode-agent.agentManager.newTab", ) expect(terminal).toMatchObject({ key: "ctrl+/", mac: "cmd+/", - when: "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && !kilo-code.new.sidebarFocused", + when: "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && !bharatcode-agent.sidebarFocused", }) expect(create).toMatchObject({ key: "ctrl+shift+t", mac: "cmd+shift+t", - when: "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && !kilo-code.new.agentManagerSideTerminalFocused", + when: "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && !bharatcode-agent.agentManagerSideTerminalFocused", }) expect(sessionCreate).toMatchObject({ key: "ctrl+t", mac: "cmd+t", - when: "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && !kilo-code.new.agentManagerSideTerminalFocused", + when: "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && !bharatcode-agent.agentManagerSideTerminalFocused", }) const terminalCreate = pkg.contributes?.keybindings?.find( (item: { command: string; key?: string; mac?: string; when?: string }) => - item.command === "kilo-code.new.agentManager.newSideTerminal" && item.key === "ctrl+t", + item.command === "bharatcode-agent.agentManager.newSideTerminal" && item.key === "ctrl+t", ) expect(terminalCreate).toMatchObject({ key: "ctrl+t", mac: "cmd+t", - when: "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && kilo-code.new.agentManagerSideTerminalFocused", + when: "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && bharatcode-agent.agentManagerSideTerminalFocused", }) expect( pkg.contributes?.keybindings?.some( (item: { command: string }) => - item.command === "kilo-code.new.agentManager.newTerminal" || - item.command === "kilo-code.new.agentManager.newMainTerminal", + item.command === "bharatcode-agent.agentManager.newTerminal" || + item.command === "bharatcode-agent.agentManager.newMainTerminal", ), ).toBe(false) }) it("declares the Agent Manager terminal destination setting", () => { - const setting = pkg.contributes?.configuration?.properties?.["kilo-code.new.agentManager.terminalButtonDestination"] + const setting = + pkg.contributes?.configuration?.properties?.["bharatcode-agent.agentManager.terminalButtonDestination"] expect(setting).toMatchObject({ type: "string", scope: "application", @@ -174,28 +176,29 @@ describe("Extension — package.json command sync", () => { it("scopes the open PR shortcut to Agent Manager", () => { const binding = pkg.contributes?.keybindings?.find( - (item: { command: string }) => item.command === "kilo-code.new.agentManager.openPR", + (item: { command: string }) => item.command === "bharatcode-agent.agentManager.openPR", ) expect(binding).toMatchObject({ key: "ctrl+shift+r", mac: "cmd+shift+r", - when: "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel'", + when: "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel'", }) }) it("scopes agent mode shortcuts to focused Kilo webviews", () => { const bindings = pkg.contributes?.keybindings?.filter( (item: { command: string }) => - item.command === "kilo-code.new.cycleAgentMode" || item.command === "kilo-code.new.cyclePreviousAgentMode", + item.command === "bharatcode-agent.cycleAgentMode" || + item.command === "bharatcode-agent.cyclePreviousAgentMode", ) const when = - "kilo-code.new.sidebarFocused || activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' || activeWebviewPanelId == 'kilo-code.new.TabPanel'" + "bharatcode-agent.sidebarFocused || activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' || activeWebviewPanelId == 'bharatcode-agent.TabPanel'" expect(bindings).toHaveLength(2) expect(bindings).toEqual( expect.arrayContaining([ - expect.objectContaining({ command: "kilo-code.new.cycleAgentMode", when }), - expect.objectContaining({ command: "kilo-code.new.cyclePreviousAgentMode", when }), + expect.objectContaining({ command: "bharatcode-agent.cycleAgentMode", when }), + expect.objectContaining({ command: "bharatcode-agent.cyclePreviousAgentMode", when }), ]), ) }) @@ -204,9 +207,9 @@ describe("Extension — package.json command sync", () => { const commands = pkg.contributes?.commands ?? [] expect(commands).toEqual( expect.arrayContaining([ - expect.objectContaining({ command: "kilo-code.new.closeTask", title: "Close Task", category: "BharatCode" }), + expect.objectContaining({ command: "bharatcode-agent.closeTask", title: "Close Task", category: "BharatCode" }), expect.objectContaining({ - command: "kilo-code.new.closeAllTasks", + command: "bharatcode-agent.closeAllTasks", title: "Close All Tasks", category: "BharatCode", }), @@ -214,8 +217,11 @@ describe("Extension — package.json command sync", () => { ) const source = fs.readFileSync(EXTENSION_FILE, "utf-8") - const closeTask = sliceBlock(source, source.indexOf('vscode.commands.registerCommand("kilo-code.new.closeTask"')) - const closeAll = sliceBlock(source, source.indexOf('vscode.commands.registerCommand("kilo-code.new.closeAllTasks"')) + const closeTask = sliceBlock(source, source.indexOf('vscode.commands.registerCommand("bharatcode-agent.closeTask"')) + const closeAll = sliceBlock( + source, + source.indexOf('vscode.commands.registerCommand("bharatcode-agent.closeAllTasks"'), + ) expect(closeTask).toContain('taskTarget().postMessage({ type: "action", action: "closeTask" })') expect(closeAll).toContain('taskTarget().postMessage({ type: "action", action: "closeAllTasks" })') @@ -309,7 +315,7 @@ describe("Extension — KiloProvider handler wiring", () => { it("new and restored tabs use shared setup and retain disposal", () => { expect(ext).toContain("openKiloInNewTab(context, tabPanels, attach)") - for (const name of ["function openKiloInNewTab", '"kilo-code.new.TabPanel"']) { + for (const name of ["function openKiloInNewTab", '"bharatcode-agent.TabPanel"']) { const start = ext.indexOf(name) expect(start, `${name} must exist`).toBeGreaterThan(-1) const body = sliceBlock(ext, start) diff --git a/packages/kilo-vscode/tests/unit/extension-identity.test.ts b/packages/kilo-vscode/tests/unit/extension-identity.test.ts new file mode 100644 index 00000000..484dac81 --- /dev/null +++ b/packages/kilo-vscode/tests/unit/extension-identity.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from "bun:test" +import { readFileSync, readdirSync } from "node:fs" +import { resolve, join } from "node:path" +import { EXTENSION_DISPLAY_NAME, EXTENSION_ID } from "../../src/constants" +import { NAMESPACE } from "../../src/namespace" + +const root = resolve(import.meta.dir, "../..") +const read = (path: string) => readFileSync(join(root, path), "utf8") +const pkg = JSON.parse(read("package.json")) +const prefix = `${NAMESPACE}.` + +function sources(directory: string): Array<{ file: string; source: string }> { + return readdirSync(join(root, directory), { withFileTypes: true }).flatMap((entry) => { + const file = `${directory}/${entry.name}` + if (entry.isDirectory()) return sources(file) + if (!/\.tsx?$/.test(entry.name) || /\.(test|spec)\./.test(entry.name)) return [] + return [{ file, source: read(file) }] + }) +} + +const files = sources("src") +const source = files.map((file) => file.source).join("\n") + +describe("BharatCode Agent public namespace and persistent identity", () => { + it("shared shortcuts do not toggle approval or capture keys outside BharatCode", () => { + for (const name of ["focusChatInput", "toggleAutoApprove", "generateTerminalCommand", "agentManagerOpen"]) { + const binding = pkg.contributes.keybindings.find( + (item: { command: string }) => item.command === `bharatcode-agent.${name}`, + ) + expect(binding?.when).toContain("bharatcode-agent.sidebarFocused") + } + expect( + pkg.contributes.keybindings.some((item: { command: string }) => item.command.startsWith("-workbench.")), + ).toBe(false) + }) + + it("keeps the installed extension identity and backend storage behavior", () => { + expect(pkg.name).toBe("bharatcode-agent") + expect(pkg.publisher).toBe("bharatcode") + expect(pkg.displayName).toBe("BharatCode Agent") + expect(EXTENSION_DISPLAY_NAME).toBe(pkg.displayName) + expect(`${pkg.publisher}.${pkg.name}`).toBe(EXTENSION_ID) + expect(EXTENSION_ID).toBe("bharatcode.bharatcode-agent") + expect(read("src/extension.ts")).toContain('const RESTORE_KEY = "kilo.workbench.restore"') + expect(read("src/extension.ts")).toContain("context.globalStorageUri.fsPath") + expect(read("src/onboarding/bharatcode.ts")).toContain('const CONNECTED_FLAG = "bharatcode.apiKeySet"') + expect(read("src/services/cli-backend/server-manager.ts")).toContain('KILO_APP_NAME: "kilo-code"') + expect(read("src/services/cli-backend/server-manager.ts")).toContain("this.context.globalStorageUri.fsPath") + expect(read("src/agent-manager/WorktreeStateManager.ts")).toContain('const STATE_FILE = "agent-manager.json"') + expect(read("src/agent-manager/WorktreeStateManager.ts")).toContain("path.join(root, KILO_DIR, STATE_FILE)") + expect(read("src/agent-manager/constants.ts")).toContain('".kilo"') + // A UI namespace change must never turn into an auth/chat data migration. + const migration = read("src/configuration.ts") + read("src/namespace.ts") + expect(migration).not.toMatch(/secrets\.|globalStorageUri|auth\.json|unlink|rmSync/) + expect(migration).not.toMatch(/legacy\.update\(/) + }) + + it("retains the correct lookup identity in production compilation", async () => { + const result = await Bun.build({ + entrypoints: [join(root, "src/constants.ts")], + target: "node", + minify: true, + }) + expect(result.success).toBe(true) + const output = await result.outputs[0]!.text() + expect(output).toContain("bharatcode.bharatcode-agent") + expect(output).toContain("BharatCode Agent") + expect(output).not.toContain("bharatcode.bharatcode-vscode") + expect(output).not.toContain("thenabbu.bharatcode-vscode") + }) + + it("has isolated contributions, with menu/keybinding commands matching declarations", () => { + const commands = pkg.contributes.commands.map((item: { command: string }) => item.command) as string[] + expect(new Set(commands).size).toBe(commands.length) + expect(commands.every((id) => id.startsWith(prefix))).toBe(true) + const submenus = pkg.contributes.submenus.map((item: { id: string }) => item.id) as string[] + for (const id of submenus) expect(id.startsWith(prefix)).toBe(true) + for (const items of Object.values(pkg.contributes.menus) as Array>) { + for (const item of items) { + if (item.command) expect(commands).toContain(item.command) + if (item.submenu) expect(submenus).toContain(item.submenu) + } + } + for (const item of pkg.contributes.keybindings) { + if (item.command.startsWith("-workbench.")) continue // Existing built-in keybinding removal. + expect(commands).toContain(item.command) + } + for (const key of Object.keys(pkg.contributes.configuration.properties)) expect(key.startsWith(prefix)).toBe(true) + for (const item of pkg.contributes.taskDefinitions) expect(item.type.startsWith(prefix)).toBe(true) + expect(JSON.stringify(pkg.contributes)).not.toMatch(/kilo-code(?:\.new|\.SidebarProvider|-ActivityBar)/) + }) + + it("matches sidebar/container IDs, panel IDs, context keys and command references", () => { + const container = pkg.contributes.viewsContainers.activitybar[0].id + const view = pkg.contributes.views[container][0].id + expect(container).toBe(`${NAMESPACE}-ActivityBar`) + // VS Code rejects dots in container IDs (unlike command and view IDs). + expect(container).toMatch(/^[a-zA-Z0-9_-]+$/) + expect(view).toBe(`${NAMESPACE}.SidebarProvider`) + expect(read("src/KiloProvider.ts")).toContain(`viewType = "${view}"`) + expect(read("src/extension.ts")).toContain(`"${view}.focus"`) + for (const { file, source } of files) { + if (file === "src/namespace.ts") continue + expect(source, file).not.toMatch( + /kilo-code\.new|kilo-code\\\.new|kilo-code\.SidebarProvider|kilo-code-ActivityBar|kilo-code\.agentTerminalFocus/, + ) + } + const registered = new Set([...source.matchAll(/registerCommand\s*\(\s*"([^"]+)"/g)].map((match) => match[1])) + registered.add(`${NAMESPACE}.setBharatcodeKey`) + for (let i = 1; i <= 9; i++) registered.add(`${NAMESPACE}.agentManager.jumpTo${i}`) + for (const match of source.matchAll(/executeCommand\s*\(\s*"(bharatcode-agent\.[^"]+)"/g)) { + if (match[1] === `${view}.focus`) continue // VS Code's generated focus command. + expect(registered.has(match[1]!), match[1]).toBe(true) + } + for (const match of source.matchAll(/setContext"\s*,\s*"([^"]+)"/g)) expect(match[1]!.startsWith(prefix)).toBe(true) + expect(read("src/SettingsEditorProvider.ts")).toContain("type.match(/^bharatcode-agent\\.(\\w+)Panel$/)") + expect(read("src/extension.ts")).toContain("registerWebviewPanelSerializer(`bharatcode-agent.${suffix}`") + }) + + it("migrates before any backend service or onboarding starts, without settings definitions in the old namespace", () => { + const activation = read("src/extension.ts") + expect(activation.indexOf("await migrateConfiguration(context)")).toBeLessThan( + activation.indexOf("new KiloConnectionService("), + ) + expect(activation.indexOf("await migrateConfiguration(context)")).toBeLessThan( + activation.indexOf("startBharatcodeOnboarding(context"), + ) + // Current settings are scalar/arrays, not mergeable object or language overrides. + // Extending this schema requires extending the legacy resolver and migration tests. + for (const schema of Object.values(pkg.contributes.configuration.properties) as Array<{ + type: string + scope?: string + }>) { + expect(schema.type).not.toBe("object") + expect(schema.scope).not.toBe("language-overridable") + } + }) +}) diff --git a/packages/kilo-vscode/tests/unit/font-size-arch.test.ts b/packages/kilo-vscode/tests/unit/font-size-arch.test.ts index 750c0dc5..8e6d2be0 100644 --- a/packages/kilo-vscode/tests/unit/font-size-arch.test.ts +++ b/packages/kilo-vscode/tests/unit/font-size-arch.test.ts @@ -1,7 +1,7 @@ /** * Architecture test: webview font-size token usage. * - * Kilo's VS Code webviews use the `kilo-code.new.fontSize` setting, not + * Kilo's VS Code webviews use the `bharatcode-agent.fontSize` setting, not * VS Code editor font-size or raw pixel declarations. This keeps the Kilo UI * independently scalable across sidebar, settings, Agent Manager, * diff viewers, code blocks, and shared kilo-ui controls. @@ -133,7 +133,7 @@ describe("webview font-size architecture", () => { const missing = WATCHED_PROVIDERS.filter((file) => !fs.readFileSync(file, "utf-8").includes("watchFontSizeConfig")) expect( missing.map(rel), - `Webview providers that stay open must broadcast fontSizeChanged when kilo-code.new.fontSize changes.\n` + + `Webview providers that stay open must broadcast fontSizeChanged when bharatcode-agent.fontSize changes.\n` + missing.map((file) => ` - ${rel(file)}`).join("\n"), ).toEqual([]) }) diff --git a/packages/kilo-vscode/tests/unit/format-keybinding.test.ts b/packages/kilo-vscode/tests/unit/format-keybinding.test.ts index 3ed8d90c..472ca68b 100644 --- a/packages/kilo-vscode/tests/unit/format-keybinding.test.ts +++ b/packages/kilo-vscode/tests/unit/format-keybinding.test.ts @@ -78,15 +78,15 @@ describe("formatKeybinding", () => { describe("buildKeybindingMap", () => { it("maps the configurable Agent Manager search shortcut", () => { - const bindings = [{ command: "kilo-code.new.agentManager.search", key: "ctrl+f", mac: "cmd+f" }] + const bindings = [{ command: "bharatcode-agent.agentManager.search", key: "ctrl+f", mac: "cmd+f" }] expect(buildKeybindingMap(bindings, true).search).toBe("⌘F") expect(buildKeybindingMap(bindings, false).search).toBe("Ctrl+F") }) it("maps the shared session tab shortcuts", () => { const bindings = [ - { command: "kilo-code.new.agentManager.previousTab", key: "ctrl+alt+left", mac: "cmd+alt+left" }, - { command: "kilo-code.new.agentManager.nextTab", key: "ctrl+alt+right", mac: "cmd+alt+right" }, + { command: "bharatcode-agent.agentManager.previousTab", key: "ctrl+alt+left", mac: "cmd+alt+left" }, + { command: "bharatcode-agent.agentManager.nextTab", key: "ctrl+alt+right", mac: "cmd+alt+right" }, ] expect(buildKeybindingMap(bindings, true)).toMatchObject({ previousTab: "⌘⌥←", nextTab: "⌘⌥→" }) expect(buildKeybindingMap(bindings, false)).toMatchObject({ previousTab: "Ctrl+Alt+←", nextTab: "Ctrl+Alt+→" }) @@ -102,16 +102,16 @@ describe("buildKeybindingMap", () => { it("keeps prompt and side-terminal shortcuts separate", () => { const bindings = [ { - command: "kilo-code.new.agentManager.newTerminalTab", + command: "bharatcode-agent.agentManager.newTerminalTab", key: "ctrl+shift+t", mac: "cmd+shift+t", - when: "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && kilo-code.new.agentManagerPromptFocused", + when: "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && bharatcode-agent.agentManagerPromptFocused", }, { - command: "kilo-code.new.agentManager.newSideTerminal", + command: "bharatcode-agent.agentManager.newSideTerminal", key: "ctrl+t", mac: "cmd+t", - when: "activeWebviewPanelId == 'kilo-code.new.AgentManagerPanel' && kilo-code.new.agentManagerSideTerminalFocused", + when: "activeWebviewPanelId == 'bharatcode-agent.AgentManagerPanel' && bharatcode-agent.agentManagerSideTerminalFocused", }, ] expect(buildKeybindingMap(bindings, true)).toMatchObject({ diff --git a/packages/kilo-vscode/tests/unit/i18n-shim.test.ts b/packages/kilo-vscode/tests/unit/i18n-shim.test.ts index c8cf066e..ad902d04 100644 --- a/packages/kilo-vscode/tests/unit/i18n-shim.test.ts +++ b/packages/kilo-vscode/tests/unit/i18n-shim.test.ts @@ -69,7 +69,7 @@ describe("extension host i18n", () => { env: { language: "en" }, workspace: { getConfiguration: (section: string) => ({ - get: () => (section === "kilo-code.new" ? "de" : undefined), + get: () => (section === "bharatcode-agent" ? "de" : undefined), }), }, } as unknown as typeof import("vscode") diff --git a/packages/kilo-vscode/tests/unit/indexing-settings-message.test.ts b/packages/kilo-vscode/tests/unit/indexing-settings-message.test.ts index b80f479d..784f0204 100644 --- a/packages/kilo-vscode/tests/unit/indexing-settings-message.test.ts +++ b/packages/kilo-vscode/tests/unit/indexing-settings-message.test.ts @@ -12,7 +12,7 @@ const original = vscode.workspace.getConfiguration function stubConfig(state: Map) { ;(vscode.workspace as unknown as Stub).getConfiguration = (section?: string) => { - if (section !== "kilo-code.new.indexing") { + if (section !== "bharatcode-agent.indexing") { return { get: (_key: string, fallback?: T) => fallback } } return { diff --git a/packages/kilo-vscode/tests/unit/kilo-provider-catalog.test.ts b/packages/kilo-vscode/tests/unit/kilo-provider-catalog.test.ts index b4abd064..6d6347aa 100644 --- a/packages/kilo-vscode/tests/unit/kilo-provider-catalog.test.ts +++ b/packages/kilo-vscode/tests/unit/kilo-provider-catalog.test.ts @@ -259,7 +259,10 @@ describe("KiloProvider catalog refresh", () => { fail = true await internal.fetchAndSendProviders() - expect(messages.at(-1)).toEqual({ type: "providersLoading" }) + expect(messages.at(-1)).toEqual({ + type: "providersLoadFailed", + failure: { providerID: "bharatcode", kind: "network" }, + }) expect(messages.filter((message) => message.type === "providersLoaded")).toHaveLength(1) expect(internal.cachedProvidersMessage).toBeNull() }) diff --git a/packages/kilo-vscode/tests/unit/kilo-provider-provider-refresh.test.ts b/packages/kilo-vscode/tests/unit/kilo-provider-provider-refresh.test.ts index 203e22fa..0d9318ee 100644 --- a/packages/kilo-vscode/tests/unit/kilo-provider-provider-refresh.test.ts +++ b/packages/kilo-vscode/tests/unit/kilo-provider-provider-refresh.test.ts @@ -14,6 +14,7 @@ type Internals = { refreshConfig: (type: "configLoaded" | "configUpdated", dir?: string) => Promise initializeConnection: () => Promise fetchAndSendProviders: () => Promise + refreshBharatcodeCatalog: () => Promise fetchAndSendIndexingStatus: (directory?: string, projectId?: string) => void flushPendingKiloModel: () => void checkConfigWarnings: (reason: string) => Promise @@ -89,6 +90,194 @@ function stub(internal: Internals) { } describe("KiloProvider providers on reconnect", () => { + it("coalesces explicit catalog retries without disposing sessions or replaying tools", async () => { + const gate = Promise.withResolvers() + const messages: unknown[] = [] + let refreshes = 0 + let lists = 0 + let disposals = 0 + let prompts = 0 + const internal = provider( + connection(true, { + provider: { + refresh: async (input: unknown) => { + expect(input).toEqual({ providerID: "bharatcode", directory: "/repo" }) + refreshes++ + await gate.promise + return { data: true } + }, + list: async () => { + lists++ + return { + data: { + all: [{ id: "bharatcode", models: { glm: { id: "glm" } } }], + connected: ["bharatcode"], + default: { bharatcode: "glm" }, + }, + } + }, + }, + kilo: { authStatus: async () => ({ data: undefined }) }, + global: { + dispose: async () => { + disposals++ + }, + }, + session: { + prompt: async () => { + prompts++ + }, + }, + }), + ) + stub(internal) + internal.webview = { postMessage: async (message) => messages.push(message) } + const first = internal.refreshBharatcodeCatalog() + const second = internal.refreshBharatcodeCatalog() + expect(first).toBe(second) + expect(refreshes).toBe(1) + gate.resolve() + await first + expect(lists).toBe(1) + expect(disposals).toBe(0) + expect(prompts).toBe(0) + expect(messages).toContainEqual({ type: "providersRefreshing" }) + expect(messages).toContainEqual( + expect.objectContaining({ type: "providersLoaded", ready: false, connected: ["bharatcode"] }), + ) + }) + + it("reports a sanitized retry error and releases the retry lock", async () => { + const messages: unknown[] = [] + let attempts = 0 + const internal = provider( + connection(true, { + provider: { + refresh: async () => { + attempts++ + throw new Error("private-response-body") + }, + }, + }), + ) + stub(internal) + internal.webview = { postMessage: async (message) => messages.push(message) } + await internal.refreshBharatcodeCatalog() + await internal.refreshBharatcodeCatalog() + expect(attempts).toBe(2) + expect(messages).toContainEqual({ + type: "providersLoadFailed", + failure: { providerID: "bharatcode", kind: "network" }, + }) + expect(JSON.stringify(messages)).not.toContain("private-response-body") + }) + + for (const change of ["project", "directory", "client", "generation"] as const) { + it.each([true, false])( + `ignores a stale catalog retry after a ${change} change (rejected: %s)`, + async (rejected) => { + const gate = Promise.withResolvers() + let directory = "/before" + const requests: string[] = [] + const messages: unknown[] = [] + const service = connection(true, { + provider: { + refresh: async () => gate.promise, + list: async (input: { directory: string }) => { + requests.push(input.directory) + return { data: { all: [], connected: [], default: {} } } + }, + }, + kilo: { authStatus: async () => ({ data: { authenticated: false } }) }, + }) + const internal = provider(service, () => directory) + stub(internal) + internal.webview = { postMessage: async (message) => messages.push(message) } + const pending = internal.refreshBharatcodeCatalog() + if (change === "project" || change === "directory") directory = "/after" + if (change === "project" || change === "generation") await internal.fetchAndSendProviders() + if (change === "client") service.getClient = () => ({}) as never + const published = [...messages] + const fetched = [...requests] + if (rejected) gate.reject(new Error("stale private error")) + else gate.resolve() + await pending + + // Neither an old error nor an old success may replace/refetch the current catalog. + expect(messages).toEqual(published) + expect(requests).toEqual(fetched) + if (change === "project") { + expect(requests).toEqual(["/after"]) + expect(messages.at(-1)).toEqual(expect.objectContaining({ type: "providersLoaded" })) + } + }, + ) + } + + it("lets the active project retry while an obsolete retry is still pending", async () => { + const before = Promise.withResolvers() + const after = Promise.withResolvers() + let directory = "/before" + const requests: string[] = [] + const messages: unknown[] = [] + const internal = provider( + connection(true, { + provider: { + refresh: async (input: { directory: string }) => { + requests.push(input.directory) + await (input.directory === "/before" ? before.promise : after.promise) + }, + list: async () => ({ data: { all: [], connected: [], default: {} } }), + }, + kilo: { authStatus: async () => ({ data: { authenticated: false } }) }, + }), + () => directory, + ) + stub(internal) + internal.webview = { postMessage: async (message) => messages.push(message) } + const stale = internal.refreshBharatcodeCatalog() + directory = "/after" + const active = internal.refreshBharatcodeCatalog() + expect(active).not.toBe(stale) + expect(requests).toEqual(["/before", "/after"]) + before.reject(new Error("obsolete project")) + await stale + expect(messages).not.toContainEqual(expect.objectContaining({ type: "providersLoadFailed" })) + expect(internal.refreshBharatcodeCatalog()).toBe(active) + after.resolve() + await active + expect(messages.at(-1)).toEqual(expect.objectContaining({ type: "providersLoaded" })) + expect(requests).toHaveLength(2) + }) + + it("keeps duplicate retries coalesced through the follow-up provider list", async () => { + const started = Promise.withResolvers() + const gate = Promise.withResolvers() + let refreshes = 0 + const internal = provider( + connection(true, { + provider: { + refresh: async () => { + refreshes++ + }, + list: async () => { + started.resolve() + await gate.promise + return { data: { all: [], connected: [], default: {} } } + }, + }, + kilo: { authStatus: async () => ({ data: { authenticated: false } }) }, + }), + ) + stub(internal) + const pending = internal.refreshBharatcodeCatalog() + await started.promise + expect(internal.refreshBharatcodeCatalog()).toBe(pending) + expect(refreshes).toBe(1) + gate.resolve() + await pending + }) + it("recovers providers against the selected project without reconnecting", async () => { let dir = "/unavailable" const requests: string[] = [] diff --git a/packages/kilo-vscode/tests/unit/model-selector-lifecycle.test.ts b/packages/kilo-vscode/tests/unit/model-selector-lifecycle.test.ts index 0f7e3212..35ee92af 100644 --- a/packages/kilo-vscode/tests/unit/model-selector-lifecycle.test.ts +++ b/packages/kilo-vscode/tests/unit/model-selector-lifecycle.test.ts @@ -46,6 +46,7 @@ function check(code: string) { freeDataLabel, autoSummary, buildTriggerLabel, sanitizeName, mostUsedModels, rankModelSearch } = await import("./webview-ui/src/components/shared/model-selector-utils.ts") const { isEnterKeyCommitNotIme } = await import("./webview-ui/src/utils/ime-enter.ts") const { providerFailure, providerFailureMessageKey } = await import("./src/shared/provider-model.ts") + const { catalogNotice } = await import("./src/shared/bharatcode-catalog.ts") const window = new EventTarget() const requestAnimationFrame = () => 1 const cancelAnimationFrame = () => {} @@ -76,7 +77,7 @@ function check(code: string) { const [favorites, setFavorites] = createSignal([{ providerID: "kilo", modelID: "alpha" }]) const [usage, setUsage] = createSignal({ "kilo/bravo": { count: 7, lastUsed: 10 } }) const [recent, setRecent] = createSignal([]) - provider = { models, connected, findModel: (selection) => models().find((item) => item.providerID === selection?.providerID && item.id === selection?.modelID), kiloUnavailable: () => false, failures: () => [] } + provider = { models, connected, findModel: (selection) => models().find((item) => item.providerID === selection?.providerID && item.id === selection?.modelID), kiloUnavailable: () => false, failures: () => [], ready: () => true, catalogReady: () => true } session = { favoriteModels: () => { stats.favorites++; return favorites() }, modelUsageHistory: () => { stats.usage++; return usage() }, @@ -107,6 +108,25 @@ function check(code: string) { } describe("ModelSelector closed popup work", () => { + it("leaves recovery buttons' Enter action alone with retained models or a clear row", () => { + check(` + for (const onlyClear of [false, true]) { + const state = scene() + try { + state.setOpen(true) + if (onlyClear) state.refresh([]) + await flush() + const before = state.value() + let prevented = false + state.handleKeyDown({ key: "Enter", target: { closest: () => ({}) }, preventDefault() { prevented = true } }) + assert.equal(prevented, false) + assert.equal(state.open(), true) + assert.deepEqual(state.value(), before) + } finally { state.dispose() } + } + `) + }) + it("keeps trigger state reactive without catalog filtering or personalization work while closed", () => { check(` const state = scene() @@ -136,8 +156,8 @@ describe("ModelSelector closed popup work", () => { state.setValue(null) state.refresh([model("hidden", "offline"), model("kilo-auto/small")]) assert.equal(state.hasProviders(), false) - assert.equal(state.canOpen(), false) - assert.equal(state.triggerLabel(), "dialog.model.noProviders") + assert.equal(state.canOpen(), true) + assert.equal(state.triggerLabel(), "bharatcode.catalog.signIn") state.setConnected(["offline"]) assert.equal(state.hasProviders(), true) assert.equal(state.canOpen(), true) @@ -156,7 +176,7 @@ describe("ModelSelector closed popup work", () => { assert.equal(clear.hasProviders(), false) assert.equal(clear.canOpen(), true) clear.setValue(null) - assert.equal(clear.canOpen(), false) + assert.equal(clear.canOpen(), true) clear.dispose() } finally { state.dispose() } `) diff --git a/packages/kilo-vscode/tests/unit/namespace-migration.test.ts b/packages/kilo-vscode/tests/unit/namespace-migration.test.ts new file mode 100644 index 00000000..8592bdb0 --- /dev/null +++ b/packages/kilo-vscode/tests/unit/namespace-migration.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from "bun:test" +import type { WorkspaceConfiguration } from "vscode" +import { copySettings, fallback } from "../../src/namespace" + +type Values = { + defaultValue?: unknown + globalValue?: unknown + workspaceValue?: unknown + workspaceFolderValue?: unknown +} + +// A small VS Code configuration boundary; tests exercise the real migration/read logic. +function config(values: Record = {}, blocked = new Set()) { + const writes: Array<{ key: string; value: unknown; target: unknown }> = [] + const api = { + get: (key: string, value?: unknown) => { + const info = values[key] + return info?.workspaceFolderValue ?? info?.workspaceValue ?? info?.globalValue ?? info?.defaultValue ?? value + }, + inspect: (key: string) => (values[key] ? { key, ...values[key] } : undefined), + update: async (key: string, value: unknown, target: number) => { + if (blocked.has(key)) throw new Error("read-only settings") + writes.push({ key, value, target }) + const level = target === 3 ? "workspaceFolderValue" : target === 2 ? "workspaceValue" : "globalValue" + ;(values[key] ??= {})[level] = value + }, + } as WorkspaceConfiguration + return { api, values, writes } +} + +describe("BharatCode settings namespace migration", () => { + it("reads explicit legacy values ahead of new defaults, including false/zero/empty values", () => { + for (const value of [false, 0, "", [], ["existing-model"]]) { + const current = config({ setting: { defaultValue: "new-default" } }) + const legacy = config({ setting: { defaultValue: "other-extension-default", globalValue: value } }) + expect(fallback(current.api, legacy.api).get("setting")).toEqual(value) + expect(current.writes).toEqual([]) + expect(legacy.writes).toEqual([]) + } + }) + + it("never adopts another extension's contributed defaults", () => { + const current = config({ setting: { defaultValue: false } }) + const legacy = config({ setting: { defaultValue: true } }) + expect(fallback(current.api, legacy.api).get("setting")).toBe(false) + expect(fallback(current.api, legacy.api).get("missing", "fallback")).toBe("fallback") + }) + + it("preserves VS Code scope precedence and prefers explicit new values within each scope", () => { + const current = config({ setting: { globalValue: "new-user", workspaceFolderValue: "new-folder" } }) + const legacy = config({ + setting: { globalValue: "old-user", workspaceValue: "old-workspace", workspaceFolderValue: "old-folder" }, + }) + const resolved = fallback(current.api, legacy.api) + expect(resolved.get("setting")).toBe("new-folder") + delete current.values.setting!.workspaceFolderValue + expect(resolved.get("setting")).toBe("old-folder") + delete legacy.values.setting!.workspaceFolderValue + expect(resolved.get("setting")).toBe("old-workspace") + expect(resolved.inspect("setting")).toMatchObject({ globalValue: "new-user", workspaceValue: "old-workspace" }) + current.values.setting!.workspaceValue = false + expect(resolved.get("setting")).toBe(false) + }) + + it("copies only missing explicit values to the same scope without touching old settings", async () => { + const current = config({ setting: { defaultValue: true }, existing: { globalValue: false } }) + const legacy = config({ + setting: { globalValue: false, workspaceValue: true, workspaceFolderValue: false }, + existing: { globalValue: true }, + defaults: { defaultValue: 99 }, + }) + const before = structuredClone(legacy.values) + const errors: unknown[] = [] + for (const [level, target] of [ + ["globalValue", 1], + ["workspaceValue", 2], + ["workspaceFolderValue", 3], + ] as const) { + expect( + await copySettings(current.api, legacy.api, ["setting", "existing", "defaults"], level, target, (_, error) => + errors.push(error), + ), + ).toBe(true) + } + expect(current.writes).toEqual([ + { key: "setting", value: false, target: 1 }, + { key: "setting", value: true, target: 2 }, + { key: "setting", value: false, target: 3 }, + ]) + expect(legacy.values).toEqual(before) + expect(legacy.writes).toEqual([]) + expect(errors).toEqual([]) + expect(await copySettings(current.api, legacy.api, ["setting"], "globalValue", 1, () => {})).toBe(true) + expect(current.writes).toHaveLength(3) + }) + + it("keeps failed values readable, continues other copies, and safely retries", async () => { + const blocked = new Set(["first"]) + const current = config({ first: { defaultValue: true } }, blocked) + const legacy = config({ first: { globalValue: false }, second: { globalValue: 0 } }) + const errors: string[] = [] + expect( + await copySettings(current.api, legacy.api, ["first", "second"], "globalValue", 1, (key) => errors.push(key)), + ).toBe(false) + expect(errors).toEqual(["first"]) + expect(fallback(current.api, legacy.api).get("first")).toBe(false) + expect(current.writes).toEqual([{ key: "second", value: 0, target: 1 }]) + blocked.clear() + expect(await copySettings(current.api, legacy.api, ["first", "second"], "globalValue", 1, () => {})).toBe(true) + expect(current.writes).toHaveLength(2) + }) + + it("does not resurrect old preferences after a migrated setting is reset", async () => { + const current = config({ setting: { defaultValue: true, globalValue: false } }) + const legacy = config({ setting: { globalValue: false } }) + const resolved = fallback(current.api, legacy.api, [true, true, true]) + await resolved.update("setting", undefined, 1) + expect(resolved.get("setting")).toBe(true) + expect(resolved.inspect("setting")?.globalValue).toBeUndefined() + expect(legacy.values.setting!.globalValue).toBe(false) + expect(legacy.writes).toEqual([]) + }) +}) diff --git a/packages/kilo-vscode/tests/unit/provider-actions-save.test.ts b/packages/kilo-vscode/tests/unit/provider-actions-save.test.ts index ac588bc9..dc9851f2 100644 --- a/packages/kilo-vscode/tests/unit/provider-actions-save.test.ts +++ b/packages/kilo-vscode/tests/unit/provider-actions-save.test.ts @@ -543,6 +543,34 @@ describe("disconnectProvider", () => { }) describe("fetchProviderData", () => { + it.each([true, false])( + "preserves Kilo auth readiness independently of BharatCode catalog results (recovered: %s)", + async (recovered) => { + const client = { + provider: { + list: async () => ({ + data: { + all: [{ id: "bharatcode", models: recovered ? { glm: { id: "glm" } } : {} }], + connected: recovered ? ["bharatcode"] : [], + default: {}, + failed: recovered ? [] : ["bharatcode"], + failures: recovered ? [] : [{ providerID: "bharatcode", kind: "http", status: 503 }], + }, + }), + }, + kilo: { + authStatus: async () => { + throw new Error("unrelated Kilo service unavailable") + }, + }, + } as unknown as Parameters[0] + const result = await fetchProviderData(client, "/workspace") + expect(result.ready).toBe(false) + expect(result.response.all[0].id).toBe("bharatcode") + expect(result.response.failures).toHaveLength(recovered ? 0 : 1) + }, + ) + for (const item of [ { name: "uses the allowed organization API default", recommended: "org/default", expected: "org/default" }, { name: "uses the first allowed model when no default exists", recommended: undefined, expected: "org/first" }, diff --git a/packages/kilo-vscode/tests/unit/provider-context-catalog.test.ts b/packages/kilo-vscode/tests/unit/provider-context-catalog.test.ts new file mode 100644 index 00000000..f6d06e0d --- /dev/null +++ b/packages/kilo-vscode/tests/unit/provider-context-catalog.test.ts @@ -0,0 +1,149 @@ +import { describe, expect, it } from "bun:test" +import path from "node:path" +import { Project, SyntaxKind } from "ts-morph" + +const root = path.resolve(import.meta.dir, "../..") +const project = new Project({ useInMemoryFileSystem: true }) +const source = project.createSourceFile( + "provider.tsx", + await Bun.file(path.join(root, "webview-ui/src/context/provider.tsx")).text(), +) +const body = source + .getVariableDeclarationOrThrow("ProviderProvider") + .getInitializerIfKindOrThrow(SyntaxKind.ArrowFunction) + .getBody() + .asKindOrThrow(SyntaxKind.Block) +// Exercise the real context subscriptions and Solid signals without loading the JSX renderer graph. +const setup = new Bun.Transpiler({ loader: "ts" }).transformSync(` + function provider() { + ${body + .getStatements() + .filter((statement) => !statement.isKind(SyntaxKind.ReturnStatement)) + .map((statement) => statement.getText()) + .join("\n")} + return value + } +`) + +function check(code: string) { + const script = ` + import assert from "node:assert/strict" + import { dirname, join } from "node:path" + const solid = join(dirname(require.resolve("solid-js")), "solid.js") + const { batch, createRoot, createSignal, createMemo, onCleanup } = await import(solid) + const { flattenModels, findModel: _findModel, isModelValid: isValid } = await import("./webview-ui/src/context/provider-utils.ts") + const { KILO_AUTO } = await import("./src/shared/provider-model.ts") + const { catalogNotice } = await import("./src/shared/bharatcode-catalog.ts") + const listeners = new Set() + const requests = [] + const useVSCode = () => ({ + onMessage(callback) { listeners.add(callback); return () => listeners.delete(callback) }, + postMessage(message) { requests.push(message) }, + }) + ${setup} + const state = createRoot((dispose) => ({ ...provider(), dispose })) + const post = (message) => { for (const callback of [...listeners]) callback(message) } + const loaded = (overrides = {}) => post({ + type: "providersLoaded", providers: {}, connected: [], defaults: {}, ready: false, + defaultSelection: KILO_AUTO, authMethods: {}, authStates: {}, ...overrides, + }) + const notice = () => catalogNotice({ + ready: state.catalogReady(), connected: state.connected(), failures: state.failures(), + hasModels: state.models().length > 0, + }) + try { ${code} } finally { state.dispose() } + assert.equal(listeners.size, 0) + ` + const child = Bun.spawnSync([process.execPath, "--conditions=browser", "-e", script], { + cwd: root, + stdout: "pipe", + stderr: "pipe", + windowsHide: true, + }) + expect(child.exitCode, child.stdout.toString() + child.stderr.toString()).toBe(0) +} + +describe("provider catalog completion", () => { + it("settles a signed-out empty catalog even when Kilo auth is unavailable", () => { + check(` + assert.equal(state.ready(), false) + assert.equal(state.catalogReady(), false) + assert.equal(notice().key, "bharatcode.catalog.loading") + assert.deepEqual(requests, [{ type: "requestProviders" }]) + loaded() + assert.equal(state.ready(), false) + assert.equal(state.organizationId(), undefined) + assert.equal(state.catalogReady(), true) + assert.deepEqual(notice(), { key: "bharatcode.catalog.signIn", action: "signIn" }) + `) + }) + + it("settles an initial catalog failure without inventing Kilo auth readiness", () => { + check(` + post({ type: "providersLoadFailed", failure: { providerID: "bharatcode", kind: "network" } }) + assert.equal(state.ready(), false) + assert.equal(state.organizationId(), undefined) + assert.equal(state.catalogReady(), true) + assert.equal(notice().key, "bharatcode.catalog.network") + assert.equal(notice().action, "retry") + post({ type: "providersRefreshing" }) + assert.equal(state.catalogReady(), false) + assert.equal(state.ready(), false) + assert.equal(notice().key, "bharatcode.catalog.loading") + loaded() + assert.equal(state.catalogReady(), true) + assert.deepEqual(state.failures(), []) + assert.equal(notice().action, "signIn") + `) + }) + + it("preserves auth, selection, and usable models through retry failure and recovery", () => { + check(` + const selection = { providerID: "bharatcode", modelID: "glm" } + const providers = { bharatcode: { id: "bharatcode", name: "BharatCode", models: { glm: { id: "glm", name: "GLM" } } } } + loaded({ ready: true, organizationId: "org", providers, connected: ["bharatcode"], + defaults: { bharatcode: "glm" }, defaultSelection: selection, authStates: { bharatcode: "oauth" }, + failures: [{ providerID: "other", kind: "network" }] }) + const models = state.models() + post({ type: "providersRefreshing" }) + assert.equal(state.catalogReady(), false) + assert.equal(state.ready(), true) + assert.equal(state.organizationId(), "org") + assert.equal(state.models(), models) + assert.equal(notice().key, "bharatcode.catalog.loading") + for (const kind of ["network", "unauthorized"]) { + post({ type: "providersLoadFailed", failure: { providerID: "bharatcode", kind } }) + assert.equal(state.catalogReady(), true) + assert.equal(state.ready(), true) + assert.equal(state.organizationId(), "org") + assert.equal(state.models(), models) + assert.deepEqual(state.defaultSelection(), selection) + assert.deepEqual(state.defaults(), { bharatcode: "glm" }) + assert.deepEqual(state.authStates(), { bharatcode: "oauth" }) + assert.deepEqual(state.failures(), [{ providerID: "other", kind: "network" }, { providerID: "bharatcode", kind }]) + } + assert.equal(notice().action, "signIn") + loaded({ providers, connected: ["bharatcode"], defaultSelection: selection }) + assert.equal(state.catalogReady(), true) + assert.equal(state.ready(), false) + assert.deepEqual(state.failures(), []) + assert.equal(notice(), undefined) + `) + }) + + it("resets catalog completion and auth readiness for a new provider load", () => { + check(` + loaded({ ready: true, organizationId: "org" }) + assert.equal(state.catalogReady(), true) + assert.equal(state.ready(), true) + post({ type: "providersLoading" }) + assert.equal(state.catalogReady(), false) + assert.equal(state.ready(), false) + assert.equal(state.organizationId(), undefined) + assert.equal(notice().key, "bharatcode.catalog.loading") + loaded() + assert.equal(state.catalogReady(), true) + assert.equal(state.ready(), false) + `) + }) +}) diff --git a/packages/kilo-vscode/tests/unit/push-fixes-settings.test.ts b/packages/kilo-vscode/tests/unit/push-fixes-settings.test.ts index 7a829afb..9b1cf760 100644 --- a/packages/kilo-vscode/tests/unit/push-fixes-settings.test.ts +++ b/packages/kilo-vscode/tests/unit/push-fixes-settings.test.ts @@ -20,7 +20,7 @@ const original = { function stubConfig(state: Map) { ;(vscode.workspace as unknown as Stub).getConfiguration = (section?: string) => { - if (section !== "kilo-code.new.agentManager") { + if (section !== "bharatcode-agent.agentManager") { return { get: (_key: string, fallback?: T) => fallback } } return { @@ -66,18 +66,18 @@ describe("push fixes settings", () => { for (const listener of listeners) listener({ affectsConfiguration: (name) => name === key }) } - emit("kilo-code.new.agentManager.autoBranchNaming") + emit("bharatcode-agent.agentManager.autoBranchNaming") expect(parent).toEqual([]) expect(child).toEqual([]) state.set("pushFixes", false) - emit("kilo-code.new.agentManager.pushFixes") + emit("bharatcode-agent.agentManager.pushFixes") expect(parent).toEqual([{ type: "pushFixesSettingLoaded", enabled: false }]) expect(child).toEqual(parent) viewer.dispose() state.set("pushFixes", true) - emit("kilo-code.new.agentManager.pushFixes") + emit("bharatcode-agent.agentManager.pushFixes") expect(parent).toHaveLength(2) expect(child).toHaveLength(1) diff --git a/packages/kilo-vscode/tests/unit/register-code-actions.test.ts b/packages/kilo-vscode/tests/unit/register-code-actions.test.ts index a7843bca..0e9b3a98 100644 --- a/packages/kilo-vscode/tests/unit/register-code-actions.test.ts +++ b/packages/kilo-vscode/tests/unit/register-code-actions.test.ts @@ -119,7 +119,7 @@ describe("registerCodeActions", () => { it("keeps targeting Agent Manager after the code editor takes focus", async () => { const state = setup(false, true, "agent") - await state.commands.get("kilo-code.new.addToContext")?.() + await state.commands.get("bharatcode-agent.addToContext")?.() expect(state.recipients).toEqual(["agent"]) expect(state.executed).toEqual([]) @@ -130,19 +130,19 @@ describe("registerCodeActions", () => { it.each(["sidebar", "tab"] as const)("prefers the last focused %s over the active panel", async (last) => { const state = setup(true, true, last) - await state.commands.get("kilo-code.new.addToContext")?.() + await state.commands.get("bharatcode-agent.addToContext")?.() expect(state.recipients).toEqual([last]) - expect(state.executed).toEqual(last === "sidebar" ? [["kilo-code.SidebarProvider.focus"]] : []) + expect(state.executed).toEqual(last === "sidebar" ? [["bharatcode-agent.SidebarProvider.focus"]] : []) expectContextPost(state.posts.at(0)) }) it("uses the latest focused chat and falls back after it closes", async () => { const state = setup(false, true, "tab") state.focused.current = "agent" - await state.commands.get("kilo-code.new.addToContext")?.() + await state.commands.get("bharatcode-agent.addToContext")?.() state.focused.current = undefined - await state.commands.get("kilo-code.new.addToContext")?.() + await state.commands.get("bharatcode-agent.addToContext")?.() expect(state.recipients).toEqual(["agent", "sidebar"]) }) @@ -150,7 +150,7 @@ describe("registerCodeActions", () => { it("does not reroute when the remembered Agent Manager closes while waiting", async () => { const state = setup(false, false, "agent") - await state.commands.get("kilo-code.new.addToContext")?.() + await state.commands.get("bharatcode-agent.addToContext")?.() expect(state.waits).toEqual(["agent"]) expect(state.recipients).toEqual([]) @@ -160,8 +160,8 @@ describe("registerCodeActions", () => { it("keeps focus-only commands on their existing route", async () => { const state = setup(false, true, "agent") - await state.commands.get("kilo-code.new.focusChatInput")?.() - await state.commands.get("kilo-code.new.toggleChatSearch")?.() + await state.commands.get("bharatcode-agent.focusChatInput")?.() + await state.commands.get("bharatcode-agent.toggleChatSearch")?.() expect(state.recipients).toEqual(["sidebar", "sidebar"]) expect(state.waits).toEqual(["provider", "provider"]) @@ -170,10 +170,10 @@ describe("registerCodeActions", () => { it("reveals the sidebar before adding selected code to context", async () => { const state = setup() - await state.commands.get("kilo-code.new.addToContext")?.() + await state.commands.get("bharatcode-agent.addToContext")?.() expect(state.events).toEqual(["focus", "wait", "post"]) - expect(state.executed).toEqual([["kilo-code.SidebarProvider.focus"]]) + expect(state.executed).toEqual([["bharatcode-agent.SidebarProvider.focus"]]) expect(state.waits).toEqual(["provider"]) expect(state.posts).toHaveLength(1) expectContextPost(state.posts[0]) @@ -182,7 +182,7 @@ describe("registerCodeActions", () => { it("adds selected code to the active Agent Manager without revealing the sidebar", async () => { const state = setup(true) - await state.commands.get("kilo-code.new.addToContext")?.() + await state.commands.get("bharatcode-agent.addToContext")?.() expect(state.events).toEqual(["wait", "post"]) expect(state.executed).toEqual([]) @@ -194,7 +194,7 @@ describe("registerCodeActions", () => { it("does not post to the Agent Manager when its readiness wait is cancelled", async () => { const state = setup(true, false) - await state.commands.get("kilo-code.new.addToContext")?.() + await state.commands.get("bharatcode-agent.addToContext")?.() expect(state.events).toEqual(["wait"]) expect(state.posts).toEqual([]) @@ -203,7 +203,7 @@ describe("registerCodeActions", () => { it("toggles chat search on the active Agent Manager once it is ready", async () => { const state = setup(true) - await state.commands.get("kilo-code.new.toggleChatSearch")?.() + await state.commands.get("bharatcode-agent.toggleChatSearch")?.() expect(state.events).toEqual(["wait", "post"]) expect(state.posts).toEqual([{ type: "action", action: "focusSearch" }]) @@ -212,7 +212,7 @@ describe("registerCodeActions", () => { it("does not toggle chat search when Agent Manager readiness is cancelled", async () => { const state = setup(true, false) - await state.commands.get("kilo-code.new.toggleChatSearch")?.() + await state.commands.get("bharatcode-agent.toggleChatSearch")?.() expect(state.events).toEqual(["wait"]) expect(state.posts).toEqual([]) diff --git a/packages/kilo-vscode/tests/unit/register-terminal-actions.test.ts b/packages/kilo-vscode/tests/unit/register-terminal-actions.test.ts index f599f9c4..cf50445f 100644 --- a/packages/kilo-vscode/tests/unit/register-terminal-actions.test.ts +++ b/packages/kilo-vscode/tests/unit/register-terminal-actions.test.ts @@ -65,10 +65,10 @@ describe("registerTerminalActions", () => { it("reveals the sidebar before adding terminal output to context", async () => { const state = setup() - await state.commands.get("kilo-code.new.terminalAddToContext")?.({ selection: "bun test" }) + await state.commands.get("bharatcode-agent.terminalAddToContext")?.({ selection: "bun test" }) expect(state.events).toEqual(["focus", "wait", "post", "post"]) - expect(state.executed).toEqual([["kilo-code.SidebarProvider.focus"]]) + expect(state.executed).toEqual([["bharatcode-agent.SidebarProvider.focus"]]) expect(state.waits).toEqual(["provider"]) expect(state.posts).toEqual([ { @@ -82,7 +82,7 @@ describe("registerTerminalActions", () => { it("adds terminal output to the active Agent Manager without revealing the sidebar", async () => { const state = setup(true) - await state.commands.get("kilo-code.new.terminalAddToContext")?.({ selection: "bun test" }) + await state.commands.get("bharatcode-agent.terminalAddToContext")?.({ selection: "bun test" }) expect(state.events).toEqual(["post", "post"]) expect(state.executed).toEqual([]) diff --git a/packages/kilo-vscode/tests/unit/reuse-candidate-resources.test.ts b/packages/kilo-vscode/tests/unit/reuse-candidate-resources.test.ts new file mode 100644 index 00000000..45390a89 --- /dev/null +++ b/packages/kilo-vscode/tests/unit/reuse-candidate-resources.test.ts @@ -0,0 +1,63 @@ +import { expect, test } from "bun:test" +import { chmod, cp, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { + copyKiloSandboxWorker, + copySandboxResources, + copyTreeSitterResources, +} from "../../src/services/cli-backend/cli-resources" + +test("packaging copies parent companions from CLI_DIST_DIR without regenerating them", async () => { + const root = await mkdtemp(join(tmpdir(), "bharatcode-reuse-resources-")) + try { + for (const target of [ + "win32-x64", + "win32-arm64", + "linux-x64", + "linux-arm64", + "alpine-x64", + "alpine-arm64", + "darwin-x64", + "darwin-arm64", + ]) { + const source = join(root, target, "source") + const output = join(root, target, "output") + const binary = target.startsWith("win32-") ? "bharatcode.exe" : "bharatcode" + const files: Record = { + [binary]: `synthetic ${target} backend`, + "tree-sitter/tree-sitter.wasm": "parent runtime", + "tree-sitter/tree-sitter-bash.wasm": "parent grammar", + "kilo-sandbox-mutation-worker.js": "parent worker", + ...(target.startsWith("linux-") || target.startsWith("alpine-") + ? { + "kilo-sandbox-network-relay.js": "parent relay", + "kilo-sandbox-seccomp": "parent seccomp", + "licenses/sandbox-runtime/LICENSE": "parent license", + } + : {}), + } + for (const [name, data] of Object.entries(files)) { + const file = join(source, name) + await mkdir(join(file, ".."), { recursive: true }) + await writeFile(file, data) + await chmod(file, name === binary || name.endsWith(".wasm") || name.endsWith("seccomp") ? 0o755 : 0o644) + } + await mkdir(output) + await cp(join(source, binary), join(output, binary)) + await copyTreeSitterResources(join(source, binary), join(output, binary)) + await copySandboxResources(join(source, binary), join(output, binary)) + await copyKiloSandboxWorker(join(source, binary), join(output, binary)) + const entries = await readdir(output, { recursive: true, withFileTypes: true }) + expect(entries.filter((entry) => entry.isFile())).toHaveLength(Object.keys(files).length) + for (const name of Object.keys(files)) { + expect(await readFile(join(output, name))).toEqual(await readFile(join(source, name))) + if (process.platform !== "win32") { + expect((await stat(join(output, name))).mode & 0o777).toBe((await stat(join(source, name))).mode & 0o777) + } + } + } + } finally { + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/packages/kilo-vscode/tests/unit/session-terminal-manager.test.ts b/packages/kilo-vscode/tests/unit/session-terminal-manager.test.ts index 42886985..fb73ef58 100644 --- a/packages/kilo-vscode/tests/unit/session-terminal-manager.test.ts +++ b/packages/kilo-vscode/tests/unit/session-terminal-manager.test.ts @@ -77,7 +77,7 @@ describe("SessionTerminalManager structure", () => { it("dispose clears the context key, disposes terminals, and clears the map", () => { const text = body("dispose") // All three are required for clean shutdown — missing any would leak resources - expect(text).toContain("kilo-code.agentTerminalFocus") + expect(text).toContain("bharatcode-agent.agentTerminalFocus") expect(text).toContain("terminal.dispose()") expect(text).toContain("terminals.clear()") }) diff --git a/packages/kilo-vscode/tests/unit/setup-script-task.test.ts b/packages/kilo-vscode/tests/unit/setup-script-task.test.ts index 013a13f9..e792d23c 100644 --- a/packages/kilo-vscode/tests/unit/setup-script-task.test.ts +++ b/packages/kilo-vscode/tests/unit/setup-script-task.test.ts @@ -406,7 +406,11 @@ describe("setupTaskIdentity", () => { expect(a.definition).not.toEqual(b.definition) expect(a.name).not.toBe(b.name) - expect(a.definition).toEqual({ type: "kilo-worktree-setup", script: "sh", worktree: "/repo/.kilo/worktrees/a" }) + expect(a.definition).toEqual({ + type: "bharatcode-agent.worktree-setup", + script: "sh", + worktree: "/repo/.kilo/worktrees/a", + }) expect(a.name).toBe("Worktree Setup (a)") }) }) diff --git a/packages/kilo-vscode/tests/unit/shortcut-hints-settings.test.ts b/packages/kilo-vscode/tests/unit/shortcut-hints-settings.test.ts index 9ce52cab..227e972d 100644 --- a/packages/kilo-vscode/tests/unit/shortcut-hints-settings.test.ts +++ b/packages/kilo-vscode/tests/unit/shortcut-hints-settings.test.ts @@ -20,7 +20,7 @@ const original = { function stubConfig(state: Map) { ;(vscode.workspace as unknown as Stub).getConfiguration = (section?: string) => { - if (section !== "kilo-code.new") { + if (section !== "bharatcode-agent") { return { get: (_key: string, fallback?: T) => fallback } } return { @@ -66,18 +66,18 @@ describe("shortcut hints settings", () => { for (const listener of listeners) listener({ affectsConfiguration: (name) => name === key }) } - emit("kilo-code.new.agentManager.autoBranchNaming") + emit("bharatcode-agent.agentManager.autoBranchNaming") expect(parent).toEqual([]) expect(child).toEqual([]) state.set("showShortcutHints", false) - emit("kilo-code.new.showShortcutHints") + emit("bharatcode-agent.showShortcutHints") expect(parent).toEqual([{ type: "shortcutHintsSettingLoaded", visible: false }]) expect(child).toEqual(parent) viewer.dispose() state.set("showShortcutHints", true) - emit("kilo-code.new.showShortcutHints") + emit("bharatcode-agent.showShortcutHints") expect(parent).toHaveLength(2) expect(child).toHaveLength(1) diff --git a/packages/kilo-vscode/tests/unit/throughput-settings-message.test.ts b/packages/kilo-vscode/tests/unit/throughput-settings-message.test.ts index cba5ff5c..330b7137 100644 --- a/packages/kilo-vscode/tests/unit/throughput-settings-message.test.ts +++ b/packages/kilo-vscode/tests/unit/throughput-settings-message.test.ts @@ -12,7 +12,7 @@ const original = vscode.workspace.getConfiguration function stubConfig(state: Map) { ;(vscode.workspace as unknown as Stub).getConfiguration = (section?: string) => { - if (section !== "kilo-code.new") { + if (section !== "bharatcode-agent") { return { get: (_key: string, fallback?: T) => fallback } } return { diff --git a/packages/kilo-vscode/tests/unit/user-keybindings.test.ts b/packages/kilo-vscode/tests/unit/user-keybindings.test.ts index 82bfe9be..cf0ecf83 100644 --- a/packages/kilo-vscode/tests/unit/user-keybindings.test.ts +++ b/packages/kilo-vscode/tests/unit/user-keybindings.test.ts @@ -4,9 +4,9 @@ import { buildKeybindingMap } from "../../src/agent-manager/format-keybinding" import { mergeUserKeybindings, parseJsonc, userKeybindingFiles } from "../../src/agent-manager/user-keybindings" const defaults = [ - { command: "kilo-code.new.agentManagerOpen", key: "ctrl+shift+m", mac: "cmd+shift+m" }, - { command: "kilo-code.new.agentManager.toggleDiff", key: "ctrl+d", mac: "cmd+d" }, - { command: "kilo-code.new.agentManager.showShortcuts", key: "ctrl+shift+/", mac: "cmd+shift+/" }, + { command: "bharatcode-agent.agentManagerOpen", key: "ctrl+shift+m", mac: "cmd+shift+m" }, + { command: "bharatcode-agent.agentManager.toggleDiff", key: "ctrl+d", mac: "cmd+d" }, + { command: "bharatcode-agent.agentManager.showShortcuts", key: "ctrl+shift+/", mac: "cmd+shift+/" }, ] const map = (user: unknown, mac: boolean) => buildKeybindingMap(mergeUserKeybindings(defaults, user, mac), mac) @@ -15,35 +15,35 @@ describe("user keybindings", () => { it("parses keybindings.json with comments and trailing commas", () => { const text = `// Place your key bindings in this file [ - { "key": "cmd+j", "command": "kilo-code.new.agentManagerOpen" }, /* block */ + { "key": "cmd+j", "command": "bharatcode-agent.agentManagerOpen" }, /* block */ { "key": "cmd+//", "command": "x", "when": "a // not a comment" }, ]` expect(parseJsonc(text)).toEqual([ - { key: "cmd+j", command: "kilo-code.new.agentManagerOpen" }, + { key: "cmd+j", command: "bharatcode-agent.agentManagerOpen" }, { key: "cmd+//", command: "x", when: "a // not a comment" }, ]) expect(parseJsonc("[ { ")).toBeUndefined() }) it("shows the user's shortcut instead of the default", () => { - const user = [{ key: "cmd+j", command: "kilo-code.new.agentManagerOpen" }] + const user = [{ key: "cmd+j", command: "bharatcode-agent.agentManagerOpen" }] expect(map(user, true).agentManagerOpen).toBe("⌘J") - expect(map([{ key: "ctrl+alt+j", command: "kilo-code.new.agentManagerOpen" }], false).agentManagerOpen).toBe( + expect(map([{ key: "ctrl+alt+j", command: "bharatcode-agent.agentManagerOpen" }], false).agentManagerOpen).toBe( "Ctrl+Alt+J", ) expect(map(undefined, false).agentManagerOpen).toBe("Ctrl+Shift+M") }) it("formats chords", () => { - expect(map([{ key: "cmd+k cmd+d", command: "kilo-code.new.agentManager.toggleDiff" }], true).toggleDiff).toBe( + expect(map([{ key: "cmd+k cmd+d", command: "bharatcode-agent.agentManager.toggleDiff" }], true).toggleDiff).toBe( "⌘K ⌘D", ) }) it("hides a removed shortcut instead of showing its fallback", () => { - const user = [{ key: "cmd+d", command: "-kilo-code.new.agentManager.toggleDiff" }] + const user = [{ key: "cmd+d", command: "-bharatcode-agent.agentManager.toggleDiff" }] expect(map(user, true).toggleDiff).toBeUndefined() - const other = [{ key: "cmd+x", command: "-kilo-code.new.agentManager.toggleDiff" }] + const other = [{ key: "cmd+x", command: "-bharatcode-agent.agentManager.toggleDiff" }] expect(map(other, true).toggleDiff).toBe("⌘D") }) diff --git a/packages/kilo-vscode/webview-ui/src/components/chat/AssistantMessage.tsx b/packages/kilo-vscode/webview-ui/src/components/chat/AssistantMessage.tsx index 47785dc8..6ca875e5 100644 --- a/packages/kilo-vscode/webview-ui/src/components/chat/AssistantMessage.tsx +++ b/packages/kilo-vscode/webview-ui/src/components/chat/AssistantMessage.tsx @@ -231,7 +231,7 @@ function BashToolCard(props: { part: ToolPart; defaultOpen: boolean }) { * rate across the turn's model-generation steps (output + reasoning * tokens over active generation time). * - * Visibility is gated by the same `kilo-code.new.showTokenThroughput` + * Visibility is gated by the same `bharatcode-agent.showTokenThroughput` * toggle that previously controlled the multi-row badge. The metric only * renders when the message has at least one step-finish part carrying both * a token count and elapsed timing. diff --git a/packages/kilo-vscode/webview-ui/src/components/chat/ErrorDisplay.tsx b/packages/kilo-vscode/webview-ui/src/components/chat/ErrorDisplay.tsx index a0f5b2e5..1509c6cb 100644 --- a/packages/kilo-vscode/webview-ui/src/components/chat/ErrorDisplay.tsx +++ b/packages/kilo-vscode/webview-ui/src/components/chat/ErrorDisplay.tsx @@ -8,6 +8,7 @@ import { Button } from "@kilocode/kilo-ui/button" import type { AssistantMessage } from "@kilocode/sdk/v2" import { useLanguage } from "../../context/language" import { useProvider } from "../../context/provider" +import { useVSCode } from "../../context/vscode" import { unwrapError, parseAssistantError, parseProviderAuthError } from "../../utils/errorUtils" import ProviderConnectDialog from "../settings/ProviderConnectDialog" @@ -19,6 +20,7 @@ export interface ErrorDisplayProps { export const ErrorDisplay: Component = (props) => { const { t } = useLanguage() const dialog = useDialog() + const vscode = useVSCode() const provider = useProvider() const parsed = createMemo(() => parseAssistantError(props.error)) const auth = createMemo(() => parseProviderAuthError(props.error)) @@ -51,6 +53,10 @@ export const ErrorDisplay: Component = (props) => { function connectProvider() { const err = auth() if (!err) return + if (err.providerID === "bharatcode") { + vscode.postMessage({ type: "connectBharatcode" }) + return + } dialog.show(() => ) } diff --git a/packages/kilo-vscode/webview-ui/src/components/chat/FeedbackDialog.tsx b/packages/kilo-vscode/webview-ui/src/components/chat/FeedbackDialog.tsx index 6acebcc0..d3f4817c 100644 --- a/packages/kilo-vscode/webview-ui/src/components/chat/FeedbackDialog.tsx +++ b/packages/kilo-vscode/webview-ui/src/components/chat/FeedbackDialog.tsx @@ -7,7 +7,7 @@ import { BharatCodeMark } from "../brand/BharatCodeMark" import { useVSCode } from "../../context/vscode" import { useLanguage } from "../../context/language" -const GITHUB_ISSUES_URL = "https://github.com/thenabbu/BharatCode-VSCode-Extension/issues/new/choose" +const GITHUB_ISSUES_URL = "https://github.com/BharatCode-ai/bharatcode-vscode/issues/new/choose" const DISCORD_URL = "https://bharatcode.ai" const SUPPORT_URL = "https://bharatcode.ai" diff --git a/packages/kilo-vscode/webview-ui/src/components/chat/WelcomeEmptyState.tsx b/packages/kilo-vscode/webview-ui/src/components/chat/WelcomeEmptyState.tsx index c4700f51..ead93c2e 100644 --- a/packages/kilo-vscode/webview-ui/src/components/chat/WelcomeEmptyState.tsx +++ b/packages/kilo-vscode/webview-ui/src/components/chat/WelcomeEmptyState.tsx @@ -64,7 +64,6 @@ export const WelcomeEmptyState: Component = (props) => { -

{language.t("session.onboarding.hint")}

diff --git a/packages/kilo-vscode/webview-ui/src/components/marketplace/MarketplaceContribute.tsx b/packages/kilo-vscode/webview-ui/src/components/marketplace/MarketplaceContribute.tsx index 26fb746c..d9c62966 100644 --- a/packages/kilo-vscode/webview-ui/src/components/marketplace/MarketplaceContribute.tsx +++ b/packages/kilo-vscode/webview-ui/src/components/marketplace/MarketplaceContribute.tsx @@ -2,7 +2,7 @@ import { Button } from "@kilocode/kilo-ui/button" import { useVSCode } from "../../context/vscode" import { useLanguage } from "../../context/language" -const REPO_URL = "https://github.com/thenabbu/BharatCode-VSCode-Extension" +const REPO_URL = "https://github.com/BharatCode-ai/bharatcode-vscode" export const MarketplaceContribute = () => { const vscode = useVSCode() diff --git a/packages/kilo-vscode/webview-ui/src/components/settings/AboutKiloCodeTab.tsx b/packages/kilo-vscode/webview-ui/src/components/settings/AboutKiloCodeTab.tsx index 90bf8639..5cf49451 100644 --- a/packages/kilo-vscode/webview-ui/src/components/settings/AboutKiloCodeTab.tsx +++ b/packages/kilo-vscode/webview-ui/src/components/settings/AboutKiloCodeTab.tsx @@ -208,10 +208,7 @@ const AboutKiloCodeTab: Component = (props) => { }} > {language.t("settings.aboutKiloCode.feedback.prefix")}{" "} - open("https://github.com/thenabbu/BharatCode-VSCode-Extension/issues")} - > + open("https://github.com/BharatCode-ai/bharatcode-vscode/issues")}> GitHub ,{" "} diff --git a/packages/kilo-vscode/webview-ui/src/components/settings/ProviderSelectDialog.tsx b/packages/kilo-vscode/webview-ui/src/components/settings/ProviderSelectDialog.tsx index d682a8b5..926d71d1 100644 --- a/packages/kilo-vscode/webview-ui/src/components/settings/ProviderSelectDialog.tsx +++ b/packages/kilo-vscode/webview-ui/src/components/settings/ProviderSelectDialog.tsx @@ -8,6 +8,7 @@ import type { ProviderFailure } from "@kilocode/sdk/v2/client" import { useConfig } from "../../context/config" import { useLanguage } from "../../context/language" import { useProvider } from "../../context/provider" +import { useVSCode } from "../../context/vscode" import type { Provider } from "../../types/messages" import ProviderConnectDialog from "./ProviderConnectDialog" import { CUSTOM_PROVIDER_ID, isPopularProvider, providerIcon, popularProviderIndex } from "./provider-catalog" @@ -23,6 +24,7 @@ type ProviderItem = { const ProviderSelectDialog = () => { const dialog = useDialog() + const vscode = useVSCode() const { config } = useConfig() const provider = useProvider() const language = useLanguage() @@ -50,6 +52,11 @@ const ProviderSelectDialog = () => { }) function open(item: ProviderItem) { + if (item.id === "bharatcode") { + dialog.close() + vscode.postMessage({ type: "connectBharatcode" }) + return + } if (item.id === CUSTOM_PROVIDER_ID) { dialog.show(() => dialog.show(() => )} />) return diff --git a/packages/kilo-vscode/webview-ui/src/components/settings/ProvidersTab.tsx b/packages/kilo-vscode/webview-ui/src/components/settings/ProvidersTab.tsx index f63c4576..ddef14f0 100644 --- a/packages/kilo-vscode/webview-ui/src/components/settings/ProvidersTab.tsx +++ b/packages/kilo-vscode/webview-ui/src/components/settings/ProvidersTab.tsx @@ -135,6 +135,10 @@ const ProvidersTab: Component = () => { } function connectProvider(item: Provider) { + if (item.id === "bharatcode") { + vscode.postMessage({ type: "connectBharatcode" }) + return + } dialog.show(() => ) } diff --git a/packages/kilo-vscode/webview-ui/src/components/shared/ModelSelector.tsx b/packages/kilo-vscode/webview-ui/src/components/shared/ModelSelector.tsx index a06e4963..8f0792fe 100644 --- a/packages/kilo-vscode/webview-ui/src/components/shared/ModelSelector.tsx +++ b/packages/kilo-vscode/webview-ui/src/components/shared/ModelSelector.tsx @@ -49,6 +49,7 @@ import { rankModelSearch, } from "./model-selector-utils" import { providerFailure, providerFailureMessageKey } from "../../../../src/shared/provider-model" +import { catalogNotice } from "../../../../src/shared/bharatcode-catalog" import { ModelPreview } from "./ModelPreview" // --------------------------------------------------------------------------- @@ -74,6 +75,10 @@ function groupKey(key: string) { return `group:${key}` } +function isButtonEvent(event: KeyboardEvent) { + return !!event.target && !!(event.target as Element).closest?.("button") +} + // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- @@ -151,7 +156,7 @@ export interface ModelSelectorBaseProps { } export const ModelSelectorBase: Component = (props) => { - const { connected, models, findModel, kiloUnavailable, failures } = useProvider() + const { connected, models, findModel, kiloUnavailable, failures, catalogReady } = useProvider() const language = useLanguage() const vscode = useVSCode() // Session context is optional — ModelSelectorBase is also used in Settings @@ -251,7 +256,8 @@ export const ModelSelectorBase: Component = (props) => { const c = connected() return models().some((m) => available(m, c)) }) - const canOpen = () => hasProviders() || ((props.allowClear ?? false) && !!props.value) + // An empty selector must remain usable so users can see and recover from a catalog failure. + const canOpen = () => !props.models || hasProviders() || ((props.allowClear ?? false) && !!props.value) // Flat filtered list for keyboard navigation const filtered = createMemo(() => { @@ -768,6 +774,8 @@ export const ModelSelectorBase: Component = (props) => { return } + // Preserve native Enter/Space activation for retry, sign-in and other popup buttons. + if (isButtonEvent(e)) return if (list.length === 0) return if (e.key === "ArrowDown" || e.key === "ArrowUp") { @@ -815,7 +823,30 @@ export const ModelSelectorBase: Component = (props) => { } const kiloModelFailure = createMemo(() => providerFailure(KILO_GATEWAY_ID, failures())) + const notice = createMemo(() => + props.models + ? undefined + : catalogNotice({ + ready: catalogReady(), + connected: connected(), + failures: failures(), + hasModels: hasProviders(), + }), + ) + const recoverCatalog = () => { + if (notice()?.action === "signIn") vscode.postMessage({ type: "connectBharatcode" }) + else if (catalogReady()) vscode.postMessage({ type: "requestProviders", refresh: true }) + } const noProvidersLabel = () => { + const state = notice() + if (state) + return language.t( + !catalogReady() + ? "bharatcode.catalog.loading" + : state.action === "signIn" + ? "bharatcode.catalog.signIn" + : "bharatcode.catalog.unavailable", + ) const failure = kiloModelFailure() if (failure) { const { key, vars } = providerFailureMessageKey(failure) @@ -988,6 +1019,19 @@ export const ModelSelectorBase: Component = (props) => { + + {(state) => ( +
+ {language.t(state().key, state().vars)} + + + +
+ )} +
+
= (props) => { ref={listRef} onMouseMove={pointerMove} > - +
{language.t("dialog.model.empty")}
diff --git a/packages/kilo-vscode/webview-ui/src/context/provider.tsx b/packages/kilo-vscode/webview-ui/src/context/provider.tsx index f2a493f8..01fc955f 100644 --- a/packages/kilo-vscode/webview-ui/src/context/provider.tsx +++ b/packages/kilo-vscode/webview-ui/src/context/provider.tsx @@ -20,6 +20,8 @@ interface ProviderContextValue { defaults: Accessor> organizationId: Accessor ready: Accessor + /** The provider catalog request has settled, independently of Kilo auth readiness. */ + catalogReady: Accessor defaultSelection: Accessor models: Accessor findModel: (selection: ModelSelection | null) => EnrichedModel | undefined @@ -42,6 +44,7 @@ export const ProviderProvider: ParentComponent = (props) => { const [defaults, setDefaults] = createSignal>({}) const [organizationId, setOrganizationId] = createSignal() const [ready, setReady] = createSignal(false) + const [catalogReady, setCatalogReady] = createSignal(false) const [defaultSelection, setDefaultSelection] = createSignal(KILO_AUTO) const [authMethods, setAuthMethods] = createSignal>({}) const [authStates, setAuthStates] = createSignal>({}) @@ -61,9 +64,24 @@ export const ProviderProvider: ParentComponent = (props) => { // Register handler immediately (not in onMount) so we never miss // a providersLoaded message that arrives before the DOM mount. const unsubscribe = vscode.onMessage((message: ExtensionMessage) => { + if (message.type === "providersRefreshing") { + setCatalogReady(false) + return + } + if (message.type === "providersLoadFailed") { + batch(() => { + setCatalogReady(true) + setFailures((prev) => [ + ...prev.filter((item) => item.providerID !== message.failure.providerID), + message.failure, + ]) + }) + return + } if (message.type === "providersLoading") { batch(() => { setReady(false) + setCatalogReady(false) setOrganizationId(undefined) setProviders((prev) => { const next = { ...prev } @@ -88,6 +106,7 @@ export const ProviderProvider: ParentComponent = (props) => { setDefaults(message.defaults) setOrganizationId(message.ready === false ? undefined : (message.organizationId ?? null)) setReady(message.ready ?? true) + setCatalogReady(true) setDefaultSelection(message.defaultSelection) setAuthMethods(message.authMethods) setAuthStates(message.authStates) @@ -128,6 +147,7 @@ export const ProviderProvider: ParentComponent = (props) => { defaults, organizationId, ready, + catalogReady, defaultSelection, models, findModel, diff --git a/packages/kilo-vscode/webview-ui/src/i18n/ar.ts b/packages/kilo-vscode/webview-ui/src/i18n/ar.ts index 28148e83..3a61e083 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/ar.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/ar.ts @@ -743,10 +743,9 @@ export const dict = { "session.messages.welcome": "يشغّل BharatCode وكيلًا في هذه اللوحة مدعومًا بنماذج BharatCode الخاصة بك. اطلب منه إنشاء ميزات أو إصلاح الأخطاء أو شرح شيفرتك.", - "session.messages.connect": "ربط BharatCode", + "session.messages.connect": "تسجيل الدخول باستخدام BharatCode", "session.onboarding.title": "إعداد BharatCode", - "session.onboarding.body": - "سجّل الدخول من المتصفح أو الصق مفتاح API - كلاهما يعمل. يحفظ الإصدار الحساب ولا يُخزَّن في الإعدادات.", + "session.onboarding.body": "وافق على السماح بالوصول على موقع BharatCode، ثم ارجع إلى VS Code.", "session.onboarding.hint": "BharatCode هو الوكيل في هذه اللوحة. اربطه مرة واحدة وابدأ.", "session.workspaceScope.description": "تستخدم دردشة BharatCode المجلد «{{folder}}» فقط، وهو المجلد الأول في مساحة العمل هذه.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/br.ts b/packages/kilo-vscode/webview-ui/src/i18n/br.ts index ef65eaaf..a8c296cd 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/br.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/br.ts @@ -762,10 +762,9 @@ export const dict = { "session.messages.welcome": "BharatCode executa um agente neste painel, com seus modelos BharatCode. Peça para criar recursos, corrigir bugs ou explicar seu código.", - "session.messages.connect": "Conectar BharatCode", + "session.messages.connect": "Entrar com BharatCode", "session.onboarding.title": "Configurar BharatCode", - "session.onboarding.body": - "Entre pelo navegador ou cole uma chave de API — os dois funcionam. A conta fica na extensão, nunca nas configurações.", + "session.onboarding.body": "Autorize o acesso no site do BharatCode e volte ao VS Code.", "session.onboarding.hint": "BharatCode é o agente deste painel. Conecte uma vez e comece.", "session.workspaceScope.description": "O chat do BharatCode usa apenas “{{folder}}”, a primeira pasta deste espaço de trabalho.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/bs.ts b/packages/kilo-vscode/webview-ui/src/i18n/bs.ts index b29d3b28..551fcda1 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/bs.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/bs.ts @@ -760,10 +760,9 @@ export const dict = { "session.messages.welcome": "BharatCode pokreće agenta u ovom panelu, na vašim BharatCode modelima. Zamolite ga da napravi funkciju, ispravi grešku ili objasni vašu bazu koda.", - "session.messages.connect": "Poveži BharatCode", + "session.messages.connect": "Prijavi se putem BharatCode", "session.onboarding.title": "Podesi BharatCode", - "session.onboarding.body": - "Prijavite se u pregledniku ili zalijepite API ključ — oboje radi. Račun čuva ekstenzija, nikad postavke.", + "session.onboarding.body": "Odobri pristup na stranici BharatCode, pa se vrati u VS Code.", "session.onboarding.hint": "BharatCode je agent u ovom panelu. Povežite ga jednom i počnite.", "session.workspaceScope.description": "BharatCode razgovor koristi samo „{{folder}}“, prvi folder u ovom radnom prostoru.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/da.ts b/packages/kilo-vscode/webview-ui/src/i18n/da.ts index df613bc3..d3502980 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/da.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/da.ts @@ -758,10 +758,9 @@ export const dict = { "session.messages.welcome": "BharatCode kører en agent i dette panel på dine BharatCode-modeller. Bed den om at bygge funktioner, rette fejl eller forklare din kodebase.", - "session.messages.connect": "Forbind BharatCode", + "session.messages.connect": "Log ind med BharatCode", "session.onboarding.title": "Opsæt BharatCode", - "session.onboarding.body": - "Log ind i browseren eller indsæt en API-nøgle - begge virker. Kontoen gemmes af udvidelsen, aldrig i indstillingerne.", + "session.onboarding.body": "Godkend adgangen på BharatCodes websted, og vend tilbage til VS Code.", "session.onboarding.hint": "BharatCode er agenten i dette panel. Forbind den én gang og begynd.", "session.workspaceScope.description": "BharatCode-chatten bruger kun “{{folder}}”, den første mappe i dette arbejdsområde.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/de.ts b/packages/kilo-vscode/webview-ui/src/i18n/de.ts index 1bfa683c..c2339843 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/de.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/de.ts @@ -772,10 +772,9 @@ export const dict = { "session.messages.welcome": "BharatCode betreibt in diesem Panel einen Agenten, angetrieben von deinen BharatCode-Modellen. Bitte ihn, Funktionen zu erstellen, Fehler zu beheben oder deine Codebasis zu erklären.", - "session.messages.connect": "BharatCode verbinden", + "session.messages.connect": "Mit BharatCode anmelden", "session.onboarding.title": "BharatCode einrichten", - "session.onboarding.body": - "Melde dich im Browser an oder füge einen API-Schlüssel ein - beides funktioniert. Dein Konto speichert die Erweiterung, nicht die Einstellungen.", + "session.onboarding.body": "Erlaube den Zugriff auf der BharatCode-Website und kehre dann zu VS Code zurück.", "session.onboarding.hint": "BharatCode ist der Agent in diesem Panel. Einmal verbinden, dann direkt loslegen.", "session.workspaceScope.description": "Der BharatCode-Chat verwendet nur „{{folder}}“, den ersten Ordner in diesem Arbeitsbereich.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/en.ts b/packages/kilo-vscode/webview-ui/src/i18n/en.ts index a68a99d7..ea9eae61 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/en.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/en.ts @@ -53,6 +53,22 @@ export const anacondaDesktopDict = { } as const export const dict = { + "bharatcode.catalog.loading": "Loading BharatCode models…", + "bharatcode.catalog.unavailable": "Models unavailable", + "bharatcode.catalog.network": + "Couldn’t reach the model catalog. Check your connection and retry. Your chats and sign-in are unchanged.", + "bharatcode.catalog.http": + "The model catalog returned HTTP {{status}}. Retry in a moment; you don’t need to sign in again.", + "bharatcode.catalog.schema": + "The model catalog returned an unexpected response. Retry; if it continues, share the BharatCode Agent output log.", + "bharatcode.catalog.unauthorized": + "BharatCode could not verify your sign-in. Sign in again; your chats will stay here.", + "bharatcode.catalog.unauthenticated": + "Sign in with BharatCode to load your models. Your existing chats will stay here.", + "bharatcode.catalog.empty": + "BharatCode returned no available models. Retry the catalog; your chats and sign-in are unchanged.", + "bharatcode.catalog.signIn": "Sign in with BharatCode", + "bharatcode.catalog.retry": "Retry model catalog", ...anacondaDesktopDict, ...cloudProviderDict, "task.swarm.title": "Board", @@ -703,10 +719,9 @@ export const dict = { "session.messages.welcome": "BharatCode runs an agent in this panel, powered by your BharatCode models. Ask it to build features, fix bugs, or explain your codebase.", - "session.messages.connect": "Connect BharatCode", + "session.messages.connect": "Sign in with BharatCode", "session.onboarding.title": "Set up BharatCode", - "session.onboarding.body": - "Sign in with your browser or paste an API key - either works. Your account is stored by the extension, never in settings.", + "session.onboarding.body": "Approve access on the BharatCode website, then return to VS Code.", "session.onboarding.hint": "BharatCode is the agent in this panel. Connect it once and start asking.", "session.workspaceScope.description": "BharatCode chat uses only “{{folder}}”, the first folder in this workspace.", "session.workspaceScope.alternatives": diff --git a/packages/kilo-vscode/webview-ui/src/i18n/es.ts b/packages/kilo-vscode/webview-ui/src/i18n/es.ts index e83e7a70..ecc20dde 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/es.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/es.ts @@ -767,10 +767,9 @@ export const dict = { "session.messages.welcome": "BharatCode ejecuta un agente en este panel, impulsado por tus modelos BharatCode. Pídele que cree funciones, corrija errores o explique tu código.", - "session.messages.connect": "Conectar BharatCode", + "session.messages.connect": "Iniciar sesión con BharatCode", "session.onboarding.title": "Configurar BharatCode", - "session.onboarding.body": - "Inicia sesión en el navegador o pega una clave de API: ambos funcionan. La cuenta la guarda la extensión, nunca los ajustes.", + "session.onboarding.body": "Autoriza el acceso en el sitio de BharatCode y vuelve a VS Code.", "session.onboarding.hint": "BharatCode es el agente de este panel. Conéctalo una vez y empieza.", "session.workspaceScope.description": "El chat de BharatCode solo usa «{{folder}}», la primera carpeta de este espacio de trabajo.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/fa.ts b/packages/kilo-vscode/webview-ui/src/i18n/fa.ts index 654539f9..7f63f1c1 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/fa.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/fa.ts @@ -713,10 +713,9 @@ export const dict = { "session.messages.welcome": "BharatCode یک عامل در این پنل اجرا می‌کند که با مدل‌های BharatCode شما کار می‌کند. از آن بخواهید قابلیت بسازد، باگ رفع کند یا کد شما را توضیح دهد.", - "session.messages.connect": "اتصال به BharatCode", + "session.messages.connect": "ورود با BharatCode", "session.onboarding.title": "راه‌اندازی BharatCode", - "session.onboarding.body": - "از طریق مرورگر وارد شوید یا کلید API را بچسبانید — هر دو کار می‌کند. حساب توسط افزونه ذخیره می‌شود، نه در تنظیمات.", + "session.onboarding.body": "دسترسی را در وب‌سایت BharatCode تأیید کنید و به VS Code برگردید.", "session.onboarding.hint": "BharatCode همان عاملِ این پنل است. یک بار وصلش کنید و شروع کنید.", "session.workspaceScope.description": "گفتگوی BharatCode فقط از «{{folder}}»، اولین پوشه در این فضای کاری، استفاده می‌کند.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/fr.ts b/packages/kilo-vscode/webview-ui/src/i18n/fr.ts index cde3fc6c..e1c1aa95 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/fr.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/fr.ts @@ -773,10 +773,9 @@ export const dict = { "session.messages.welcome": "BharatCode fait tourner un agent dans ce panneau, propulsé par vos modèles BharatCode. Demandez-lui de créer des fonctionnalités, corriger des bugs ou expliquer votre base de code.", - "session.messages.connect": "Connecter BharatCode", + "session.messages.connect": "Se connecter avec BharatCode", "session.onboarding.title": "Configurer BharatCode", - "session.onboarding.body": - "Connectez-vous dans le navigateur ou collez une clé API : les deux fonctionnent. Le compte est stocké par l'extension, jamais dans les paramètres.", + "session.onboarding.body": "Autorisez l’accès sur le site de BharatCode, puis revenez dans VS Code.", "session.onboarding.hint": "BharatCode est l’agent de ce panneau. Connectez-le une fois et commencez.", "session.workspaceScope.description": "Le chat BharatCode utilise uniquement « {{folder}} », le premier dossier de cet espace de travail.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/it.ts b/packages/kilo-vscode/webview-ui/src/i18n/it.ts index 7e1e9b49..fae92312 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/it.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/it.ts @@ -618,10 +618,9 @@ export const dict = { "settings.aboutKiloCode.title": "Informazioni su BharatCode", "session.messages.welcome": "BharatCode esegue un agente in questo pannello, basato sui tuoi modelli BharatCode. Chiedigli di creare funzionalità, correggere bug o spiegare la tua codebase.", - "session.messages.connect": "Connetti BharatCode", + "session.messages.connect": "Accedi con BharatCode", "session.onboarding.title": "Configura BharatCode", - "session.onboarding.body": - "Accedi dal browser o incolla una chiave API: vanno bene entrambi. L'account è salvato dall'estensione, mai nelle impostazioni.", + "session.onboarding.body": "Autorizza l’accesso sul sito di BharatCode, poi torna a VS Code.", "session.onboarding.hint": "BharatCode è l’agente di questo pannello. Collegalo una volta e inizia.", "session.workspaceScope.description": "La chat di BharatCode usa solo «{{folder}}», la prima cartella di questo workspace.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/ja.ts b/packages/kilo-vscode/webview-ui/src/i18n/ja.ts index ab9db148..1c85f30a 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/ja.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/ja.ts @@ -755,10 +755,9 @@ export const dict = { "session.messages.welcome": "BharatCode はこのパネルで、あなたの BharatCode モデルを使ったエージェントを実行します。機能の実装、バグ修正、コードベースの説明を依頼できます。", - "session.messages.connect": "BharatCode に接続", + "session.messages.connect": "BharatCode でサインイン", "session.onboarding.title": "BharatCode をセットアップ", - "session.onboarding.body": - "ブラウザでサインインするか API キーを貼り付けてください。どちらでも使えます。アカウントは拡張機能が保存し、設定には保存しません。", + "session.onboarding.body": "BharatCode のウェブサイトでアクセスを許可し、VS Code に戻ってください。", "session.onboarding.hint": "BharatCode はこのパネルのエージェントです。一度接続すればすぐに使えます。", "session.workspaceScope.description": "BharatCode チャットは、このワークスペースの最初のフォルダー「{{folder}}」のみを使用します。", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/ko.ts b/packages/kilo-vscode/webview-ui/src/i18n/ko.ts index 65171d53..a6d52d03 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/ko.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/ko.ts @@ -753,10 +753,9 @@ export const dict = { "session.messages.welcome": "BharatCode는 이 패널에서 귀하의 BharatCode 모델로 에이전트를 실행합니다. 기능 구현, 버그 수정, 코드베이스 설명을 요청하세요.", - "session.messages.connect": "BharatCode 연결", + "session.messages.connect": "BharatCode로 로그인", "session.onboarding.title": "BharatCode 설정", - "session.onboarding.body": - "브라우저에서 로그인하거나 API 키를 붙여넣으세요. 둘 다 가능합니다. 계정은 확장 프로그램이 저장하며 설정에는 저장되지 않습니다.", + "session.onboarding.body": "BharatCode 웹사이트에서 접근을 허용한 다음 VS Code로 돌아오세요.", "session.onboarding.hint": "BharatCode는 이 패널의 에이전트입니다. 한 번 연결하고 시작하세요.", "session.workspaceScope.description": "BharatCode 채팅은 이 작업 영역의 첫 번째 폴더인 “{{folder}}”만 사용합니다.", "session.workspaceScope.alternatives": diff --git a/packages/kilo-vscode/webview-ui/src/i18n/nl.ts b/packages/kilo-vscode/webview-ui/src/i18n/nl.ts index 4f2d0857..5d631d87 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/nl.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/nl.ts @@ -750,10 +750,9 @@ export const dict = { "session.messages.welcome": "BharatCode laat een agent in dit paneel draaien, aangedreven door je BharatCode-modellen. Vraag het om features te bouwen, bugs op te lossen of je codebase uit te leggen.", - "session.messages.connect": "BharatCode verbinden", + "session.messages.connect": "Aanmelden met BharatCode", "session.onboarding.title": "BharatCode instellen", - "session.onboarding.body": - "Log in via je browser of plak een API-sleutel - beide werken. Je account wordt door de extensie opgeslagen, nooit in instellingen.", + "session.onboarding.body": "Geef toestemming op de website van BharatCode en ga terug naar VS Code.", "session.onboarding.hint": "BharatCode is de agent in dit paneel. Verbind het een keer en begin.", "session.workspaceScope.description": "De BharatCode-chat gebruikt alleen ‘{{folder}}’, de eerste map in deze werkruimte.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/no.ts b/packages/kilo-vscode/webview-ui/src/i18n/no.ts index e2bbbbf5..f026778d 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/no.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/no.ts @@ -720,10 +720,9 @@ export const dict = { "session.messages.welcome": "BharatCode kjører en agent i dette panelet på dine BharatCode-modeller. Be den bygge funksjoner, rette feil eller forklare kodebasen din.", - "session.messages.connect": "Koble til BharatCode", + "session.messages.connect": "Logg inn med BharatCode", "session.onboarding.title": "Sett opp BharatCode", - "session.onboarding.body": - "Logg inn i nettleseren eller lim inn en API-nøkkel - begge fungerer. Kontoen lagres av utvidelsen, aldri i innstillingene.", + "session.onboarding.body": "Godkjenn tilgangen på BharatCode-nettstedet, og gå tilbake til VS Code.", "session.onboarding.hint": "BharatCode er agenten i dette panelet. Koble til én gang og begynn.", "session.workspaceScope.description": "BharatCode-chatten bruker bare «{{folder}}», den første mappen i dette arbeidsområdet.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/pl.ts b/packages/kilo-vscode/webview-ui/src/i18n/pl.ts index ff9a9c1f..f033105a 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/pl.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/pl.ts @@ -718,10 +718,9 @@ export const dict = { "session.messages.welcome": "BharatCode uruchamia agenta w tym panelu, opartego na Twoich modelach BharatCode. Poproś go o tworzenie funkcji, naprawę błędów lub wyjaśnienie bazy kodu.", - "session.messages.connect": "Połącz z BharatCode", + "session.messages.connect": "Zaloguj się przez BharatCode", "session.onboarding.title": "Skonfiguruj BharatCode", - "session.onboarding.body": - "Zaloguj się w przeglądarce lub wklej klucz API — obie opcje działają. Konto przechowuje rozszerzenie, nigdy ustawienia.", + "session.onboarding.body": "Zezwól na dostęp na stronie BharatCode, a następnie wróć do VS Code.", "session.onboarding.hint": "BharatCode to agent w tym panelu. Połącz go raz i zaczynaj.", "session.workspaceScope.description": "Czat BharatCode używa tylko „{{folder}}”, pierwszego folderu w tym obszarze roboczym.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/ru.ts b/packages/kilo-vscode/webview-ui/src/i18n/ru.ts index 21afe48e..275907b2 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/ru.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/ru.ts @@ -758,10 +758,9 @@ export const dict = { "session.messages.welcome": "BharatCode запускает агента в этой панели на ваших моделях BharatCode. Попросите его создать функцию, исправить ошибку или объяснить кодовую базу.", - "session.messages.connect": "Подключить BharatCode", + "session.messages.connect": "Войти через BharatCode", "session.onboarding.title": "Настроить BharatCode", - "session.onboarding.body": - "Войдите через браузер или вставьте API-ключ — подойдёт любой способ. Аккаунт хранит расширение, а не настройки.", + "session.onboarding.body": "Разрешите доступ на сайте BharatCode, затем вернитесь в VS Code.", "session.onboarding.hint": "BharatCode — это агент в этой панели. Подключите один раз и начинайте.", "session.workspaceScope.description": "Чат BharatCode использует только «{{folder}}» — первую папку в этой рабочей области.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/th.ts b/packages/kilo-vscode/webview-ui/src/i18n/th.ts index 8465a8cf..4794799e 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/th.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/th.ts @@ -752,10 +752,9 @@ export const dict = { "session.messages.welcome": "BharatCode รันเอเยนต์ในแผงนี้ด้วยโมเดล BharatCode ของคุณ สั่งให้สร้างฟีเจอร์ แก้บั๊ก หรืออธิบายโค้ดเบสของคุณได้เลย", - "session.messages.connect": "เชื่อมต่อ BharatCode", + "session.messages.connect": "ลงชื่อเข้าใช้ด้วย BharatCode", "session.onboarding.title": "ตั้งค่า BharatCode", - "session.onboarding.body": - "ลงชื่อเข้าใช้ผ่านเบราว์เซอร์หรือวางคีย์ API ก็ได้ทั้งคู่ บัญช���ถูกเก็บโดยส่วนขยาย ไม่ได้เก็บในตั้งค่า", + "session.onboarding.body": "อนุญาตการเข้าถึงบนเว็บไซต์ BharatCode แล้วกลับไปที่ VS Code", "session.onboarding.hint": "BharatCode คือเอเยนต์ในแผงนี้ เชื่อมต่อครั้งเดียวแล้วเริ่มได้เลย", "session.workspaceScope.description": "แชต BharatCode ใช้เฉพาะ “{{folder}}” ซึ่งเป็นโฟลเดอร์แรกในพื้นที่ทำงานนี้", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/tr.ts b/packages/kilo-vscode/webview-ui/src/i18n/tr.ts index 03249e79..5d5a8fc1 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/tr.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/tr.ts @@ -748,10 +748,9 @@ export const dict = { "session.messages.welcome": "BharatCode bu panelde BharatCode modellerinizle bir ajan çalıştırır. Özellik geliştirmesini, hata düzeltmesini veya kod tabanınızı açıklamasını isteyin.", - "session.messages.connect": "BharatCode'a bağlan", + "session.messages.connect": "BharatCode ile giriş yap", "session.onboarding.title": "BharatCode kurulumu", - "session.onboarding.body": - "Tarayıcıdan giriş yapın veya bir API anahtarı yapıştırın - ikisi de olur. Hesap ayarlarda değil, uzantıda saklanır.", + "session.onboarding.body": "BharatCode sitesinde erişimi onaylayıp VS Code’a dönün.", "session.onboarding.hint": "BharatCode bu paneldeki ajandır. Bir kez bağlanın ve başlayın.", "session.workspaceScope.description": "BharatCode sohbeti yalnızca bu çalışma alanındaki ilk klasör olan “{{folder}}” klasörünü kullanır.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/uk.ts b/packages/kilo-vscode/webview-ui/src/i18n/uk.ts index 32ca7d12..b06e9e3d 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/uk.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/uk.ts @@ -748,10 +748,9 @@ export const dict = { "session.messages.welcome": "BharatCode запускає агента у цій панелі на ваших моделях BharatCode. Попросіть його створити функцію, виправити помилку або пояснити кодову базу.", - "session.messages.connect": "Підключити BharatCode", + "session.messages.connect": "Увійти через BharatCode", "session.onboarding.title": "Налаштувати BharatCode", - "session.onboarding.body": - "Увійдіть через браузер або вставте API-ключ — підійде будь-який спосіб. Акаунт зберігає розширення, а не налаштування.", + "session.onboarding.body": "Дозвольте доступ на сайті BharatCode, а потім поверніться до VS Code.", "session.onboarding.hint": "BharatCode — це агент у цій панелі. Підключіть один раз і починайте.", "session.workspaceScope.description": "Чат BharatCode використовує лише «{{folder}}» — першу папку в цьому робочому просторі.", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/zh.ts b/packages/kilo-vscode/webview-ui/src/i18n/zh.ts index 57b46db5..2f620fa6 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/zh.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/zh.ts @@ -734,9 +734,9 @@ export const dict = { "session.messages.welcome": "BharatCode 在此面板中运行一个由你的 BharatCode 模型驱动的智能体。让它构建功能、修复 bug 或解释你的代码库。", - "session.messages.connect": "连接 BharatCode", + "session.messages.connect": "使用 BharatCode 登录", "session.onboarding.title": "设置 BharatCode", - "session.onboarding.body": "在浏览器中登录或粘贴 API 密钥,两种方式都可用。账户由扩展保存,不会写入设置。", + "session.onboarding.body": "在 BharatCode 网站上授权,然后返回 VS Code。", "session.onboarding.hint": "BharatCode 就是此面板中的智能体。连接一次即可开始。", "session.workspaceScope.description": "BharatCode 聊天仅使用此工作区中的第一个文件夹“{{folder}}”。", diff --git a/packages/kilo-vscode/webview-ui/src/i18n/zht.ts b/packages/kilo-vscode/webview-ui/src/i18n/zht.ts index 438264b3..9b4131ad 100644 --- a/packages/kilo-vscode/webview-ui/src/i18n/zht.ts +++ b/packages/kilo-vscode/webview-ui/src/i18n/zht.ts @@ -694,9 +694,9 @@ export const dict = { "session.messages.welcome": "BharatCode 在此面板中執行一個由你的 BharatCode 模型驅動的智慧代理。讓它建構功能、修復 bug 或解釋你的程式碼庫。", - "session.messages.connect": "連接 BharatCode", + "session.messages.connect": "使用 BharatCode 登入", "session.onboarding.title": "設定 BharatCode", - "session.onboarding.body": "在瀏覽器登入或貼上 API 金鑰,兩種方式皆可。帳戶由擴充功能保存,不會寫入設定。", + "session.onboarding.body": "在 BharatCode 網站上授權,然後返回 VS Code。", "session.onboarding.hint": "BharatCode 就是此面板中的智慧代理。連接一次即可開始。", "session.workspaceScope.description": "BharatCode 聊天僅使用此工作區中的第一個資料夾「{{folder}}」。", diff --git a/packages/kilo-vscode/webview-ui/src/stories/StoryProviders.tsx b/packages/kilo-vscode/webview-ui/src/stories/StoryProviders.tsx index e5a33882..bdc19a3c 100644 --- a/packages/kilo-vscode/webview-ui/src/stories/StoryProviders.tsx +++ b/packages/kilo-vscode/webview-ui/src/stories/StoryProviders.tsx @@ -112,6 +112,7 @@ const MockProviderProvider: ParentComponent<{ kiloAuth?: boolean; training?: boo defaults: () => ({}), organizationId: () => null, ready: () => true, + catalogReady: () => true, defaultSelection: () => ({ providerID: "kilo", modelID: "anthropic/claude-sonnet-4-6" }), models, findModel: (sel: any) => _findModel(models(), sel), diff --git a/packages/kilo-vscode/webview-ui/src/stories/shared.stories.tsx b/packages/kilo-vscode/webview-ui/src/stories/shared.stories.tsx index 9f13b164..6067a531 100644 --- a/packages/kilo-vscode/webview-ui/src/stories/shared.stories.tsx +++ b/packages/kilo-vscode/webview-ui/src/stories/shared.stories.tsx @@ -8,7 +8,7 @@ import type { Meta, StoryObj } from "storybook-solidjs-vite" import { StoryProviders, mockSessionValue } from "./StoryProviders" import { ModelSelectorBase } from "../components/shared/ModelSelector" import { SessionContext } from "../context/session" -import type { EnrichedModel } from "../context/provider" +import { ProviderProvider, type EnrichedModel } from "../context/provider" import type { ModelSelection } from "../types/messages" import { Markdown } from "@kilocode/kilo-ui/markdown" @@ -59,6 +59,17 @@ export const ModelSelectorNoProviders: Story = { ), } +export const ModelSelectorBharatcodeRecovery: Story = { + name: "ModelSelector — BharatCode catalog recovery", + render: () => ( + + + {}} placement="bottom-start" collapsed /> + + + ), +} + const ACCESSIBLE_MODELS: EnrichedModel[] = [ { id: "kilo-auto/efficient", diff --git a/packages/kilo-vscode/webview-ui/src/styles/model-selector.css b/packages/kilo-vscode/webview-ui/src/styles/model-selector.css index 9d1f31ad..0be5fd2e 100644 --- a/packages/kilo-vscode/webview-ui/src/styles/model-selector.css +++ b/packages/kilo-vscode/webview-ui/src/styles/model-selector.css @@ -348,6 +348,17 @@ text-align: center; } +.model-selector-notice { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 8px; + padding: 12px 16px; + color: var(--text-base, var(--vscode-foreground)); + font-size: var(--kilo-font-size-12); + line-height: 1.5; +} + .model-selector-group-label { display: flex; align-items: center; diff --git a/packages/kilo-vscode/webview-ui/src/types/messages/extension-messages.ts b/packages/kilo-vscode/webview-ui/src/types/messages/extension-messages.ts index 47304b28..41cec1c9 100644 --- a/packages/kilo-vscode/webview-ui/src/types/messages/extension-messages.ts +++ b/packages/kilo-vscode/webview-ui/src/types/messages/extension-messages.ts @@ -1844,6 +1844,8 @@ export type ExtensionMessage = | SpeechToTextModelsLoadedMessage | ProvidersLoadedMessage | { type: "providersLoading" } + | { type: "providersRefreshing" } + | { type: "providersLoadFailed"; failure: ProviderFailure } | AgentsLoadedMessage | SkillsLoadedMessage | CommandsLoadedMessage diff --git a/packages/kilo-vscode/webview-ui/src/types/messages/webview-messages.ts b/packages/kilo-vscode/webview-ui/src/types/messages/webview-messages.ts index ef25ca5a..83b9bd87 100644 --- a/packages/kilo-vscode/webview-ui/src/types/messages/webview-messages.ts +++ b/packages/kilo-vscode/webview-ui/src/types/messages/webview-messages.ts @@ -245,6 +245,8 @@ export interface SelectSourceRequest { export interface RequestProvidersMessage { type: "requestProviders" + /** Retry only the catalog; never reset a running backend session. */ + refresh?: boolean } export interface CompactRequest { @@ -289,7 +291,7 @@ export interface OpenProfilePanelRequest { type: "openProfilePanel" } -/** Opens the BharatCode connect picker (OAuth or API key) from the chat welcome screen. */ +/** Starts website sign-in from the welcome screen or provider settings. */ export interface ConnectBharatcodeRequest { type: "connectBharatcode" } diff --git a/packages/opencode/README.md b/packages/opencode/README.md index 8544a685..3dc5ddd4 100644 --- a/packages/opencode/README.md +++ b/packages/opencode/README.md @@ -1,6 +1,6 @@ # BharatCode Agent Runtime (`packages/opencode/`) -The agent runtime and CLI behind BharatCode: agent loop, tool execution, session management, and an HTTP + SSE server. It is the core engine of the [BharatCode VS Code extension](https://github.com/thenabbu/BharatCode-VSCode-Extension), which bundles the built binary and spawns it as a local backend. +The agent runtime and CLI behind BharatCode: agent loop, tool execution, session management, and an HTTP + SSE server. It is the core engine of the [BharatCode VS Code extension](https://github.com/BharatCode-ai/bharatcode-vscode), which bundles the built binary and spawns it as a local backend. ## Lineage @@ -8,7 +8,7 @@ This package is a fork of the [Kilo Code CLI](https://github.com/Kilo-Org/kiloco ## Publishing -This fork does not publish to npm or any registry. The built binary ships inside the platform `.vsix` files on the [Releases page](https://github.com/thenabbu/BharatCode-VSCode-Extension/releases); install the extension from there. +This fork does not publish to npm or any registry. The built binary ships inside the platform `.vsix` files on the [Releases page](https://github.com/BharatCode-ai/bharatcode-vscode/releases); install the extension from there. ## Development diff --git a/packages/opencode/src/auth/index.ts b/packages/opencode/src/auth/index.ts index cb0ddd26..4decc458 100644 --- a/packages/opencode/src/auth/index.ts +++ b/packages/opencode/src/auth/index.ts @@ -6,7 +6,7 @@ import { Global } from "@opencode-ai/core/global" import { FSUtil } from "@opencode-ai/core/fs-util" import { Telemetry } from "@kilocode/kilo-telemetry" // kilocode_change -export const OAUTH_DUMMY_KEY = "kilo-oauth-dummy-key" // kilocode_change +export { OAUTH_DUMMY_KEY } from "./placeholder" // kilocode_change const file = path.join(Global.Path.data, "auth.json") diff --git a/packages/opencode/src/auth/placeholder.ts b/packages/opencode/src/auth/placeholder.ts new file mode 100644 index 00000000..8bcf1308 --- /dev/null +++ b/packages/opencode/src/auth/placeholder.ts @@ -0,0 +1,3 @@ +// kilocode_change - new file +// Non-secret placeholder required by the SDK when fetch supplies the real OAuth bearer. +export const OAUTH_DUMMY_KEY = "kilo-oauth-dummy-key" diff --git a/packages/opencode/src/kilocode/provider/bharatcode-catalog-http.ts b/packages/opencode/src/kilocode/provider/bharatcode-catalog-http.ts new file mode 100644 index 00000000..e51a1a7c --- /dev/null +++ b/packages/opencode/src/kilocode/provider/bharatcode-catalog-http.ts @@ -0,0 +1,70 @@ +import { Effect, Schema } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" +import * as Catalog from "./bharatcode-catalog" + +const modality = Schema.Literals(["text", "audio", "image", "video", "pdf"]) +const item = Schema.Struct({ + id: Schema.String, + owned_by: Schema.optional(Schema.String), + display_name: Schema.optional(Schema.String), + context_window: Schema.optional(Schema.Number), + max_output_tokens: Schema.optional(Schema.Number), + metadata: Schema.optional( + Schema.Struct({ + reasoning: Schema.optional(Schema.Boolean), + toolCalling: Schema.optional(Schema.Boolean), + input: Schema.optional(Schema.Array(modality)), + output: Schema.optional(Schema.Array(modality)), + }), + ), +}) +const response = Schema.Struct({ data: Schema.Array(item) }) + +export function fetch(http: HttpClient.HttpClient, options: Catalog.Options): Effect.Effect { + return Effect.gen(function* () { + const url = `${(options.baseURL ?? Catalog.baseURL).replace(/\/+$/, "")}/models` + const res = yield* HttpClientRequest.get(url).pipe( + HttpClientRequest.acceptJson, + options.apiKey ? HttpClientRequest.bearerToken(options.apiKey) : (request) => request, + http.execute, + ) + if (res.status < 200 || res.status >= 300) + return { models: {}, error: Catalog.failure(res.status, res.headers["retry-after"]) } + + return yield* HttpClientResponse.schemaBodyJson(response)(res).pipe( + Effect.map((json): Catalog.Result => { + if (json.data.some((model) => !model.id.trim())) return { models: {}, error: { kind: "schema" } } + if (json.data.length === 0) return { models: {}, error: { kind: "schema" }, empty: true } + return { + models: Object.fromEntries( + json.data.map((model) => [ + model.id, + { + id: model.id, + name: model.display_name ?? model.id, + family: model.owned_by ?? "", + release_date: "", + attachment: true, + reasoning: model.metadata?.reasoning ?? false, + temperature: true, + tool_call: model.metadata?.toolCalling ?? true, + cost: { input: 0, output: 0 }, + limit: { context: model.context_window ?? 128000, output: model.max_output_tokens ?? 4096 }, + modalities: { + input: model.metadata?.input ?? ["text", "image"], + output: model.metadata?.output ?? ["text"], + }, + }, + ]), + ), + } + }), + Effect.catch(() => Effect.succeed({ models: {}, error: { kind: "schema" } })), + ) + }).pipe( + // Bound the whole request, including a response body that never finishes. + Effect.timeout("10 seconds"), + // Transport errors can contain URLs, headers and credentials. Never retain or log them. + Effect.catch(() => Effect.succeed({ models: {}, error: { kind: "network" } })), + ) +} diff --git a/packages/opencode/src/kilocode/provider/bharatcode-catalog.ts b/packages/opencode/src/kilocode/provider/bharatcode-catalog.ts new file mode 100644 index 00000000..3e003cd4 --- /dev/null +++ b/packages/opencode/src/kilocode/provider/bharatcode-catalog.ts @@ -0,0 +1,53 @@ +import { createHash } from "node:crypto" +import type { KiloModelsResult } from "@kilocode/kilo-gateway" +import type { Provider } from "@opencode-ai/core/models-dev" + +export const baseURL = "https://bharatcode.ai/api/model/v1" +export type Options = { baseURL?: string; apiKey?: string; catalogAccount?: string } +export type Result = { + readonly models: Provider["models"] + readonly error?: NonNullable + // An empty, otherwise valid catalog is recoverable, unlike an invalid schema. + readonly empty?: boolean +} + +export function key(options: Options) { + return createHash("sha256") + .update(JSON.stringify([(options.baseURL ?? baseURL).replace(/\/+$/, ""), options.apiKey, options.catalogAccount])) + .digest("hex") +} + +export function failure(status: number, header?: string, now = Date.now()): NonNullable { + const value = header?.trim() + const seconds = !value + ? NaN + : /^\d+$/.test(value) + ? Math.min(Number(value), Number.MAX_SAFE_INTEGER) + : (Date.parse(value) - now) / 1000 + const retryAfter = Number.isFinite(seconds) ? Math.max(0, seconds) : undefined + return { + kind: status === 401 || status === 403 ? "unauthorized" : "http", + status, + ...(retryAfter == null ? {} : { retryAfter }), + } +} + +export function retryable(result: Result) { + if (result.empty || result.error?.kind === "network") return true + const status = result.error?.status ?? 0 + return result.error?.kind === "http" && (status === 408 || status === 429 || (status >= 500 && status < 600)) +} + +// Five automatic retries per recovery cycle. Explicit refresh starts a new cycle; +// polling a failed cache does not. Retry-After is a minimum, never capped by backoff. +export function delay(result: Result, attempt: number) { + if (!retryable(result) || attempt >= 5) return undefined + const seconds = Math.max(2 ** attempt, result.error?.retryAfter ?? 0) + // Do not overflow a platform timer into an immediate retry. An impractically + // long Retry-After leaves the catalog in cooldown until a later caller/clear. + return seconds * 1000 > 2_147_483_647 ? undefined : seconds +} + +export function retain(result: Result, models?: Provider["models"]): Result { + return models && retryable(result) ? { ...result, models } : result +} diff --git a/packages/opencode/src/kilocode/provider/catalog-refresh.ts b/packages/opencode/src/kilocode/provider/catalog-refresh.ts new file mode 100644 index 00000000..16bc634e --- /dev/null +++ b/packages/opencode/src/kilocode/provider/catalog-refresh.ts @@ -0,0 +1,26 @@ +import { Effect } from "effect" +import * as ModelsRefresh from "@opencode-ai/core/kilocode/models-refresh" +import type { Config } from "@/config/config" +import type { ModelCache } from "@/provider/model-cache" + +export const refresh = Effect.fn("Catalog.refresh")(function* ( + cache: ModelCache.Interface, + config: Config.Info, + providerID: string, +) { + // This endpoint deliberately does not refresh the global models.dev catalog, + // dispose instances, or invoke provider login/plugin loaders. + if (providerID !== "bharatcode") return false + if (config.disabled_providers?.includes(providerID)) return false + if (config.enabled_providers && !config.enabled_providers.includes(providerID)) return false + return yield* cache.refresh(providerID).pipe( + Effect.flatMap((models) => + cache.getFailure(providerID).pipe(Effect.map((error) => !error && Object.keys(models).length > 0)), + ), + // Also cover an explicit refresh of a newly selected/warm account. Only + // model-provider caches watch this signal; session/tool scopes stay alive. + Effect.tap((success) => (success ? ModelsRefresh.notify() : Effect.void)), + Effect.timeout("15 seconds"), + Effect.catch(() => Effect.succeed(false)), + ) +}) diff --git a/packages/opencode/src/plugin/bharatcode.ts b/packages/opencode/src/plugin/bharatcode.ts index 09392ad6..ccb3c49a 100644 --- a/packages/opencode/src/plugin/bharatcode.ts +++ b/packages/opencode/src/plugin/bharatcode.ts @@ -1,7 +1,7 @@ // kilocode_change - new file import type { Hooks, PluginInput } from "@kilocode/plugin" import type { Auth } from "@kilocode/sdk/v2" -import { OAUTH_DUMMY_KEY } from "../auth" +import { OAUTH_DUMMY_KEY } from "../auth/placeholder" import { createServer } from "http" // GoTrue-compatible OAuth 2.0, authorization code + PKCE (S256) — the same @@ -31,6 +31,7 @@ export interface BharatcodeAuthPluginOptions { issuer?: string clientId?: string redirectUri?: string + modelFetch?: (input: RequestInfo | URL, init: RequestInit) => Promise } type OauthAuth = Extract @@ -87,6 +88,7 @@ export function buildAuthorizeUrl(pkce: PkceCodes, state: string, options: Bhara async function postToken(params: Record, options: BharatcodeAuthPluginOptions): Promise { const response = await fetch(`${issuerUrl(options)}/oauth/token`, { method: "POST", + redirect: "error", headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, body: new URLSearchParams(params), }) @@ -105,6 +107,7 @@ async function fetchAccountId(access: string, options: BharatcodeAuthPluginOptio try { const response = await fetch(`${issuerUrl(options)}/oauth/userinfo`, { headers: { [AUTH_HEADER]: bearer(access) }, + redirect: "error", }) if (!response.ok) return undefined const body = await response.json().catch(() => ({}) as { sub?: unknown }) @@ -209,6 +212,7 @@ function waitForCallback(state: string, timeoutMs = CALLBACK_TIMEOUT_MS): Promis return new Promise((resolvePromise, rejectPromise) => { const timer = setTimeout(() => { pendingCallbacks.delete(state) + if (!pendingCallbacks.size) stopOAuthServer() rejectPromise(new Error("BharatCode sign-in timed out. Start sign-in again.")) }, timeoutMs) pendingCallbacks.set(state, { resolve: resolvePromise, reject: rejectPromise, timer }) @@ -231,42 +235,46 @@ export async function BharatcodeAuthPlugin( // Single-flight refresh: concurrent requests share one HTTP call so a // rotating refresh_token is never replayed twice. - let refreshPromise: Promise | undefined + const refreshing = new Map>() const refreshAccess = (current: OauthAuth): Promise => { - if (!refreshPromise) { - const refreshToken = current.refresh - refreshPromise = postToken( - { grant_type: "refresh_token", refresh_token: refreshToken, client_id: clientId }, - options, - ) - .then(async (tokens): Promise => { - const next: Refreshed = { - access: tokens.access_token, - refresh: tokens.refresh_token || refreshToken, - expires: Date.now() + (tokens.expires_in ?? 3600) * 1000, - } - // Best-effort persist: the in-memory result still serves this - // request; a stale copy on disk just forces the next refresh. - await input.client.auth - .set({ - path: { id: "bharatcode" }, - body: { - type: "oauth", - access: next.access, - refresh: next.refresh, - expires: next.expires, - ...(current.accountId ? { accountId: current.accountId } : {}), - }, - }) - .catch(() => {}) - return next - }) - .finally(() => { - refreshPromise = undefined - }) - } - return refreshPromise + const refreshToken = current.refresh + const existing = refreshing.get(refreshToken) + if (existing) return existing + const pending = postToken( + { grant_type: "refresh_token", refresh_token: refreshToken, client_id: clientId }, + options, + ) + .then(async (tokens): Promise => { + const next: Refreshed = { + access: tokens.access_token, + refresh: tokens.refresh_token || refreshToken, + expires: Date.now() + (tokens.expires_in ?? 3600) * 1000, + } + const stored = await getAuth() + if (stored.type !== "oauth" || stored.refresh !== refreshToken) + throw new Error("BharatCode session changed") + // Best-effort persist: the in-memory result still serves this + // request; a stale copy on disk just forces the next refresh. + await input.client.auth + .set({ + path: { id: "bharatcode" }, + body: { + type: "oauth", + access: next.access, + refresh: next.refresh, + expires: next.expires, + ...(current.accountId ? { accountId: current.accountId } : {}), + }, + }) + .catch(() => {}) + return next + }) + .finally(() => { + refreshing.delete(refreshToken) + }) + refreshing.set(refreshToken, pending) + return pending } const tokenFor = async (current: OauthAuth, force: boolean): Promise => { @@ -285,6 +293,15 @@ export async function BharatcodeAuthPlugin( // request through so the store's own key reaches the API intact. if (current.type !== "oauth") return fetch(requestInput, init) + const destination = new URL(requestInput instanceof Request ? requestInput.url : requestInput.toString()) + if ( + destination.origin !== "https://bharatcode.ai" || + !destination.pathname.startsWith("/api/model/v1/") || + destination.username || + destination.password + ) + throw new Error("Unapproved BharatCode model endpoint") + const send = options.modelFetch ?? fetch const headers = new Headers(requestInput instanceof Request ? requestInput.headers : undefined) if (init?.headers) { const entries = @@ -298,20 +315,23 @@ export async function BharatcodeAuthPlugin( } } headers.set(AUTH_HEADER, bearer(await tokenFor(current, false))) - let response = await fetch(requestInput, { ...init, headers }) + let response = await send(requestInput, { ...init, headers, redirect: "error" }) // A revoked-but-unexpired token still 401s: force one refresh and // replay — only when the body can be re-sent as-is. const replayable = - init?.body === undefined || typeof init.body === "string" || init.body instanceof URLSearchParams + !(requestInput instanceof Request && requestInput.body && init?.body === undefined) && + (init?.body === undefined || typeof init.body === "string" || init.body instanceof URLSearchParams) if (response.status === 401 && replayable) { - try { - await response.body?.cancel() - } catch {} + const previous = current current = await getAuth() - if (current.type === "oauth") { + if ( + current.type === "oauth" && + (previous.accountId ? previous.accountId === current.accountId : previous.refresh === current.refresh) + ) { + await response.body?.cancel().catch(() => {}) headers.set(AUTH_HEADER, bearer(await tokenFor(current, true))) - response = await fetch(requestInput, { ...init, headers }) + response = await send(requestInput, { ...init, headers, redirect: "error" }) } } return response @@ -333,7 +353,7 @@ export async function BharatcodeAuthPlugin( void callbackPromise.catch(() => {}) return { url, - instructions: "Complete sign-in in your browser. This window will close automatically.", + instructions: "Approve access on the BharatCode website, then return to VS Code.", method: "auto" as const, callback: async () => { try { @@ -360,16 +380,12 @@ export async function BharatcodeAuthPlugin( } catch { return { type: "failed" as const } } finally { - stopOAuthServer() + if (!pendingCallbacks.size) stopOAuthServer() } }, } }, }, - { - type: "api", - label: "Use an API key", - }, ], }, } diff --git a/packages/opencode/src/provider/model-cache.ts b/packages/opencode/src/provider/model-cache.ts index d1358003..8f45b50c 100644 --- a/packages/opencode/src/provider/model-cache.ts +++ b/packages/opencode/src/provider/model-cache.ts @@ -1,11 +1,13 @@ // kilocode_change - new file import { fetchKiloModels, type KiloModelsResult } from "@kilocode/kilo-gateway" -import { Context, Deferred, Duration, Effect, Exit, Fiber, Layer, Schema, Scope } from "effect" +import { Clock, Context, Deferred, Duration, Effect, Exit, Fiber, Layer, Schema, Scope } from "effect" import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" import { Config } from "../config/config" import { Auth } from "../auth" import { compatible, organization, token } from "@/kilocode/provider/catalog" import { delay, retryable } from "@/kilocode/provider/catalog-recovery" +import * as BharatcodeCatalog from "@/kilocode/provider/bharatcode-catalog" +import { fetch as fetchBharatcodeCatalog } from "@/kilocode/provider/bharatcode-catalog-http" import * as ModelsRefresh from "@opencode-ai/core/kilocode/models-refresh" import type { Provider } from "@opencode-ai/core/models-dev" import * as Log from "@opencode-ai/core/util/log" @@ -16,9 +18,9 @@ import { httpClient } from "@opencode-ai/core/effect/app-node-platform" // kiloc type Models = Provider["models"] type Modalities = NonNullable type KiloOptions = NonNullable[0]> -type Options = { -readonly [K in keyof KiloOptions]?: KiloOptions[K] } & { apiKey?: string } +type Options = { -readonly [K in keyof KiloOptions]?: KiloOptions[K] } & BharatcodeCatalog.Options type Failure = NonNullable -type Result = { readonly models: Models; readonly error?: Failure } +type Result = BharatcodeCatalog.Result type View = { models?: Models; timestamp?: number; empty?: boolean } type Flight = { readonly done: Deferred.Deferred; version: number } @@ -37,7 +39,10 @@ export const kiloModelsLayer = Layer.succeed( type Cell = { readonly providerID: string readonly options: Options + readonly input: Options readonly view: View + attempts?: number + retryAt?: number cached?: { readonly result: Result; readonly expires: number } flight?: Flight recovery?: Fiber.Fiber @@ -57,7 +62,6 @@ export class Service extends Context.Service()("@kilocode/Mo const log = Log.create({ service: "model-cache" }) const ttl = Duration.minutes(5) const APERTIS_BASE_URL = "https://api.apertis.ai/v1" -const BHARATCODE_BASE_URL = "https://bharatcode.ai/api/model/v1" // OpenAI GET /models item shape. Optional extras are read by BharatCode's richer // response (display_name/context_window/metadata); apertis items without them // fall back to the legacy defaults in aperture(). @@ -125,8 +129,7 @@ export const layer: Layer.Layer< const fetchApertisModels = Effect.fn("ModelCache.fetchApertisModels")(function* (options: Options) { const baseURL = options.baseURL ?? APERTIS_BASE_URL - // bharatcode.ai serves GET /models without auth; apertis requires a key. - const anon = baseURL === BHARATCODE_BASE_URL + const anon = baseURL === BharatcodeCatalog.baseURL if (!options.apiKey && !anon) { log.debug("no API key for apertis, skipping model fetch") return {} @@ -188,6 +191,9 @@ export const layer: Layer.Layer< const info = yield* auth.get(providerID) if (info?.type === "api") options.apiKey = info.key + // The catalog is public. Scope OAuth caches to the account without sending + // its bearer token to an arbitrary configured catalog endpoint. + if (info?.type === "oauth") options.catalogAccount = info.access if (process.env.BHARATCODE_API_KEY) options.apiKey = process.env.BHARATCODE_API_KEY log.debug("bharatcode auth options resolved", { providerID, @@ -201,12 +207,7 @@ export const layer: Layer.Layer< const fetchModels = (providerID: string, options: Options): Effect.Effect => { if (providerID === "kilo") return kilo.fetch(options) - // ponytail: fetchApertisModels is really a generic OpenAI GET /models client - // (Bearer + {data:[...]}); renamed scope would touch apertis tests too. - if (providerID === "bharatcode") - return fetchApertisModels({ ...options, baseURL: options.baseURL ?? BHARATCODE_BASE_URL }).pipe( - Effect.map((models) => ({ models })), - ) + if (providerID === "bharatcode") return fetchBharatcodeCatalog(http, options) if (providerID === "apertis") return fetchApertisModels(options).pipe(Effect.map((models) => ({ models }))) log.debug("provider not implemented", { providerID }) return Effect.succeed({ models: {} }) @@ -218,6 +219,9 @@ export const layer: Layer.Layer< }) const resolve = Effect.fn("ModelCache.resolve")(function* (providerID: string, options: Options) { + // Never silently replace a failed account/config lookup with anonymous + // default-endpoint credentials for BharatCode. + if (providerID === "bharatcode") return { ...(yield* authOptions(providerID)), ...options } const resolved = yield* authOptions(providerID).pipe( Effect.catchCause((cause) => Effect.sync(() => { @@ -234,6 +238,7 @@ export const layer: Layer.Layer< return JSON.stringify([providerID, options?.baseURL, options?.kilocodeOrganizationId, options?.kilocodeToken]) } if (providerID === "apertis") return JSON.stringify([providerID, options?.baseURL, options?.apiKey]) + if (providerID === "bharatcode") return `${providerID}:${BharatcodeCatalog.key(options ?? {})}` return providerID } @@ -243,7 +248,7 @@ export const layer: Layer.Layer< const existing = cells.get(id) if (existing) return existing const view: View = {} - const next: Cell = { providerID, options: input, view } + const next: Cell = { providerID, options: input, input: options, view } cells.set(id, next) return next }) @@ -263,16 +268,31 @@ export const layer: Layer.Layer< ), ) - const commit = (providerID: string, version: number, entry: Cell, result: Result) => + const commit = (providerID: string, version: number | (() => number), entry: Cell, result: Result) => Effect.gen(function* () { - if ((versions.get(providerID) ?? 0) !== version) return result.models + if (providerID === "bharatcode") { + const current = yield* resolve(providerID, entry.input).pipe(Effect.catch(() => Effect.succeed(undefined))) + if (!current || key(providerID, current) !== key(providerID, entry.options)) { + if (active.get(providerID) === entry) active.delete(providerID) + if (selected.get(providerID) === entry) failures.delete(providerID) + return result.models + } + if (selected.get(providerID) !== entry) return result.models + } + if ((versions.get(providerID) ?? 0) !== (typeof version === "function" ? version() : version)) + return result.models const empty = Object.keys(result.models).length === 0 - const recovered = providerID === "kilo" && entry.view.empty && !empty && !result.error + const recovered = + providerID === "bharatcode" + ? (!result.error && !empty && failures.has(providerID)) || + (entry.view.models != null && JSON.stringify(entry.view.models) !== JSON.stringify(result.models)) + : providerID === "kilo" && entry.view.empty && !empty && !result.error if (result.error) { failures.set(providerID, result.error) log.warn("model fetch error", { providerID, error: result.error }) } else { failures.delete(providerID) + if (providerID === "bharatcode") entry.attempts = 0 } entry.view.models = result.models entry.view.timestamp = Date.now() @@ -305,13 +325,26 @@ export const layer: Layer.Layer< entry.flight = flight yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () { - const exit = yield* restore(load(entry.providerID, entry.options)).pipe(Effect.exit) + const exit = yield* restore(load(entry.providerID, entry.options)).pipe( + Effect.map((result) => + entry.providerID === "bharatcode" ? BharatcodeCatalog.retain(result, entry.view.models) : result, + ), + Effect.exit, + ) if (entry.flight === flight) { - entry.flight = undefined + if (entry.providerID !== "bharatcode") entry.flight = undefined if (Exit.isSuccess(exit)) { entry.cached = { result: exit.value, expires: Date.now() + Duration.toMillis(ttl) } - yield* commit(entry.providerID, flight.version, entry, exit.value) + if (entry.providerID === "bharatcode") + entry.retryAt = (yield* Clock.currentTimeMillis) + (exit.value.error?.retryAfter ?? 0) * 1000 + yield* commit( + entry.providerID, + entry.providerID === "bharatcode" ? () => flight.version : flight.version, + entry, + exit.value, + ) } + if (entry.providerID === "bharatcode" && entry.flight === flight) entry.flight = undefined } yield* Deferred.done(done, exit) if (Exit.isSuccess(exit)) yield* recover(entry, exit.value) @@ -329,9 +362,12 @@ export const layer: Layer.Layer< } const age = Date.now() - entry.view.timestamp - if (age > Duration.toMillis(ttl)) { + if ( + age > Duration.toMillis(ttl) && + !(providerID === "bharatcode" && (entry.retryAt ?? 0) > (yield* Clock.currentTimeMillis)) + ) { log.debug("cache expired", { providerID, age }) - entry.view.models = undefined + if (providerID !== "bharatcode") entry.view.models = undefined entry.view.timestamp = undefined yield* invalidate(entry) return @@ -343,6 +379,10 @@ export const layer: Layer.Layer< const fetch = Effect.fn("ModelCache.fetch")(function* (providerID: string, options?: Options) { const entry = yield* cell(providerID, options) + if (providerID === "bharatcode" && selected.get(providerID) !== entry) { + active.delete(providerID) + failures.delete(providerID) + } selected.set(providerID, entry) const cached = active.get(providerID) === entry ? yield* get(providerID) : undefined if (cached) { @@ -353,36 +393,74 @@ export const layer: Layer.Layer< versions.set(providerID, version) log.info("fetching models", { providerID }) const result = yield* evaluate(entry, version) + if (providerID === "bharatcode" && active.get(providerID) !== entry) return {} return result.models }) const refresh = Effect.fn("ModelCache.refresh")(function* (providerID: string, options?: Options) { + const resolved = providerID === "bharatcode" ? yield* cell(providerID, options) : undefined const version = (versions.get(providerID) ?? 0) + 1 versions.set(providerID, version) - const entry = yield* cell(providerID, options) + const entry = resolved ?? (yield* cell(providerID, options)) + if (providerID === "bharatcode" && selected.get(providerID) !== entry) { + active.delete(providerID) + failures.delete(providerID) + } selected.set(providerID, entry) + if (providerID === "bharatcode") { + // Repeated clicks coalesce with the flight, and cannot bypass Retry-After. + if (entry.cached && (entry.retryAt ?? 0) > (yield* Clock.currentTimeMillis)) { + yield* commit(providerID, version, entry, entry.cached.result) + yield* recover(entry, entry.cached.result) + return entry.cached.result.models + } + if (!entry.flight && !entry.recovery) entry.attempts = 0 + } log.info("refreshing models", { providerID }) yield* invalidate(entry) const result = yield* evaluate(entry, version) + if (providerID === "bharatcode" && active.get(providerID) !== entry) return {} return result.models }) const recover = Effect.fn("ModelCache.recover")(function* (entry: Cell, result: Result) { if ( - entry.providerID !== "kilo" || + (entry.providerID !== "kilo" && entry.providerID !== "bharatcode") || selected.get(entry.providerID) !== entry || active.get(entry.providerID) !== entry || entry.recovery || - !retryable(result) + !(entry.providerID === "bharatcode" ? BharatcodeCatalog.retryable(result) : retryable(result)) ) return entry.recovery = yield* Effect.gen(function* () { let next = result for (let attempt = 0; ; attempt++) { - yield* Effect.sleep(Duration.seconds(delay(next, attempt))) + const seconds = + entry.providerID === "bharatcode" + ? BharatcodeCatalog.delay(next, entry.attempts ?? 0) + : delay(next, attempt) + if (seconds === undefined) return + yield* Effect.sleep(Duration.seconds(seconds)) // A newer account or endpoint must not be replaced by this retry. if (selected.get(entry.providerID) !== entry || active.get(entry.providerID) !== entry) return - if (entry.cached && !retryable(entry.cached.result)) return + if (entry.providerID === "bharatcode") { + const current = yield* resolve(entry.providerID, entry.input).pipe( + Effect.catch(() => Effect.succeed(undefined)), + ) + if (!current || key(entry.providerID, current) !== key(entry.providerID, entry.options)) return + if (entry.cached && !BharatcodeCatalog.retryable(entry.cached.result)) return + // A manual request can extend Retry-After while this fiber sleeps. + const remaining = (entry.retryAt ?? 0) - (yield* Clock.currentTimeMillis) + if (remaining > 0) yield* Effect.sleep(Duration.millis(remaining)) + if (selected.get(entry.providerID) !== entry || active.get(entry.providerID) !== entry) return + const latest = yield* resolve(entry.providerID, entry.input).pipe( + Effect.catch(() => Effect.succeed(undefined)), + ) + if (!latest || key(entry.providerID, latest) !== key(entry.providerID, entry.options)) return + if (entry.cached && !BharatcodeCatalog.retryable(entry.cached.result)) return + entry.attempts = (entry.attempts ?? 0) + 1 + } + if (entry.providerID !== "bharatcode" && entry.cached && !retryable(entry.cached.result)) return yield* invalidate(entry) const version = (versions.get(entry.providerID) ?? 0) + 1 versions.set(entry.providerID, version) @@ -391,7 +469,12 @@ export const layer: Layer.Layer< const value = yield* evaluate(entry, version).pipe( Effect.catch((error) => Effect.sync(() => { - log.error("catalog recovery failed", { providerID: entry.providerID, error }) + log.error( + "catalog recovery failed", + entry.providerID === "bharatcode" + ? { providerID: entry.providerID } + : { providerID: entry.providerID, error }, + ) return undefined }), ), @@ -399,7 +482,7 @@ export const layer: Layer.Layer< if (!value) return next = value if (selected.get(entry.providerID) !== entry || active.get(entry.providerID) !== entry) return - if (retryable(next)) continue + if (entry.providerID === "bharatcode" ? BharatcodeCatalog.retryable(next) : retryable(next)) continue return } }).pipe(Effect.ensuring(Effect.sync(() => (entry.recovery = undefined))), Effect.forkIn(scope)) diff --git a/packages/opencode/src/provider/models.ts b/packages/opencode/src/provider/models.ts index 1cd7bc23..5f88125d 100644 --- a/packages/opencode/src/provider/models.ts +++ b/packages/opencode/src/provider/models.ts @@ -62,11 +62,12 @@ export const layer: Layer.Layer Effect.succeed({}))) + // Let the cache resolve config so retries can detect endpoint changes; + // a captured baseURL override would pin recovery to the old endpoint. + const models = yield* cache.fetch("bharatcode").pipe(Effect.catch(() => Effect.succeed({}))) providers.bharatcode = { id: "bharatcode", name: "BharatCode", @@ -75,8 +76,8 @@ export const layer: Layer.Layer + cfg.get().pipe(Effect.flatMap((config) => refreshCatalog(cache, config, ctx.params.providerID))) + // kilocode_change end + return handlers .handle("list", list) + .handle("refresh", refresh) // kilocode_change .handle("auth", auth) .handleRaw("authorize", authorizeRaw) .handle("callback", callback) diff --git a/packages/opencode/test/kilocode/provider/bharatcode-catalog-cache.test.ts b/packages/opencode/test/kilocode/provider/bharatcode-catalog-cache.test.ts new file mode 100644 index 00000000..f9c505f6 --- /dev/null +++ b/packages/opencode/test/kilocode/provider/bharatcode-catalog-cache.test.ts @@ -0,0 +1,540 @@ +import { expect, setSystemTime } from "bun:test" +import { Deferred, Effect, Fiber, Layer, Ref } from "effect" +import * as TestClock from "effect/testing/TestClock" +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/unstable/http" +import * as Core from "@opencode-ai/core/models-dev" +import * as Refresh from "@opencode-ai/core/kilocode/models-refresh" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { ModelV2 } from "@opencode-ai/core/model" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { Auth } from "../../../src/auth" +import { Config } from "../../../src/config/config" +import { InstanceState } from "../../../src/effect/instance-state" +import { Plugin } from "../../../src/plugin" +import { ModelCache } from "../../../src/provider/model-cache" +import { ModelsDev } from "../../../src/provider/models" +import { Provider } from "../../../src/provider/provider" +import { refresh } from "../../../src/kilocode/provider/catalog-refresh" +import { TestConfig } from "../../fixture/config" +import { provideInstance, testInstanceStoreLayer } from "../../fixture/fixture" +import { testEffect } from "../../lib/effect" + +const it = testEffect(testInstanceStoreLayer) +const access = Layer.mock(Auth.Service)({ get: () => Effect.succeed(undefined), all: () => Effect.succeed({}) }) +const data = (id = "available") => ({ + data: [{ id, display_name: id, context_window: 262144, max_output_tokens: 32000, metadata: { reasoning: true } }], +}) + +function layer(http = FetchHttpClient.layer, cfg = TestConfig.layer(), auth = access) { + return Layer.fresh(ModelCache.layer).pipe( + Layer.provide(http), + Layer.provide(cfg), + Layer.provide(auth), + Layer.provide(ModelCache.kiloModelsLayer), + ) +} + +function transport(respond: () => Response) { + return Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => Effect.sync(() => HttpClientResponse.fromWeb(request, respond()))), + ) +} + +function server(respond: (request: Request) => Response | Promise) { + return Effect.acquireRelease( + Effect.sync(() => Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: respond })), + (server) => Effect.promise(() => server.stop(true)), + ) +} + +it.live("uses local HTTP and retains last-good models and safe failure metadata", () => + Effect.gen(function* () { + let status = 200 + const requests: string[] = [] + const upstream = yield* server((request) => { + requests.push(new URL(request.url).pathname) + return Response.json(status === 200 ? data() : { error: "must-not-leak-secret" }, { status }) + }) + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + const options = { baseURL: `${upstream.url}v1`, apiKey: "synthetic-key" } + const good = yield* cache.fetch("bharatcode", options) + expect(good.available).toMatchObject({ name: "available", limit: { context: 262144, output: 32000 } }) + status = 503 + expect(yield* cache.refresh("bharatcode", options)).toEqual(good) + expect(yield* cache.get("bharatcode")).toEqual(good) + expect(yield* cache.getFailure("bharatcode")).toEqual({ kind: "http", status: 503 }) + expect(yield* cache.failedProviders()).toEqual(["bharatcode"]) + status = 200 + expect(yield* cache.refresh("bharatcode", options)).toEqual(good) + expect(yield* cache.getFailure("bharatcode")).toBeUndefined() + expect(requests).toEqual(["/v1/models", "/v1/models", "/v1/models"]) + }), + ).pipe(Effect.provide(layer())) + }), +) + +it.live("coalesces simultaneous manual refreshes through the real HTTP client", () => + Effect.gen(function* () { + const started = Promise.withResolvers() + const release = Promise.withResolvers() + let calls = 0 + const upstream = yield* server(async () => { + calls++ + started.resolve() + await release.promise + return Response.json(data()) + }) + const cfg = TestConfig.layer({ + get: () => Effect.succeed({ provider: { bharatcode: { options: { baseURL: String(upstream.url) } } } }), + }) + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + const first = yield* refresh(cache, {}, "bharatcode").pipe(Effect.forkChild) + yield* Effect.promise(() => started.promise) + const second = yield* refresh(cache, {}, "bharatcode").pipe(Effect.forkChild) + yield* Effect.yieldNow + release.resolve() + expect(yield* Fiber.join(first)).toBe(true) + expect(yield* Fiber.join(second)).toBe(true) + expect(calls).toBe(1) + expect(yield* refresh(cache, {}, "unknown")).toBe(false) + expect(yield* refresh(cache, { disabled_providers: ["bharatcode"] }, "bharatcode")).toBe(false) + expect(calls).toBe(1) + }), + ).pipe(Effect.provide(layer(FetchHttpClient.layer, cfg))) + }), +) + +it.live("coalesces a second refresh while the first result is validating its account", () => + Effect.gen(function* () { + const started = yield* Deferred.make() + const release = yield* Deferred.make() + let resolutions = 0 + let calls = 0 + const cfg = TestConfig.layer({ + get: () => + Effect.gen(function* () { + resolutions++ + if (resolutions === 2) { + yield* Deferred.succeed(started, undefined) + yield* Deferred.await(release) + } + return {} + }), + }) + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + const first = yield* cache.refresh("bharatcode").pipe(Effect.forkChild) + yield* Deferred.await(started) + const second = yield* cache.refresh("bharatcode").pipe(Effect.forkChild) + yield* Effect.yieldNow + yield* Deferred.succeed(release, undefined) + expect(Object.keys(yield* Fiber.join(first))).toEqual(["available"]) + expect(Object.keys(yield* Fiber.join(second))).toEqual(["available"]) + expect(calls).toBe(1) + }), + ).pipe( + Effect.provide( + layer( + transport(() => { + calls++ + return Response.json(data()) + }), + cfg, + ), + ), + ) + }), +) + +for (const status of [401, 403, 404]) { + it.effect(`does not automatically retry HTTP ${status}`, () => + Effect.gen(function* () { + let calls = 0 + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + yield* cache.fetch("bharatcode") + yield* TestClock.adjust("1 hour") + expect(calls).toBe(1) + expect(yield* cache.getFailure("bharatcode")).toEqual({ + kind: status === 404 ? "http" : "unauthorized", + status, + }) + }), + ).pipe( + Effect.provide( + layer( + transport(() => { + calls++ + return new Response("private upstream response", { status }) + }), + ), + ), + ) + }), + ) +} + +it.effect("bounds background retries and polling cannot restart the budget", () => + Effect.gen(function* () { + let calls = 0 + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + yield* cache.fetch("bharatcode") + for (const seconds of [1, 2, 4, 8, 16]) yield* TestClock.adjust(`${seconds} seconds`) + expect(calls).toBe(6) + for (let n = 0; n < 5; n++) yield* cache.fetch("bharatcode") + yield* TestClock.adjust("1 hour") + expect(calls).toBe(6) + expect(yield* refresh(cache, {}, "bharatcode")).toBe(false) + expect(calls).toBe(7) + yield* TestClock.adjust("1 second") + expect(calls).toBe(8) + yield* cache.clear("bharatcode") + yield* TestClock.adjust("1 hour") + expect(calls).toBe(8) + expect(yield* cache.getFailure("bharatcode")).toBeUndefined() + }), + ).pipe( + Effect.provide( + layer( + transport(() => { + calls++ + return new Response(null, { status: 503 }) + }), + ), + ), + ) + }), +) + +it.effect("honors Retry-After for automatic and manual refresh", () => + Effect.gen(function* () { + let calls = 0 + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + yield* cache.fetch("bharatcode") + expect(yield* refresh(cache, {}, "bharatcode")).toBe(false) + yield* TestClock.adjust("119 seconds") + expect(calls).toBe(1) + yield* TestClock.adjust("1 second") + expect(calls).toBe(2) + expect(Object.keys((yield* cache.get("bharatcode")) ?? {})).toEqual(["available"]) + expect(yield* cache.getFailure("bharatcode")).toBeUndefined() + }), + ).pipe( + Effect.provide( + layer( + transport(() => { + calls++ + return calls === 1 + ? new Response(null, { status: 429, headers: { "Retry-After": "120" } }) + : Response.json(data()) + }), + ), + ), + ) + }), +) + +it.effect("recovers empty catalogs but reports malformed JSON and schemas without retrying", () => + Effect.gen(function* () { + let calls = 0 + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + yield* cache.fetch("bharatcode") + expect(yield* cache.getFailure("bharatcode")).toEqual({ kind: "schema" }) + yield* TestClock.adjust("1 second") + expect(Object.keys((yield* cache.get("bharatcode")) ?? {})).toEqual(["available"]) + yield* cache.refresh("bharatcode") + yield* TestClock.adjust("1 hour") + expect(calls).toBe(3) + expect(yield* cache.getFailure("bharatcode")).toEqual({ kind: "schema" }) + yield* cache.refresh("bharatcode") + yield* TestClock.adjust("1 hour") + expect(calls).toBe(4) + expect(yield* cache.getFailure("bharatcode")).toEqual({ kind: "schema" }) + }), + ).pipe( + Effect.provide( + layer( + transport(() => { + calls++ + if (calls === 1) return Response.json({ data: [] }) + if (calls === 2) return Response.json(data()) + if (calls === 3) return new Response("not JSON: private token") + return Response.json({ data: [{ id: 123 }] }) + }), + ), + ), + ) + }), +) + +for (const cooldown of [false, true]) { + it.effect(`preserves ${cooldown ? "Retry-After" : "last-good models"} beyond the normal cache TTL`, () => + Effect.gen(function* () { + const time = Date.now() + yield* Effect.addFinalizer(() => Effect.sync(() => setSystemTime())) + let calls = 0 + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + const good = yield* cache.fetch("bharatcode") + if (cooldown) yield* cache.refresh("bharatcode") + setSystemTime(time + 360000) + yield* TestClock.adjust("6 minutes") + expect(yield* cache.fetch("bharatcode")).toEqual(good) + expect(calls).toBe(2) + expect(yield* cache.getFailure("bharatcode")).toMatchObject({ kind: "http", status: 503 }) + }), + ).pipe( + Effect.provide( + layer( + transport(() => { + calls++ + return calls === 1 + ? Response.json(data()) + : new Response(null, { + status: 503, + headers: cooldown ? { "Retry-After": "3600" } : {}, + }) + }), + ), + ), + ) + }), + ) +} + +it.live("isolates credentials and endpoints and rejects late results after switch or clear", () => + Effect.gen(function* () { + const started = Promise.withResolvers() + const release = Promise.withResolvers() + const requests: Array<{ path: string; key: string | null }> = [] + const upstream = yield* server(async (request) => { + const path = new URL(request.url).pathname + const key = request.headers.get("authorization") + requests.push({ path, key }) + if (path === "/old/models") { + started.resolve() + await release.promise + } + return Response.json(data(path === "/old/models" ? "old" : key === "Bearer second" ? "second" : "first")) + }) + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + const pending = yield* cache + .fetch("bharatcode", { baseURL: `${upstream.url}old`, apiKey: "first" }) + .pipe(Effect.forkChild) + yield* Effect.promise(() => started.promise) + const options = { baseURL: `${upstream.url}new`, apiKey: "second" } + expect(Object.keys(yield* cache.fetch("bharatcode", options))).toEqual(["second"]) + release.resolve() + yield* Fiber.join(pending) + expect(Object.keys((yield* cache.get("bharatcode")) ?? {})).toEqual(["second"]) + expect(Object.keys(yield* cache.fetch("bharatcode", { ...options, apiKey: "first" }))).toEqual(["first"]) + yield* cache.clear("bharatcode") + expect(yield* cache.get("bharatcode")).toBeUndefined() + expect(requests).toEqual([ + { path: "/old/models", key: "Bearer first" }, + { path: "/new/models", key: "Bearer second" }, + { path: "/new/models", key: "Bearer first" }, + ]) + }), + ).pipe(Effect.provide(layer())) + }), +) + +it.effect("stops obsolete retries when OAuth account changes without another catalog caller", () => + Effect.gen(function* () { + let calls = 0 + const account = yield* Ref.make("first") + const auth = Layer.mock(Auth.Service)({ + get: () => + Ref.get(account).pipe( + Effect.map( + (token) => + new Auth.Oauth({ + type: "oauth", + access: token, + refresh: "synthetic-refresh", + expires: Date.now() + 3600000, + }), + ), + ), + }) + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + yield* cache.fetch("bharatcode") + yield* Ref.set(account, "second") + yield* TestClock.adjust("1 hour") + expect(calls).toBe(1) + expect(Object.keys(yield* cache.fetch("bharatcode"))).toEqual(["available"]) + expect(calls).toBe(2) + expect(yield* cache.getFailure("bharatcode")).toBeUndefined() + }), + ).pipe( + Effect.provide( + layer( + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + expect(request.headers.authorization).toBeUndefined() + calls++ + return HttpClientResponse.fromWeb( + request, + calls === 1 ? new Response(null, { status: 503 }) : Response.json(data()), + ) + }), + ), + ), + TestConfig.layer(), + auth, + ), + ), + ) + }), +) + +it.live("does not restore an in-flight catalog after clearing it", () => + Effect.gen(function* () { + const started = Promise.withResolvers() + const release = Promise.withResolvers() + const upstream = yield* server(async () => { + started.resolve() + await release.promise + return Response.json(data()) + }) + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + const pending = yield* cache.fetch("bharatcode", { baseURL: String(upstream.url) }).pipe(Effect.forkChild) + yield* Effect.promise(() => started.promise) + yield* cache.clear("bharatcode") + release.resolve() + expect(yield* Fiber.join(pending)).toEqual({}) + expect(yield* cache.get("bharatcode")).toBeUndefined() + expect(yield* cache.getFailure("bharatcode")).toBeUndefined() + }), + ).pipe(Effect.provide(layer())) + }), +) + +it.effect("stops obsolete retries when the configured endpoint changes", () => + Effect.gen(function* () { + const endpoint = yield* Ref.make("https://first.example/v1") + const requests: string[] = [] + const cfg = TestConfig.layer({ + get: () => + Ref.get(endpoint).pipe(Effect.map((baseURL) => ({ provider: { bharatcode: { options: { baseURL } } } }))), + }) + const http = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + requests.push(request.url) + return HttpClientResponse.fromWeb( + request, + requests.length === 1 ? new Response(null, { status: 503 }) : Response.json(data()), + ) + }), + ), + ) + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + yield* cache.fetch("bharatcode") + yield* Ref.set(endpoint, "https://second.example/v1") + yield* TestClock.adjust("1 hour") + expect(requests).toEqual(["https://first.example/v1/models"]) + expect(Object.keys(yield* cache.fetch("bharatcode"))).toEqual(["available"]) + expect(requests).toEqual(["https://first.example/v1/models", "https://second.example/v1/models"]) + }), + ).pipe(Effect.provide(layer(http, cfg))) + }), +) + +it.live("classifies a real local connection failure as network without leaking credentials", () => + Effect.gen(function* () { + const upstream = yield* server(() => Response.json(data())) + const url = String(upstream.url) + yield* Effect.promise(() => upstream.stop(true)) + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + expect(yield* cache.fetch("bharatcode", { baseURL: url, apiKey: "must-not-leak" })).toEqual({}) + expect(yield* cache.getFailure("bharatcode")).toEqual({ kind: "network" }) + }), + ).pipe(Effect.provide(layer())) + }), +) + +it.effect("bounds the request timeout and exposes network failure", () => + Effect.gen(function* () { + const started = yield* Deferred.make() + const http = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never))), + ) + yield* ModelCache.Service.use((cache) => + Effect.gen(function* () { + const pending = yield* cache.fetch("bharatcode").pipe(Effect.forkChild) + yield* Deferred.await(started) + yield* TestClock.adjust("10 seconds") + expect(yield* Fiber.join(pending)).toEqual({}) + expect(yield* cache.getFailure("bharatcode")).toEqual({ kind: "network" }) + yield* cache.clear("bharatcode") + }), + ).pipe(Effect.provide(layer(http))) + }), +) + +it.effect("rebuilds initialized provider state after recovery without disposing unrelated state or work", () => + Effect.gen(function* () { + let calls = 0 + const notifications = yield* Ref.make(0) + yield* Refresh.watch(() => Ref.update(notifications, (count) => count + 1)) + const cfg = TestConfig.layer({ + get: () => Effect.succeed({ enabled_providers: ["bharatcode"], provider: { bharatcode: {} } }), + }) + const cache = layer( + transport(() => (++calls === 1 ? new Response(null, { status: 503 }) : Response.json(data()))), + cfg, + ) + const models = ModelsDev.layer.pipe( + Layer.provide(cache), + Layer.provide(cfg), + Layer.provide(access), + Layer.provide(Layer.mock(Core.Service)({ get: () => Effect.succeed({}), refresh: () => Effect.void })), + ) + const graph = LayerNode.compile(Provider.node, [ + [ModelsDev.node, models], + [Config.node, cfg], + [Auth.node, access], + [Plugin.node, Layer.mock(Plugin.Service)({ list: () => Effect.succeed([]) })], + ]) + yield* Effect.gen(function* () { + const sentinel = yield* InstanceState.make(() => Effect.succeed({ marker: Symbol() })) + const original = yield* InstanceState.get(sentinel) + const stopped = yield* Ref.make(false) + const started = yield* Deferred.make() + yield* Deferred.succeed(started, undefined).pipe( + Effect.andThen(Effect.never), + Effect.ensuring(Ref.set(stopped, true)), + Effect.forkChild, + ) + yield* Deferred.await(started) + const provider = yield* Provider.Service + const id = ProviderV2.ID.make("bharatcode") + const model = ModelV2.ID.make("available") + expect((yield* provider.list())[id]).toBeUndefined() + expect(calls).toBe(1) + yield* TestClock.adjust("1 second") + expect(calls).toBe(2) + expect(yield* Ref.get(notifications)).toBe(1) + expect(yield* provider.getModel(id, model)).toMatchObject({ id: "available", providerID: "bharatcode" }) + expect(yield* InstanceState.get(sentinel)).toBe(original) + expect(yield* Ref.get(stopped)).toBe(false) + }).pipe(Effect.provide(graph), provideInstance(process.cwd())) + }), +) diff --git a/packages/opencode/test/kilocode/provider/bharatcode-catalog.test.ts b/packages/opencode/test/kilocode/provider/bharatcode-catalog.test.ts new file mode 100644 index 00000000..8128b181 --- /dev/null +++ b/packages/opencode/test/kilocode/provider/bharatcode-catalog.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, test } from "bun:test" +import { delay, failure, key, retain, retryable } from "../../../src/kilocode/provider/bharatcode-catalog" + +describe("BharatCode catalog recovery policy", () => { + test("classifies HTTP failures without retaining headers, URLs or response bodies", () => { + expect(failure(401)).toEqual({ kind: "unauthorized", status: 401 }) + expect(failure(403)).toEqual({ kind: "unauthorized", status: 403 }) + expect(failure(404)).toEqual({ kind: "http", status: 404 }) + expect(failure(503, "secret-token")).toEqual({ kind: "http", status: 503 }) + }) + + test("honors numeric and HTTP-date Retry-After and ignores invalid values", () => { + const now = Date.parse("2026-11-20T00:00:00Z") + expect(failure(429, "120", now).retryAfter).toBe(120) + expect(failure(503, "Fri, 20 Nov 2026 00:02:00 GMT", now).retryAfter).toBe(120) + expect(failure(503, "Thu, 19 Nov 2026 00:00:00 GMT", now).retryAfter).toBe(0) + expect(failure(503, "invalid", now).retryAfter).toBeUndefined() + expect(delay({ models: {}, error: failure(429, "86400") }, 0)).toBe(86400) + expect(delay({ models: {}, error: failure(429, "999999999") }, 0)).toBeUndefined() + expect(delay({ models: {}, error: failure(429, "9".repeat(400)) }, 0)).toBeUndefined() + }) + + test("bounds retries and distinguishes permanent, transient and empty failures", () => { + const result = { models: {}, error: failure(503) } + expect(Array.from({ length: 7 }, (_, attempt) => delay(result, attempt))).toEqual([ + 1, + 2, + 4, + 8, + 16, + undefined, + undefined, + ]) + for (const status of [408, 429, 500, 502, 503]) expect(retryable({ models: {}, error: failure(status) })).toBe(true) + for (const status of [400, 401, 403, 404]) expect(retryable({ models: {}, error: failure(status) })).toBe(false) + expect(retryable({ models: {}, error: { kind: "schema" } })).toBe(false) + expect(retryable({ models: {}, error: { kind: "schema" }, empty: true })).toBe(true) + }) + + test("keeps last-good models only for recoverable failures", () => { + const models = { + good: { + id: "good", + name: "Good", + release_date: "", + attachment: false, + reasoning: false, + temperature: true, + tool_call: true, + limit: { context: 128000, output: 4096 }, + }, + } + expect(retain({ models: {}, error: failure(503) }, models).models).toBe(models) + expect(retain({ models: {}, error: { kind: "network" } }, models).models).toBe(models) + expect(retain({ models: {}, error: { kind: "schema" }, empty: true }, models).models).toBe(models) + expect(retain({ models: {}, error: failure(401) }, models).models).toEqual({}) + }) + + test("scopes cache identity to normalized endpoint, API key and OAuth account", () => { + const options = { baseURL: "https://catalog.example/v1", apiKey: "secret", catalogAccount: "account-a" } + expect(key(options)).toBe(key({ ...options, baseURL: `${options.baseURL}/` })) + expect(key(options)).not.toBe(key({ ...options, apiKey: "other" })) + expect(key(options)).not.toBe(key({ ...options, baseURL: "https://other.example/v1" })) + expect(key(options)).not.toBe(key({ ...options, catalogAccount: "account-b" })) + expect(key(options)).not.toContain("secret") + }) +}) diff --git a/packages/opencode/test/kilocode/provider/catalog-refresh-route.test.ts b/packages/opencode/test/kilocode/provider/catalog-refresh-route.test.ts new file mode 100644 index 00000000..4b9c118c --- /dev/null +++ b/packages/opencode/test/kilocode/provider/catalog-refresh-route.test.ts @@ -0,0 +1,129 @@ +import { expect } from "bun:test" +import { Effect, Fiber, Layer } from "effect" +import { HttpClientResponse } from "effect/unstable/http" +import { createServer } from "node:http" +import { once } from "node:events" +import { GlobalBus, type GlobalEvent } from "../../../src/bus/global" +import { Provider } from "../../../src/provider/provider" +import { resetDatabase } from "../../fixture/db" +import { tmpdirScoped } from "../../fixture/fixture" +import { testEffect } from "../../lib/effect" +import { httpApiLayer, requestInDirectory } from "../../server/httpapi-layer" + +const state = Layer.effectDiscard( + Effect.acquireRelease( + Effect.promise(() => resetDatabase()), + () => Effect.promise(() => resetDatabase()), + ), +) +const it = testEffect(Layer.mergeAll(state, httpApiLayer)) + +it.live( + "POST refresh repairs a 503 catalog on the same backend before returning, without instance disposal", + () => + Effect.gen(function* () { + let healthy = false + let calls = 0 + const started = Promise.withResolvers() + const release = Promise.withResolvers() + const upstream = yield* Effect.acquireRelease( + Effect.promise(async () => { + const server = createServer(async (request, response) => { + if (request.url !== "/v1/models") { + response.writeHead(404).end() + return + } + calls++ + if (!healthy) { + response.writeHead(503, { "content-type": "application/json" }).end('{"error":"synthetic-secret"}') + return + } + started.resolve() + await release.promise + response.writeHead(200, { "content-type": "application/json" }).end( + JSON.stringify({ + data: [ + { id: "recovered", display_name: "Recovered", context_window: 262144, max_output_tokens: 32000 }, + ], + }), + ) + }) + server.listen(0, "127.0.0.1") + await once(server, "listening") + return server + }), + (server) => + Effect.promise(async () => { + release.resolve() + const closed = Promise.withResolvers() + server.close(() => closed.resolve()) + server.closeAllConnections() + await closed.promise + }), + ) + const address = upstream.address() + if (!address || typeof address === "string") throw new Error("Missing local catalog listener") + const directory = yield* tmpdirScoped({ + git: true, + config: { + enabled_providers: ["bharatcode"], + formatter: false, + lsp: false, + provider: { bharatcode: { options: { baseURL: `http://127.0.0.1:${address.port}/v1` } } }, + }, + }) + const auth = yield* requestInDirectory("/auth/bharatcode", directory, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ type: "api", key: "synthetic-catalog-key" }), + }) + expect(auth.status).toBe(200) + yield* Effect.addFinalizer(() => + requestInDirectory("/auth/bharatcode", directory, { method: "DELETE" }).pipe(Effect.ignore), + ) + + const events: GlobalEvent[] = [] + const listen = (event: GlobalEvent) => { + events.push(event) + } + GlobalBus.on("event", listen) + yield* Effect.addFinalizer(() => + Effect.sync(() => { + GlobalBus.off("event", listen) + }), + ) + + const initial = yield* requestInDirectory("/provider", directory).pipe( + Effect.flatMap(HttpClientResponse.schemaBodyJson(Provider.ListResult)), + ) + expect(initial.failed).toContain("bharatcode") + expect(initial.failures).toContainEqual({ providerID: "bharatcode", kind: "http", status: 503 }) + expect(initial.all.find((provider) => provider.id === "bharatcode")?.models).toEqual({}) + expect(JSON.stringify(initial.failures)).not.toContain("synthetic-secret") + + healthy = true + const first = yield* requestInDirectory("/provider/bharatcode/refresh", directory, { method: "POST" }).pipe( + Effect.forkChild, + ) + yield* Effect.promise(() => started.promise) + release.resolve() + const response = yield* Fiber.join(first) + expect(response.status).toBe(200) + expect(yield* response.json).toBe(true) + const recovered = yield* requestInDirectory("/provider", directory).pipe( + Effect.flatMap(HttpClientResponse.schemaBodyJson(Provider.ListResult)), + ) + expect(recovered.failed).not.toContain("bharatcode") + expect(recovered.failures.find((failure) => failure.providerID === "bharatcode")).toBeUndefined() + expect(recovered.connected).toContain("bharatcode") + expect(Object.keys(recovered.all.find((provider) => provider.id === "bharatcode")?.models ?? {})).toEqual([ + "recovered", + ]) + expect(calls).toBe(2) + expect(events.filter((event) => event.payload.type === "server.instance.disposed")).toEqual([]) + const unsupported = yield* requestInDirectory("/provider/unknown/refresh", directory, { method: "POST" }) + expect(yield* unsupported.json).toBe(false) + expect(calls).toBe(2) + }), + 30_000, +) diff --git a/packages/opencode/test/plugin/bharatcode.test.ts b/packages/opencode/test/plugin/bharatcode.test.ts index 5d4ef8ae..fa4c477d 100644 --- a/packages/opencode/test/plugin/bharatcode.test.ts +++ b/packages/opencode/test/plugin/bharatcode.test.ts @@ -1,7 +1,16 @@ // kilocode_change - new file import { describe, expect, test } from "bun:test" import { BharatcodeAuthPlugin, buildAuthorizeUrl, generatePKCE } from "../../src/plugin/bharatcode" -import { OAUTH_DUMMY_KEY } from "../../src/auth" +import { OAUTH_DUMMY_KEY } from "../../src/auth/placeholder" + +const MODEL_URL = "https://bharatcode.ai/api/model/v1/chat/completions" +function fixtureTransport(url: () => URL) { + return async (destination: RequestInfo | URL, init: RequestInit) => { + expect(String(destination)).toBe(MODEL_URL) + expect(init.redirect).toBe("error") + return fetch(url(), init) + } +} const TEST_REDIRECT_PORT = 39771 const TEST_REDIRECT_URI = `http://127.0.0.1:${TEST_REDIRECT_PORT}/callback` @@ -88,7 +97,7 @@ describe("plugin.bharatcode", () => { const input = makeInput() const hooks = await BharatcodeAuthPlugin(input as any, { issuer, redirectUri: TEST_REDIRECT_URI }) const methods = hooks.auth!.methods - expect(methods.map((m) => m.type)).toEqual(["oauth", "api"]) + expect(methods.map((m) => m.type)).toEqual(["oauth"]) const oauth = methods[0] as Extract<(typeof methods)[number], { type: "oauth" }> const authorization = await oauth.authorize() @@ -154,7 +163,11 @@ describe("plugin.bharatcode", () => { }) try { const input = makeInput() - const hooks = await BharatcodeAuthPlugin(input as any, { issuer, redirectUri: TEST_REDIRECT_URI }) + const hooks = await BharatcodeAuthPlugin(input as any, { + issuer, + redirectUri: TEST_REDIRECT_URI, + modelFetch: fixtureTransport(() => apiServer.url), + }) const loader = hooks.auth!.loader! const stale = { type: "oauth", @@ -176,7 +189,9 @@ describe("plugin.bharatcode", () => { }, }) try { - const response = await (options.fetch as Function)(`${apiServer.url}chat`, { headers: {} }) + await expect((options.fetch as Function)("https://example.invalid/v1/chat")).rejects.toThrow("Unapproved") + expect(seen).toHaveLength(0) + const response = await (options.fetch as Function)(MODEL_URL, { headers: {} }) expect(response.status).toBe(200) expect(seen[0]).toBe("Bearer access-new") } finally { @@ -219,7 +234,11 @@ describe("plugin.bharatcode", () => { }) try { const input = makeInput() - const hooks = await BharatcodeAuthPlugin(input as any, { issuer, redirectUri: TEST_REDIRECT_URI }) + const hooks = await BharatcodeAuthPlugin(input as any, { + issuer, + redirectUri: TEST_REDIRECT_URI, + modelFetch: fixtureTransport(() => apiServer.url), + }) const loader = hooks.auth!.loader! const fresh = { type: "oauth", @@ -228,7 +247,7 @@ describe("plugin.bharatcode", () => { expires: Date.now() + 3_600_000, } as any const options = await loader(() => Promise.resolve(fresh), {} as any) - const response = await (options.fetch as Function)(`${apiServer.url}chat/completions`, { + const response = await (options.fetch as Function)(MODEL_URL, { method: "POST", body: JSON.stringify({ model: "m" }), headers: { "content-type": "application/json" }, diff --git a/packages/sdk/js/src/v2/gen/sdk.gen.ts b/packages/sdk/js/src/v2/gen/sdk.gen.ts index 54c0d15f..da21b6db 100644 --- a/packages/sdk/js/src/v2/gen/sdk.gen.ts +++ b/packages/sdk/js/src/v2/gen/sdk.gen.ts @@ -239,11 +239,6 @@ import type { KilocodeTeardownWorktreeResponses, KilocodeWakeupsErrors, KilocodeWakeupsResponses, - KiloEditErrors, - KiloEditResponses, - KiloFimErrors, - KiloFimResponse, - KiloFimResponses, KiloModelsImagesErrors, KiloModelsImagesResponses, KiloModelsTranscriptionsErrors, @@ -358,6 +353,8 @@ import type { ProviderOauthAuthorizeResponses, ProviderOauthCallbackErrors, ProviderOauthCallbackResponses, + ProviderRefreshErrors, + ProviderRefreshResponses, PtyConnectErrors, PtyConnectResponses, PtyConnectTokenErrors, @@ -4272,6 +4269,38 @@ export class Provider extends HeyApiClient { }) } + /** + * Refresh a provider catalog + * + * Retry the BharatCode model catalog without interrupting sessions. Returns false on failure, cooldown, or an unsupported or disabled provider. + */ + public refresh( + parameters: { + providerID: string + directory?: string + workspace?: string + }, + options?: Options, + ) { + const params = buildClientParams( + [parameters], + [ + { + args: [ + { in: "path", key: "providerID" }, + { in: "query", key: "directory" }, + { in: "query", key: "workspace" }, + ], + }, + ], + ) + return (options?.client ?? this.client).post({ + url: "/provider/{providerID}/refresh", + ...options, + ...params, + }) + } + private _oauth?: Oauth get oauth(): Oauth { return (this._oauth ??= new Oauth({ client: this.client })) @@ -7194,113 +7223,6 @@ export class Kilo extends HeyApiClient { }) } - /** - * FIM completion - * - * Proxy a Fill-in-the-Middle completion request to the Kilo Gateway - */ - public fim( - parameters: { - directory?: string - workspace?: string - prefix: string - suffix: string - provider?: string - model?: string - maxTokens?: number - temperature?: number - }, - options?: Options, - ) { - const params = buildClientParams( - [parameters], - [ - { - args: [ - { in: "query", key: "directory" }, - { in: "query", key: "workspace" }, - { in: "body", key: "prefix" }, - { in: "body", key: "suffix" }, - { in: "body", key: "provider" }, - { in: "body", key: "model" }, - { in: "body", key: "maxTokens" }, - { in: "body", key: "temperature" }, - ], - }, - ], - ) - return (options?.client ?? this.client).sse.post({ - url: "/kilo/fim", - ...options, - ...params, - headers: { - "Content-Type": "application/json", - ...options?.headers, - ...params.headers, - }, - }) - } - - /** - * Next Edit completion - * - * Proxy a Mercury-style Next Edit request. The client supplies structured editor context; the gateway assembles the sentinel-tagged prompt and forwards to the upstream edit endpoint. - */ - public edit( - parameters: { - directory?: string - workspace?: string - provider?: string - model?: string - maxTokens?: number - currentFilePath: string - currentFileContent: string - cursorLine: number - cursorCharacter: number - editableRegionStartLine: number - editableRegionEndLine: number - recentlyViewedSnippets: Array<{ - filepath: string - content: string - }> - editDiffHistory: Array - }, - options?: Options, - ) { - const params = buildClientParams( - [parameters], - [ - { - args: [ - { in: "query", key: "directory" }, - { in: "query", key: "workspace" }, - { in: "body", key: "provider" }, - { in: "body", key: "model" }, - { in: "body", key: "maxTokens" }, - { in: "body", key: "currentFilePath" }, - { in: "body", key: "currentFileContent" }, - { in: "body", key: "cursorLine" }, - { in: "body", key: "cursorCharacter" }, - { in: "body", key: "editableRegionStartLine" }, - { in: "body", key: "editableRegionEndLine" }, - { in: "body", key: "recentlyViewedSnippets" }, - { in: "body", key: "editDiffHistory" }, - ], - }, - ], - ) - return (options?.client ?? this.client).post({ - url: "/kilo/edit", - ...options, - ...params, - headers: { - "Content-Type": "application/json", - ...options?.headers, - ...params.headers, - }, - }) - } - /** * Get Kilo notifications * diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index b847114e..42cfc5db 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -13451,6 +13451,36 @@ export type ProviderAuthResponses = { export type ProviderAuthResponse = ProviderAuthResponses[keyof ProviderAuthResponses] +export type ProviderRefreshData = { + body?: never + path: { + providerID: string + } + query?: { + directory?: string + workspace?: string + } + url: "/provider/{providerID}/refresh" +} + +export type ProviderRefreshErrors = { + /** + * Bad request + */ + 400: BadRequestError +} + +export type ProviderRefreshError = ProviderRefreshErrors[keyof ProviderRefreshErrors] + +export type ProviderRefreshResponses = { + /** + * Whether the provider catalog refreshed successfully + */ + 200: boolean +} + +export type ProviderRefreshResponse = ProviderRefreshResponses[keyof ProviderRefreshResponses] + export type ProviderOauthAuthorizeData = { body?: { /** @@ -16542,102 +16572,6 @@ export type KiloModesResponses = { export type KiloModesResponse = KiloModesResponses[keyof KiloModesResponses] -export type KiloFimData = { - body?: { - prefix: string - suffix: string - provider?: string - model?: string - maxTokens?: number - temperature?: number - } - path?: never - query?: { - directory?: string - workspace?: string - } - url: "/kilo/fim" -} - -export type KiloFimErrors = { - /** - * BadRequest | InvalidRequestError - */ - 400: EffectHttpApiErrorBadRequest | InvalidRequestError -} - -export type KiloFimError = KiloFimErrors[keyof KiloFimErrors] - -export type KiloFimResponses = { - /** - * Streaming FIM completion response - */ - 200: { - choices?: Array<{ - delta?: { - content?: string - } - text?: string - }> - usage?: { - prompt_tokens?: number - completion_tokens?: number - } - cost?: number - } -} - -export type KiloFimResponse = KiloFimResponses[keyof KiloFimResponses] - -export type KiloEditData = { - body?: { - provider?: string - model?: string - maxTokens?: number - currentFilePath: string - currentFileContent: string - cursorLine: number - cursorCharacter: number - editableRegionStartLine: number - editableRegionEndLine: number - recentlyViewedSnippets: Array<{ - filepath: string - content: string - }> - editDiffHistory: Array - } - path?: never - query?: { - directory?: string - workspace?: string - } - url: "/kilo/edit" -} - -export type KiloEditErrors = { - /** - * BadRequest | InvalidRequestError - */ - 400: EffectHttpApiErrorBadRequest | InvalidRequestError -} - -export type KiloEditError = KiloEditErrors[keyof KiloEditErrors] - -export type KiloEditResponses = { - /** - * Next Edit completion - */ - 200: { - content: string - usage?: { - prompt_tokens?: number - completion_tokens?: number - } - } -} - -export type KiloEditResponse = KiloEditResponses[keyof KiloEditResponses] - export type KiloAudioTranscriptionsData = { body?: { model: string diff --git a/script/check-workflows.ts b/script/check-workflows.ts index c973224e..56191707 100644 --- a/script/check-workflows.ts +++ b/script/check-workflows.ts @@ -30,7 +30,7 @@ const DIR = path.join(ROOT, ".github", "workflows") // the lab), and release (auto-cut + 8-platform vsix build + GitHub release // on every bc/main push). Upstream merge must not silently add more: add // here only after review. -const active = new Set(["checks.yml", "typecheck.yml", "release.yml"]) +const active = new Set(["checks.yml", "typecheck.yml", "release.yml", "oauth-candidate.yml"]) // GitHub picks up both .yml and .yaml in .github/workflows/. We accept both so // an upstream `.yaml` addition also shows up as unexpected drift.