Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-multi-project-session-scope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Speed up local VS Code snapshot installs and scope Agent Manager session events and Git status to the active project, including edits inside nested repositories.
1 change: 1 addition & 0 deletions packages/kilo-vscode/.vscodeignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ AGENTS.md
# not ship in the VSIX, otherwise production installs are detected as local
# builds and may inject a dev-only bwrap fallback (see ServerManager.localCli).
bin/.cli-version
bin/.ffmpeg-target

# Include WAV assets used by extension-host notification playback
!audio-wav/**
59 changes: 37 additions & 22 deletions packages/kilo-vscode/script/dev-snapshot.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env bun
import { $ } from "bun"
import { createRequire } from "node:module"
import { join, dirname } from "node:path"
import { tmpdir } from "node:os"
import { rmSync, mkdirSync, existsSync } from "node:fs"
Expand All @@ -26,37 +27,51 @@ console.log(`Commit: ${sha}`)
console.log(`Mode: ${mode}\n`)

console.log("🧹 Cleaning build directories...")
for (const dir of ["bin", "dist"]) {
const dirPath = join(root, dir)
if (existsSync(dirPath)) {
rmSync(dirPath, { recursive: true, force: true })
console.log(` ✓ Cleaned ${dir}/`)
}
const dist = join(root, "dist")
if (existsSync(dist)) {
rmSync(dist, { recursive: true, force: true })
console.log(" ✓ Cleaned dist/")
}

const outDir = join(tmpdir(), "kilo-vscode-snapshots")
mkdirSync(outDir, { recursive: true })

console.log("\n📦 Rebuilding SDK...")
await $`bun run --cwd ../sdk/js build`.cwd(root)
console.log("\n📦 Preparing SDK...")
await $`bun run prepare:sdk`.cwd(root)

console.log("\n🔧 Preparing CLI binary...")
await $`bun script/local-bin.ts --force`.cwd(root)

console.log("\n✅ Type-checking...")
await $`bun run typecheck`.cwd(root)

console.log("\n🔍 Linting...")
await $`bun run lint`.cwd(root)

console.log("\n🏗️ Building extension...")
await $`node ${join(root, "esbuild.js")} --production`.cwd(root)
console.log("\n🔧 Preparing CLI binary and validating extension...")
await $`bun script/local-bin.ts --compiled`.cwd(root)
await $`bun run build:check:production`.cwd(root)

console.log("\n📦 Packaging VSIX...")
const vsixPath = join(outDir, `kilo-vscode-snapshot-${sha}-${user}.vsix`)
await $`bunx vsce package ${snapshotVersion} --no-update-package-json --no-dependencies --skip-license -o ${vsixPath}`.cwd(
root,
)
const require = createRequire(import.meta.url)
const zlib = require("node:zlib") as typeof import("node:zlib")
const DeflateRaw = zlib.DeflateRaw
if (shouldInstall) {
// Local installs favor fast packaging and extraction over archive size.
Object.defineProperty(zlib, "DeflateRaw", {
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
value: function (options?: ConstructorParameters<typeof DeflateRaw>[0]) {
return new DeflateRaw({ ...options, level: 0 })
},
})
}
const { createVSIX } = await import("@vscode/vsce")
const marker = join(root, "bin", ".cli-version")
const cache = existsSync(marker) ? await Bun.file(marker).text() : undefined
if (cache !== undefined) rmSync(marker)
try {
await createVSIX({
cwd: root,
packagePath: vsixPath,
version: snapshotVersion,
updatePackageJson: false,
dependencies: false,
skipLicense: true,
})
} finally {
if (cache !== undefined) await Bun.write(marker, cache)
}

if (shouldInstall) {
const execPath = process.env.VSCODE_EXEC_PATH ?? ""
Expand Down
4 changes: 3 additions & 1 deletion packages/kilo-vscode/script/ffmpeg-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ export async function ensureFfmpegForTarget(target: string, bin: string): Promis

const exe = target.startsWith("win32") ? "ffmpeg.exe" : "ffmpeg"
const dest = join(bin, exe)
if (existsSync(dest)) return
const marker = join(bin, ".ffmpeg-target")
if (existsSync(dest) && existsSync(marker) && (await Bun.file(marker).text()).trim() === target) return

const tmp = join(bin, ".ffmpeg-tmp")
rmSync(tmp, { recursive: true, force: true })
Expand All @@ -37,6 +38,7 @@ export async function ensureFfmpegForTarget(target: string, bin: string): Promis
await $`tar -xzf ${join(tmp, name)} -C ${tmp}`.quiet()
copyFileSync(join(tmp, "package", exe), dest)
if (!target.startsWith("win32")) chmodSync(dest, 0o755)
await Bun.write(marker, `${target}\n`)
} finally {
rmSync(tmp, { recursive: true, force: true })
}
Expand Down
153 changes: 113 additions & 40 deletions packages/kilo-vscode/script/local-bin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env bun
import { $ } from "bun"
import { createHash } from "node:crypto"
import { join, relative, dirname, basename } from "node:path"
import { chmodSync, statSync, rmSync, readdirSync, existsSync } from "node:fs"
import {
Expand All @@ -15,6 +16,7 @@ import { currentBwrapTarget, ensureBwrapForTarget } from "./bwrap-helper"
import { currentFfmpegTarget, ensureFfmpegForTarget } from "./ffmpeg-helper"

const forceRebuild = process.argv.includes("--force")
const compiledOnly = process.argv.includes("--compiled")

/**
* Ensures the VS Code extension has a CLI binary at `packages/kilo-vscode/bin/kilo`.
Expand All @@ -32,10 +34,8 @@ const kiloVscodeDir = join(import.meta.dir, "..")
const packagesDir = join(kiloVscodeDir, "..")
const repoDir = join(packagesDir, "..")
const opencodeDir = join(packagesDir, "opencode")
const coreDir = join(packagesDir, "core")
const gatewayDir = join(packagesDir, "kilo-gateway")
const indexingDir = join(packagesDir, "kilo-indexing")
const sandboxDir = join(packagesDir, "kilo-sandbox")
const rootFile = join(repoDir, "package.json")

const targetBinDir = join(kiloVscodeDir, "bin")
const binName = process.platform === "win32" ? "kilo.exe" : "kilo"
Expand All @@ -46,50 +46,123 @@ function log(msg: string) {
console.log(`[local-bin] ${msg}`)
}

async function cliSourceHash(): Promise<string | null> {
try {
const opencodeResult = await $`git log -1 --format=%H -- .`.cwd(opencodeDir).quiet()
const coreResult = await $`git log -1 --format=%H -- .`.cwd(coreDir).quiet()
const gatewayResult = await $`git log -1 --format=%H -- .`.cwd(gatewayDir).quiet()
const indexingResult = await $`git log -1 --format=%H -- .`.cwd(indexingDir).quiet()
const sandboxResult = await $`git log -1 --format=%H -- .`.cwd(sandboxDir).quiet()
return `${opencodeResult.text().trim()}-${coreResult.text().trim()}-${gatewayResult.text().trim()}-${indexingResult.text().trim()}-${sandboxResult.text().trim()}`
} catch {
return null
}
type Package = {
name?: string
workspaces?: string[] | { packages?: string[] }
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
optionalDependencies?: Record<string, string>
peerDependencies?: Record<string, string>
}

async function isDirty(): Promise<boolean> {
try {
const opencodeResult = await $`git status --porcelain -- .`.cwd(opencodeDir).quiet()
const coreResult = await $`git status --porcelain -- .`.cwd(coreDir).quiet()
const gatewayResult = await $`git status --porcelain -- .`.cwd(gatewayDir).quiet()
const indexingResult = await $`git status --porcelain -- .`.cwd(indexingDir).quiet()
const sandboxResult = await $`git status --porcelain -- .`.cwd(sandboxDir).quiet()
return (
opencodeResult.text().trim().length > 0 ||
coreResult.text().trim().length > 0 ||
gatewayResult.text().trim().length > 0 ||
indexingResult.text().trim().length > 0 ||
sandboxResult.text().trim().length > 0
async function cliInputs() {
const root: Package = await Bun.file(rootFile).json()
const workspaces = Array.isArray(root.workspaces) ? root.workspaces : (root.workspaces?.packages ?? [])
const files = (
await Promise.all(
workspaces.map((pattern) =>
Array.fromAsync(new Bun.Glob(`${pattern}/package.json`).scan({ cwd: repoDir, onlyFiles: true })),
),
)
} catch {
return false
).flat()
const entries = await Promise.all(
files.map(async (file) => ({ file, pkg: (await Bun.file(join(repoDir, file)).json()) as Package })),
)
const packages = new Map(entries.flatMap((entry) => (entry.pkg.name ? [[entry.pkg.name, entry] as const] : [])))
const dirs = new Set<string>()

function visit(name: string) {
const entry = packages.get(name)
if (!entry) return
const dir = dirname(entry.file)
if (dirs.has(dir)) return
dirs.add(dir)
const deps = {
...entry.pkg.dependencies,
...entry.pkg.devDependencies,
...entry.pkg.optionalDependencies,
...entry.pkg.peerDependencies,
}
for (const dep of Object.keys(deps)) visit(dep)
}

// The CLI build embeds the console even though it is not a package dependency.
for (const dir of [opencodeDir, join(packagesDir, "kilo-console")]) {
const pkg: Package = await Bun.file(join(dir, "package.json")).json()
if (!pkg.name) throw new Error(`Workspace package at ${dir} has no name`)
visit(pkg.name)
}

return [
relative(repoDir, rootFile),
"bun.lock",
"patches",
...[...dirs].sort(),
"packages/kilo-vscode/script/bwrap-helper.ts",
"packages/kilo-vscode/script/ffmpeg-helper.ts",
"packages/kilo-vscode/script/local-bin.ts",
"packages/kilo-vscode/src/services/cli-backend/cli-resources.ts",
]
}

async function cliSourceHash() {
const inputs = await cliInputs()
const [tree, diff, extra, branch] = await Promise.all([
$`git ls-tree -r HEAD -- ${inputs}`.cwd(repoDir).quiet(),
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
$`git diff --binary HEAD -- ${inputs}`.cwd(repoDir).quiet(),
$`git ls-files --others --exclude-standard -z -- ${inputs}`.cwd(repoDir).quiet(),
$`git branch --show-current`.cwd(repoDir).quiet(),
])
const env = Object.fromEntries(
[
"GH_REPO",
"KILO_BUMP",
"KILO_BWRAP_CACHE",
"KILO_CHANNEL",
"KILO_MODELS_URL",
"KILO_PRE_RELEASE",
"KILO_RELEASE",
"KILO_SKIP_BUNDLED_BWRAP",
"KILO_VERSION",
"MODELS_DEV_API_JSON",
"ZIG",
].map((key) => [key, process.env[key] ?? ""]),
)
const hash = createHash("sha256")
.update(tree.text())
.update(diff.text())
.update(branch.text())
.update(JSON.stringify(env))
const files = extra.text().split("\0").filter(Boolean).sort()

for (const file of files) {
hash.update(file)
hash.update(new Uint8Array(await Bun.file(join(repoDir, file)).arrayBuffer()))
}

const models = process.env.MODELS_DEV_API_JSON
if (models) hash.update(new Uint8Array(await Bun.file(models).arrayBuffer()))
return hash.digest("hex")
}

async function isStale(): Promise<boolean> {
if (await isDirty()) return true
async function isStale() {
const hash = await cliSourceHash()
if (!hash) return false // can't determine — assume fresh
try {
const stored = (await Bun.file(versionFile).text()).trim()
return stored !== hash
const stored: unknown = await Bun.file(versionFile).json()
if (!stored || typeof stored !== "object") return true
const input = Reflect.get(stored, "input")
const target = Reflect.get(stored, "target")
const kind = Reflect.get(stored, "kind")
return input !== hash || target !== platformTag() || (compiledOnly && kind !== "compiled")
} catch {
return true // no version file — treat as stale
}
}

async function writeVersion(kind: "compiled" | "wrapper") {
await Bun.write(versionFile, JSON.stringify({ input: await cliSourceHash(), target: platformTag(), kind }) + "\n")
}

function platformTag(): string {
const os = process.platform === "win32" ? "windows" : process.platform
return `cli-${os}-${process.arch}`
Expand All @@ -115,6 +188,8 @@ async function findKiloBinaryInOpencodeDist(): Promise<string | null> {
// fall through to generic search
}

if (compiledOnly) return null

// Fallback: find any dist/**/bin/kilo or kilo.exe
const queue = [distDir]
while (queue.length) {
Expand Down Expand Up @@ -214,8 +289,7 @@ async function writeSourceWrapper() {
await bundleKiloSandboxWorker()
await ensureLocalHelpers()

const hash = await cliSourceHash()
if (hash) await Bun.write(versionFile, hash + "\n")
await writeVersion("wrapper")
log(
`Compiled CLI build failed; wrote source wrapper at ${relative(kiloVscodeDir, targetBinPath)} for local development.`,
)
Expand All @@ -238,7 +312,7 @@ async function main() {
return
}

if (forceRebuild && !exists) {
if ((forceRebuild || compiledOnly) && !ready) {
removeDist()
}

Expand All @@ -256,7 +330,7 @@ async function main() {
}

const sourceBinPath = await ensureBuiltBinary().catch(async (err) => {
if (forceRebuild) throw err
if (forceRebuild || compiledOnly) throw err
await writeSourceWrapper()
log(`Wrapper fallback reason: ${err instanceof Error ? err.message : String(err)}`)
return null
Expand All @@ -270,8 +344,7 @@ async function main() {
chmodSync(targetBinPath, 0o755)
await ensureLocalHelpers()

const hash = await cliSourceHash()
if (hash) await Bun.write(versionFile, hash + "\n")
await writeVersion("compiled")

log(`Copied CLI binary from ${relative(packagesDir, sourceBinPath)} -> ${relative(kiloVscodeDir, targetBinPath)}`)
}
Expand Down
Loading
Loading